babylon.viewer.max.js 5.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. if(typeof exports === 'object' && typeof module === 'object') {
  4. module.exports = factory();
  5. } else if(typeof define === 'function' && define.amd) {
  6. define("babylonjs-viewer", amdDependencies, factory);
  7. } else if(typeof exports === 'object') {
  8. exports["babylonjs-viewer"] = factory();
  9. } else {
  10. root["BabylonViewer"] = factory();
  11. }
  12. })(this, function() {
  13. var BabylonViewer =
  14. /******/ (function(modules) { // webpackBootstrap
  15. /******/ // The module cache
  16. /******/ var installedModules = {};
  17. /******/
  18. /******/ // The require function
  19. /******/ function __webpack_require__(moduleId) {
  20. /******/
  21. /******/ // Check if module is in cache
  22. /******/ if(installedModules[moduleId]) {
  23. /******/ return installedModules[moduleId].exports;
  24. /******/ }
  25. /******/ // Create a new module (and put it into the cache)
  26. /******/ var module = installedModules[moduleId] = {
  27. /******/ i: moduleId,
  28. /******/ l: false,
  29. /******/ exports: {}
  30. /******/ };
  31. /******/
  32. /******/ // Execute the module function
  33. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  34. /******/
  35. /******/ // Flag the module as loaded
  36. /******/ module.l = true;
  37. /******/
  38. /******/ // Return the exports of the module
  39. /******/ return module.exports;
  40. /******/ }
  41. /******/
  42. /******/
  43. /******/ // expose the modules object (__webpack_modules__)
  44. /******/ __webpack_require__.m = modules;
  45. /******/
  46. /******/ // expose the module cache
  47. /******/ __webpack_require__.c = installedModules;
  48. /******/
  49. /******/ // define getter function for harmony exports
  50. /******/ __webpack_require__.d = function(exports, name, getter) {
  51. /******/ if(!__webpack_require__.o(exports, name)) {
  52. /******/ Object.defineProperty(exports, name, {
  53. /******/ configurable: false,
  54. /******/ enumerable: true,
  55. /******/ get: getter
  56. /******/ });
  57. /******/ }
  58. /******/ };
  59. /******/
  60. /******/ // getDefaultExport function for compatibility with non-harmony modules
  61. /******/ __webpack_require__.n = function(module) {
  62. /******/ var getter = module && module.__esModule ?
  63. /******/ function getDefault() { return module['default']; } :
  64. /******/ function getModuleExports() { return module; };
  65. /******/ __webpack_require__.d(getter, 'a', getter);
  66. /******/ return getter;
  67. /******/ };
  68. /******/
  69. /******/ // Object.prototype.hasOwnProperty.call
  70. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  71. /******/
  72. /******/ // __webpack_public_path__
  73. /******/ __webpack_require__.p = "";
  74. /******/
  75. /******/ // Load entry module and return exports
  76. /******/ return __webpack_require__(__webpack_require__.s = 24);
  77. /******/ })
  78. /************************************************************************/
  79. /******/ ([
  80. /* 0 */
  81. /***/ (function(module, exports, __webpack_require__) {
  82. /* WEBPACK VAR INJECTION */(function(global) {
  83. (function universalModuleDefinition(root, factory) {
  84. var amdDependencies = [];
  85. var CANNON = root.CANNON || this.CANNON;
  86. var OIMO = root.OIMO || this.OIMO;
  87. var earcut = root.earcut || this.earcut;
  88. if(true) {
  89. try { CANNON = CANNON || __webpack_require__(26); } catch(e) {}
  90. try { OIMO = OIMO || __webpack_require__(27); } catch(e) {}
  91. try { earcut = earcut || __webpack_require__(28); } catch(e) {}
  92. module.exports = factory(CANNON,OIMO,earcut);
  93. } else if(typeof define === 'function' && define.amd) {
  94. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  95. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  96. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  97. define("babylonjs", amdDependencies, factory);
  98. } else if(typeof exports === 'object') {
  99. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  100. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  101. try { earcut = earcut || require("earcut"); } catch(e) {}
  102. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  103. } else {
  104. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  105. }
  106. })(this, function(CANNON,OIMO,earcut) {
  107. CANNON = CANNON || this.CANNON;
  108. OIMO = OIMO || this.OIMO;
  109. earcut = earcut || this.earcut;
  110. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  111. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  112. var BABYLON;
  113. (function (BABYLON) {
  114. /**
  115. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  116. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  117. */
  118. var EffectFallbacks = /** @class */ (function () {
  119. function EffectFallbacks() {
  120. this._defines = {};
  121. this._currentRank = 32;
  122. this._maxRank = -1;
  123. }
  124. /**
  125. * Removes the fallback from the bound mesh.
  126. */
  127. EffectFallbacks.prototype.unBindMesh = function () {
  128. this._mesh = null;
  129. };
  130. /**
  131. * Adds a fallback on the specified property.
  132. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  133. * @param define The name of the define in the shader
  134. */
  135. EffectFallbacks.prototype.addFallback = function (rank, define) {
  136. if (!this._defines[rank]) {
  137. if (rank < this._currentRank) {
  138. this._currentRank = rank;
  139. }
  140. if (rank > this._maxRank) {
  141. this._maxRank = rank;
  142. }
  143. this._defines[rank] = new Array();
  144. }
  145. this._defines[rank].push(define);
  146. };
  147. /**
  148. * Sets the mesh to use CPU skinning when needing to fallback.
  149. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  150. * @param mesh The mesh to use the fallbacks.
  151. */
  152. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  153. this._mesh = mesh;
  154. if (rank < this._currentRank) {
  155. this._currentRank = rank;
  156. }
  157. if (rank > this._maxRank) {
  158. this._maxRank = rank;
  159. }
  160. };
  161. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  162. /**
  163. * Checks to see if more fallbacks are still availible.
  164. */
  165. get: function () {
  166. return this._currentRank <= this._maxRank;
  167. },
  168. enumerable: true,
  169. configurable: true
  170. });
  171. /**
  172. * Removes the defines that shoould be removed when falling back.
  173. * @param currentDefines defines the current define statements for the shader.
  174. * @param effect defines the current effect we try to compile
  175. * @returns The resulting defines with defines of the current rank removed.
  176. */
  177. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  178. // First we try to switch to CPU skinning
  179. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  180. this._mesh.computeBonesUsingShaders = false;
  181. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  182. effect._bonesComputationForcedToCPU = true;
  183. var scene = this._mesh.getScene();
  184. for (var index = 0; index < scene.meshes.length; index++) {
  185. var otherMesh = scene.meshes[index];
  186. if (!otherMesh.material) {
  187. continue;
  188. }
  189. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  190. continue;
  191. }
  192. if (otherMesh.material.getEffect() === effect) {
  193. otherMesh.computeBonesUsingShaders = false;
  194. }
  195. else if (otherMesh.subMeshes) {
  196. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  197. var subMesh = _a[_i];
  198. var subMeshEffect = subMesh.effect;
  199. if (subMeshEffect === effect) {
  200. otherMesh.computeBonesUsingShaders = false;
  201. break;
  202. }
  203. }
  204. }
  205. }
  206. }
  207. else {
  208. var currentFallbacks = this._defines[this._currentRank];
  209. if (currentFallbacks) {
  210. for (var index = 0; index < currentFallbacks.length; index++) {
  211. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  212. }
  213. }
  214. this._currentRank++;
  215. }
  216. return currentDefines;
  217. };
  218. return EffectFallbacks;
  219. }());
  220. BABYLON.EffectFallbacks = EffectFallbacks;
  221. /**
  222. * Options to be used when creating an effect.
  223. */
  224. var EffectCreationOptions = /** @class */ (function () {
  225. function EffectCreationOptions() {
  226. }
  227. return EffectCreationOptions;
  228. }());
  229. BABYLON.EffectCreationOptions = EffectCreationOptions;
  230. /**
  231. * Effect containing vertex and fragment shader that can be executed on an object.
  232. */
  233. var Effect = /** @class */ (function () {
  234. /**
  235. * Instantiates an effect.
  236. * An effect can be used to create/manage/execute vertex and fragment shaders.
  237. * @param baseName Name of the effect.
  238. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  239. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  240. * @param samplers List of sampler variables that will be passed to the shader.
  241. * @param engine Engine to be used to render the effect
  242. * @param defines Define statements to be added to the shader.
  243. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  244. * @param onCompiled Callback that will be called when the shader is compiled.
  245. * @param onError Callback that will be called if an error occurs during shader compilation.
  246. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  247. */
  248. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  249. if (samplers === void 0) { samplers = null; }
  250. if (defines === void 0) { defines = null; }
  251. if (fallbacks === void 0) { fallbacks = null; }
  252. if (onCompiled === void 0) { onCompiled = null; }
  253. if (onError === void 0) { onError = null; }
  254. var _this = this;
  255. /**
  256. * Unique ID of the effect.
  257. */
  258. this.uniqueId = 0;
  259. /**
  260. * Observable that will be called when the shader is compiled.
  261. */
  262. this.onCompileObservable = new BABYLON.Observable();
  263. /**
  264. * Observable that will be called if an error occurs during shader compilation.
  265. */
  266. this.onErrorObservable = new BABYLON.Observable();
  267. /**
  268. * Observable that will be called when effect is bound.
  269. */
  270. this.onBindObservable = new BABYLON.Observable();
  271. /** @hidden */
  272. this._bonesComputationForcedToCPU = false;
  273. this._uniformBuffersNames = {};
  274. this._isReady = false;
  275. this._compilationError = "";
  276. this.name = baseName;
  277. if (attributesNamesOrOptions.attributes) {
  278. var options = attributesNamesOrOptions;
  279. this._engine = uniformsNamesOrEngine;
  280. this._attributesNames = options.attributes;
  281. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  282. this._samplers = options.samplers.slice();
  283. this.defines = options.defines;
  284. this.onError = options.onError;
  285. this.onCompiled = options.onCompiled;
  286. this._fallbacks = options.fallbacks;
  287. this._indexParameters = options.indexParameters;
  288. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  289. if (options.uniformBuffersNames) {
  290. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  291. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  292. }
  293. }
  294. }
  295. else {
  296. this._engine = engine;
  297. this.defines = defines;
  298. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  299. this._samplers = samplers ? samplers.slice() : [];
  300. this._attributesNames = attributesNamesOrOptions;
  301. this.onError = onError;
  302. this.onCompiled = onCompiled;
  303. this._indexParameters = indexParameters;
  304. this._fallbacks = fallbacks;
  305. }
  306. this.uniqueId = Effect._uniqueIdSeed++;
  307. var vertexSource;
  308. var fragmentSource;
  309. if (baseName.vertexElement) {
  310. vertexSource = document.getElementById(baseName.vertexElement);
  311. if (!vertexSource) {
  312. vertexSource = baseName.vertexElement;
  313. }
  314. }
  315. else {
  316. vertexSource = baseName.vertex || baseName;
  317. }
  318. if (baseName.fragmentElement) {
  319. fragmentSource = document.getElementById(baseName.fragmentElement);
  320. if (!fragmentSource) {
  321. fragmentSource = baseName.fragmentElement;
  322. }
  323. }
  324. else {
  325. fragmentSource = baseName.fragment || baseName;
  326. }
  327. this._loadVertexShader(vertexSource, function (vertexCode) {
  328. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  329. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  330. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  331. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  332. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  333. if (baseName) {
  334. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  335. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  336. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  337. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  338. }
  339. else {
  340. _this._vertexSourceCode = migratedVertexCode;
  341. _this._fragmentSourceCode = migratedFragmentCode;
  342. }
  343. _this._prepareEffect();
  344. });
  345. });
  346. });
  347. });
  348. });
  349. });
  350. }
  351. Object.defineProperty(Effect.prototype, "key", {
  352. /**
  353. * Unique key for this effect
  354. */
  355. get: function () {
  356. return this._key;
  357. },
  358. enumerable: true,
  359. configurable: true
  360. });
  361. /**
  362. * If the effect has been compiled and prepared.
  363. * @returns if the effect is compiled and prepared.
  364. */
  365. Effect.prototype.isReady = function () {
  366. return this._isReady;
  367. };
  368. /**
  369. * The engine the effect was initialized with.
  370. * @returns the engine.
  371. */
  372. Effect.prototype.getEngine = function () {
  373. return this._engine;
  374. };
  375. /**
  376. * The compiled webGL program for the effect
  377. * @returns the webGL program.
  378. */
  379. Effect.prototype.getProgram = function () {
  380. return this._program;
  381. };
  382. /**
  383. * The set of names of attribute variables for the shader.
  384. * @returns An array of attribute names.
  385. */
  386. Effect.prototype.getAttributesNames = function () {
  387. return this._attributesNames;
  388. };
  389. /**
  390. * Returns the attribute at the given index.
  391. * @param index The index of the attribute.
  392. * @returns The location of the attribute.
  393. */
  394. Effect.prototype.getAttributeLocation = function (index) {
  395. return this._attributes[index];
  396. };
  397. /**
  398. * Returns the attribute based on the name of the variable.
  399. * @param name of the attribute to look up.
  400. * @returns the attribute location.
  401. */
  402. Effect.prototype.getAttributeLocationByName = function (name) {
  403. var index = this._attributesNames.indexOf(name);
  404. return this._attributes[index];
  405. };
  406. /**
  407. * The number of attributes.
  408. * @returns the numnber of attributes.
  409. */
  410. Effect.prototype.getAttributesCount = function () {
  411. return this._attributes.length;
  412. };
  413. /**
  414. * Gets the index of a uniform variable.
  415. * @param uniformName of the uniform to look up.
  416. * @returns the index.
  417. */
  418. Effect.prototype.getUniformIndex = function (uniformName) {
  419. return this._uniformsNames.indexOf(uniformName);
  420. };
  421. /**
  422. * Returns the attribute based on the name of the variable.
  423. * @param uniformName of the uniform to look up.
  424. * @returns the location of the uniform.
  425. */
  426. Effect.prototype.getUniform = function (uniformName) {
  427. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  428. };
  429. /**
  430. * Returns an array of sampler variable names
  431. * @returns The array of sampler variable neames.
  432. */
  433. Effect.prototype.getSamplers = function () {
  434. return this._samplers;
  435. };
  436. /**
  437. * The error from the last compilation.
  438. * @returns the error string.
  439. */
  440. Effect.prototype.getCompilationError = function () {
  441. return this._compilationError;
  442. };
  443. /**
  444. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  445. * @param func The callback to be used.
  446. */
  447. Effect.prototype.executeWhenCompiled = function (func) {
  448. if (this.isReady()) {
  449. func(this);
  450. return;
  451. }
  452. this.onCompileObservable.add(function (effect) {
  453. func(effect);
  454. });
  455. };
  456. /** @hidden */
  457. Effect.prototype._loadVertexShader = function (vertex, callback) {
  458. if (BABYLON.Tools.IsWindowObjectExist()) {
  459. // DOM element ?
  460. if (vertex instanceof HTMLElement) {
  461. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  462. callback(vertexCode);
  463. return;
  464. }
  465. }
  466. // Base64 encoded ?
  467. if (vertex.substr(0, 7) === "base64:") {
  468. var vertexBinary = window.atob(vertex.substr(7));
  469. callback(vertexBinary);
  470. return;
  471. }
  472. // Is in local store ?
  473. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  474. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  475. return;
  476. }
  477. var vertexShaderUrl;
  478. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  479. vertexShaderUrl = vertex;
  480. }
  481. else {
  482. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  483. }
  484. // Vertex shader
  485. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  486. };
  487. /** @hidden */
  488. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  489. if (BABYLON.Tools.IsWindowObjectExist()) {
  490. // DOM element ?
  491. if (fragment instanceof HTMLElement) {
  492. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  493. callback(fragmentCode);
  494. return;
  495. }
  496. }
  497. // Base64 encoded ?
  498. if (fragment.substr(0, 7) === "base64:") {
  499. var fragmentBinary = window.atob(fragment.substr(7));
  500. callback(fragmentBinary);
  501. return;
  502. }
  503. // Is in local store ?
  504. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  505. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  506. return;
  507. }
  508. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  509. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  510. return;
  511. }
  512. var fragmentShaderUrl;
  513. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  514. fragmentShaderUrl = fragment;
  515. }
  516. else {
  517. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  518. }
  519. // Fragment shader
  520. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  521. };
  522. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  523. // Rebuild shaders source code
  524. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  525. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  526. vertexCode = prefix + vertexCode;
  527. fragmentCode = prefix + fragmentCode;
  528. // Number lines of shaders source code
  529. var i = 2;
  530. var regex = /\n/gm;
  531. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  532. i = 2;
  533. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  534. // Dump shaders name and formatted source code
  535. if (this.name.vertexElement) {
  536. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  537. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  538. }
  539. else if (this.name.vertex) {
  540. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  541. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  542. }
  543. else {
  544. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  545. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  546. }
  547. };
  548. ;
  549. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  550. var preparedSourceCode = this._processPrecision(sourceCode);
  551. if (this._engine.webGLVersion == 1) {
  552. callback(preparedSourceCode);
  553. return;
  554. }
  555. // Already converted
  556. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  557. callback(preparedSourceCode.replace("#version 300 es", ""));
  558. return;
  559. }
  560. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  561. // Remove extensions
  562. // #extension GL_OES_standard_derivatives : enable
  563. // #extension GL_EXT_shader_texture_lod : enable
  564. // #extension GL_EXT_frag_depth : enable
  565. // #extension GL_EXT_draw_buffers : require
  566. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  567. var result = preparedSourceCode.replace(regex, "");
  568. // Migrate to GLSL v300
  569. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  570. result = result.replace(/attribute[ \t]/g, "in ");
  571. result = result.replace(/[ \t]attribute/g, " in");
  572. if (isFragment) {
  573. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  574. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  575. result = result.replace(/texture2D\s*\(/g, "texture(");
  576. result = result.replace(/textureCube\s*\(/g, "texture(");
  577. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  578. result = result.replace(/gl_FragColor/g, "glFragColor");
  579. result = result.replace(/gl_FragData/g, "glFragData");
  580. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  581. }
  582. callback(result);
  583. };
  584. Effect.prototype._processIncludes = function (sourceCode, callback) {
  585. var _this = this;
  586. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  587. var match = regex.exec(sourceCode);
  588. var returnValue = new String(sourceCode);
  589. while (match != null) {
  590. var includeFile = match[1];
  591. // Uniform declaration
  592. if (includeFile.indexOf("__decl__") !== -1) {
  593. includeFile = includeFile.replace(/__decl__/, "");
  594. if (this._engine.supportsUniformBuffers) {
  595. includeFile = includeFile.replace(/Vertex/, "Ubo");
  596. includeFile = includeFile.replace(/Fragment/, "Ubo");
  597. }
  598. includeFile = includeFile + "Declaration";
  599. }
  600. if (Effect.IncludesShadersStore[includeFile]) {
  601. // Substitution
  602. var includeContent = Effect.IncludesShadersStore[includeFile];
  603. if (match[2]) {
  604. var splits = match[3].split(",");
  605. for (var index = 0; index < splits.length; index += 2) {
  606. var source = new RegExp(splits[index], "g");
  607. var dest = splits[index + 1];
  608. includeContent = includeContent.replace(source, dest);
  609. }
  610. }
  611. if (match[4]) {
  612. var indexString = match[5];
  613. if (indexString.indexOf("..") !== -1) {
  614. var indexSplits = indexString.split("..");
  615. var minIndex = parseInt(indexSplits[0]);
  616. var maxIndex = parseInt(indexSplits[1]);
  617. var sourceIncludeContent = includeContent.slice(0);
  618. includeContent = "";
  619. if (isNaN(maxIndex)) {
  620. maxIndex = this._indexParameters[indexSplits[1]];
  621. }
  622. for (var i = minIndex; i < maxIndex; i++) {
  623. if (!this._engine.supportsUniformBuffers) {
  624. // Ubo replacement
  625. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  626. return p1 + "{X}";
  627. });
  628. }
  629. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  630. }
  631. }
  632. else {
  633. if (!this._engine.supportsUniformBuffers) {
  634. // Ubo replacement
  635. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  636. return p1 + "{X}";
  637. });
  638. }
  639. includeContent = includeContent.replace(/\{X\}/g, indexString);
  640. }
  641. }
  642. // Replace
  643. returnValue = returnValue.replace(match[0], includeContent);
  644. }
  645. else {
  646. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  647. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  648. Effect.IncludesShadersStore[includeFile] = fileContent;
  649. _this._processIncludes(returnValue, callback);
  650. });
  651. return;
  652. }
  653. match = regex.exec(sourceCode);
  654. }
  655. callback(returnValue);
  656. };
  657. Effect.prototype._processPrecision = function (source) {
  658. if (source.indexOf("precision highp float") === -1) {
  659. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  660. source = "precision mediump float;\n" + source;
  661. }
  662. else {
  663. source = "precision highp float;\n" + source;
  664. }
  665. }
  666. else {
  667. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  668. source = source.replace("precision highp float", "precision mediump float");
  669. }
  670. }
  671. return source;
  672. };
  673. /**
  674. * Recompiles the webGL program
  675. * @param vertexSourceCode The source code for the vertex shader.
  676. * @param fragmentSourceCode The source code for the fragment shader.
  677. * @param onCompiled Callback called when completed.
  678. * @param onError Callback called on error.
  679. */
  680. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  681. var _this = this;
  682. this._isReady = false;
  683. this._vertexSourceCodeOverride = vertexSourceCode;
  684. this._fragmentSourceCodeOverride = fragmentSourceCode;
  685. this.onError = function (effect, error) {
  686. if (onError) {
  687. onError(error);
  688. }
  689. };
  690. this.onCompiled = function () {
  691. var scenes = _this.getEngine().scenes;
  692. for (var i = 0; i < scenes.length; i++) {
  693. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  694. }
  695. if (onCompiled) {
  696. onCompiled(_this._program);
  697. }
  698. };
  699. this._fallbacks = null;
  700. this._prepareEffect();
  701. };
  702. /**
  703. * Gets the uniform locations of the the specified variable names
  704. * @param names THe names of the variables to lookup.
  705. * @returns Array of locations in the same order as variable names.
  706. */
  707. Effect.prototype.getSpecificUniformLocations = function (names) {
  708. var engine = this._engine;
  709. return engine.getUniforms(this._program, names);
  710. };
  711. /**
  712. * Prepares the effect
  713. */
  714. Effect.prototype._prepareEffect = function () {
  715. var attributesNames = this._attributesNames;
  716. var defines = this.defines;
  717. var fallbacks = this._fallbacks;
  718. this._valueCache = {};
  719. var previousProgram = this._program;
  720. try {
  721. var engine = this._engine;
  722. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  723. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  724. }
  725. else {
  726. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  727. }
  728. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  729. if (engine.supportsUniformBuffers) {
  730. for (var name in this._uniformBuffersNames) {
  731. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  732. }
  733. }
  734. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  735. this._attributes = engine.getAttributes(this._program, attributesNames);
  736. var index;
  737. for (index = 0; index < this._samplers.length; index++) {
  738. var sampler = this.getUniform(this._samplers[index]);
  739. if (sampler == null) {
  740. this._samplers.splice(index, 1);
  741. index--;
  742. }
  743. }
  744. engine.bindSamplers(this);
  745. this._compilationError = "";
  746. this._isReady = true;
  747. if (this.onCompiled) {
  748. this.onCompiled(this);
  749. }
  750. this.onCompileObservable.notifyObservers(this);
  751. this.onCompileObservable.clear();
  752. // Unbind mesh reference in fallbacks
  753. if (this._fallbacks) {
  754. this._fallbacks.unBindMesh();
  755. }
  756. if (previousProgram) {
  757. this.getEngine()._deleteProgram(previousProgram);
  758. }
  759. }
  760. catch (e) {
  761. this._compilationError = e.message;
  762. // Let's go through fallbacks then
  763. BABYLON.Tools.Error("Unable to compile effect:");
  764. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  765. return " " + uniform;
  766. }));
  767. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  768. return " " + attribute;
  769. }));
  770. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  771. BABYLON.Tools.Error("Error: " + this._compilationError);
  772. if (previousProgram) {
  773. this._program = previousProgram;
  774. this._isReady = true;
  775. if (this.onError) {
  776. this.onError(this, this._compilationError);
  777. }
  778. this.onErrorObservable.notifyObservers(this);
  779. }
  780. if (fallbacks && fallbacks.isMoreFallbacks) {
  781. BABYLON.Tools.Error("Trying next fallback.");
  782. this.defines = fallbacks.reduce(this.defines, this);
  783. this._prepareEffect();
  784. }
  785. else { // Sorry we did everything we can
  786. if (this.onError) {
  787. this.onError(this, this._compilationError);
  788. }
  789. this.onErrorObservable.notifyObservers(this);
  790. this.onErrorObservable.clear();
  791. // Unbind mesh reference in fallbacks
  792. if (this._fallbacks) {
  793. this._fallbacks.unBindMesh();
  794. }
  795. }
  796. }
  797. };
  798. Object.defineProperty(Effect.prototype, "isSupported", {
  799. /**
  800. * Checks if the effect is supported. (Must be called after compilation)
  801. */
  802. get: function () {
  803. return this._compilationError === "";
  804. },
  805. enumerable: true,
  806. configurable: true
  807. });
  808. /**
  809. * Binds a texture to the engine to be used as output of the shader.
  810. * @param channel Name of the output variable.
  811. * @param texture Texture to bind.
  812. */
  813. Effect.prototype._bindTexture = function (channel, texture) {
  814. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  815. };
  816. /**
  817. * Sets a texture on the engine to be used in the shader.
  818. * @param channel Name of the sampler variable.
  819. * @param texture Texture to set.
  820. */
  821. Effect.prototype.setTexture = function (channel, texture) {
  822. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  823. };
  824. /**
  825. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  826. * @param channel Name of the sampler variable.
  827. * @param texture Texture to set.
  828. */
  829. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  830. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  831. };
  832. /**
  833. * Sets an array of textures on the engine to be used in the shader.
  834. * @param channel Name of the variable.
  835. * @param textures Textures to set.
  836. */
  837. Effect.prototype.setTextureArray = function (channel, textures) {
  838. if (this._samplers.indexOf(channel + "Ex") === -1) {
  839. var initialPos = this._samplers.indexOf(channel);
  840. for (var index = 1; index < textures.length; index++) {
  841. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  842. }
  843. }
  844. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  845. };
  846. /**
  847. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  848. * @param channel Name of the sampler variable.
  849. * @param postProcess Post process to get the input texture from.
  850. */
  851. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  852. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  853. };
  854. /**
  855. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  856. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  857. * @param channel Name of the sampler variable.
  858. * @param postProcess Post process to get the output texture from.
  859. */
  860. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  861. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  862. };
  863. /** @hidden */
  864. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  865. var cache = this._valueCache[uniformName];
  866. var flag = matrix.updateFlag;
  867. if (cache !== undefined && cache === flag) {
  868. return false;
  869. }
  870. this._valueCache[uniformName] = flag;
  871. return true;
  872. };
  873. /** @hidden */
  874. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  875. var cache = this._valueCache[uniformName];
  876. if (!cache) {
  877. cache = [x, y];
  878. this._valueCache[uniformName] = cache;
  879. return true;
  880. }
  881. var changed = false;
  882. if (cache[0] !== x) {
  883. cache[0] = x;
  884. changed = true;
  885. }
  886. if (cache[1] !== y) {
  887. cache[1] = y;
  888. changed = true;
  889. }
  890. return changed;
  891. };
  892. /** @hidden */
  893. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  894. var cache = this._valueCache[uniformName];
  895. if (!cache) {
  896. cache = [x, y, z];
  897. this._valueCache[uniformName] = cache;
  898. return true;
  899. }
  900. var changed = false;
  901. if (cache[0] !== x) {
  902. cache[0] = x;
  903. changed = true;
  904. }
  905. if (cache[1] !== y) {
  906. cache[1] = y;
  907. changed = true;
  908. }
  909. if (cache[2] !== z) {
  910. cache[2] = z;
  911. changed = true;
  912. }
  913. return changed;
  914. };
  915. /** @hidden */
  916. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  917. var cache = this._valueCache[uniformName];
  918. if (!cache) {
  919. cache = [x, y, z, w];
  920. this._valueCache[uniformName] = cache;
  921. return true;
  922. }
  923. var changed = false;
  924. if (cache[0] !== x) {
  925. cache[0] = x;
  926. changed = true;
  927. }
  928. if (cache[1] !== y) {
  929. cache[1] = y;
  930. changed = true;
  931. }
  932. if (cache[2] !== z) {
  933. cache[2] = z;
  934. changed = true;
  935. }
  936. if (cache[3] !== w) {
  937. cache[3] = w;
  938. changed = true;
  939. }
  940. return changed;
  941. };
  942. /**
  943. * Binds a buffer to a uniform.
  944. * @param buffer Buffer to bind.
  945. * @param name Name of the uniform variable to bind to.
  946. */
  947. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  948. var bufferName = this._uniformBuffersNames[name];
  949. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  950. return;
  951. }
  952. Effect._baseCache[bufferName] = buffer;
  953. this._engine.bindUniformBufferBase(buffer, bufferName);
  954. };
  955. /**
  956. * Binds block to a uniform.
  957. * @param blockName Name of the block to bind.
  958. * @param index Index to bind.
  959. */
  960. Effect.prototype.bindUniformBlock = function (blockName, index) {
  961. this._engine.bindUniformBlock(this._program, blockName, index);
  962. };
  963. /**
  964. * Sets an interger value on a uniform variable.
  965. * @param uniformName Name of the variable.
  966. * @param value Value to be set.
  967. * @returns this effect.
  968. */
  969. Effect.prototype.setInt = function (uniformName, value) {
  970. var cache = this._valueCache[uniformName];
  971. if (cache !== undefined && cache === value)
  972. return this;
  973. this._valueCache[uniformName] = value;
  974. this._engine.setInt(this.getUniform(uniformName), value);
  975. return this;
  976. };
  977. /**
  978. * Sets an int array on a uniform variable.
  979. * @param uniformName Name of the variable.
  980. * @param array array to be set.
  981. * @returns this effect.
  982. */
  983. Effect.prototype.setIntArray = function (uniformName, array) {
  984. this._valueCache[uniformName] = null;
  985. this._engine.setIntArray(this.getUniform(uniformName), array);
  986. return this;
  987. };
  988. /**
  989. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  990. * @param uniformName Name of the variable.
  991. * @param array array to be set.
  992. * @returns this effect.
  993. */
  994. Effect.prototype.setIntArray2 = function (uniformName, array) {
  995. this._valueCache[uniformName] = null;
  996. this._engine.setIntArray2(this.getUniform(uniformName), array);
  997. return this;
  998. };
  999. /**
  1000. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1001. * @param uniformName Name of the variable.
  1002. * @param array array to be set.
  1003. * @returns this effect.
  1004. */
  1005. Effect.prototype.setIntArray3 = function (uniformName, array) {
  1006. this._valueCache[uniformName] = null;
  1007. this._engine.setIntArray3(this.getUniform(uniformName), array);
  1008. return this;
  1009. };
  1010. /**
  1011. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1012. * @param uniformName Name of the variable.
  1013. * @param array array to be set.
  1014. * @returns this effect.
  1015. */
  1016. Effect.prototype.setIntArray4 = function (uniformName, array) {
  1017. this._valueCache[uniformName] = null;
  1018. this._engine.setIntArray4(this.getUniform(uniformName), array);
  1019. return this;
  1020. };
  1021. /**
  1022. * Sets an float array on a uniform variable.
  1023. * @param uniformName Name of the variable.
  1024. * @param array array to be set.
  1025. * @returns this effect.
  1026. */
  1027. Effect.prototype.setFloatArray = function (uniformName, array) {
  1028. this._valueCache[uniformName] = null;
  1029. this._engine.setFloatArray(this.getUniform(uniformName), array);
  1030. return this;
  1031. };
  1032. /**
  1033. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1034. * @param uniformName Name of the variable.
  1035. * @param array array to be set.
  1036. * @returns this effect.
  1037. */
  1038. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  1039. this._valueCache[uniformName] = null;
  1040. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  1041. return this;
  1042. };
  1043. /**
  1044. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1045. * @param uniformName Name of the variable.
  1046. * @param array array to be set.
  1047. * @returns this effect.
  1048. */
  1049. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1050. this._valueCache[uniformName] = null;
  1051. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1052. return this;
  1053. };
  1054. /**
  1055. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1056. * @param uniformName Name of the variable.
  1057. * @param array array to be set.
  1058. * @returns this effect.
  1059. */
  1060. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1061. this._valueCache[uniformName] = null;
  1062. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1063. return this;
  1064. };
  1065. /**
  1066. * Sets an array on a uniform variable.
  1067. * @param uniformName Name of the variable.
  1068. * @param array array to be set.
  1069. * @returns this effect.
  1070. */
  1071. Effect.prototype.setArray = function (uniformName, array) {
  1072. this._valueCache[uniformName] = null;
  1073. this._engine.setArray(this.getUniform(uniformName), array);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1078. * @param uniformName Name of the variable.
  1079. * @param array array to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setArray2 = function (uniformName, array) {
  1083. this._valueCache[uniformName] = null;
  1084. this._engine.setArray2(this.getUniform(uniformName), array);
  1085. return this;
  1086. };
  1087. /**
  1088. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1089. * @param uniformName Name of the variable.
  1090. * @param array array to be set.
  1091. * @returns this effect.
  1092. */
  1093. Effect.prototype.setArray3 = function (uniformName, array) {
  1094. this._valueCache[uniformName] = null;
  1095. this._engine.setArray3(this.getUniform(uniformName), array);
  1096. return this;
  1097. };
  1098. /**
  1099. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1100. * @param uniformName Name of the variable.
  1101. * @param array array to be set.
  1102. * @returns this effect.
  1103. */
  1104. Effect.prototype.setArray4 = function (uniformName, array) {
  1105. this._valueCache[uniformName] = null;
  1106. this._engine.setArray4(this.getUniform(uniformName), array);
  1107. return this;
  1108. };
  1109. /**
  1110. * Sets matrices on a uniform variable.
  1111. * @param uniformName Name of the variable.
  1112. * @param matrices matrices to be set.
  1113. * @returns this effect.
  1114. */
  1115. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1116. if (!matrices) {
  1117. return this;
  1118. }
  1119. this._valueCache[uniformName] = null;
  1120. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1121. return this;
  1122. };
  1123. /**
  1124. * Sets matrix on a uniform variable.
  1125. * @param uniformName Name of the variable.
  1126. * @param matrix matrix to be set.
  1127. * @returns this effect.
  1128. */
  1129. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1130. if (this._cacheMatrix(uniformName, matrix)) {
  1131. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1132. }
  1133. return this;
  1134. };
  1135. /**
  1136. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1137. * @param uniformName Name of the variable.
  1138. * @param matrix matrix to be set.
  1139. * @returns this effect.
  1140. */
  1141. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1142. this._valueCache[uniformName] = null;
  1143. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1144. return this;
  1145. };
  1146. /**
  1147. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1148. * @param uniformName Name of the variable.
  1149. * @param matrix matrix to be set.
  1150. * @returns this effect.
  1151. */
  1152. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1153. this._valueCache[uniformName] = null;
  1154. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1155. return this;
  1156. };
  1157. /**
  1158. * Sets a float on a uniform variable.
  1159. * @param uniformName Name of the variable.
  1160. * @param value value to be set.
  1161. * @returns this effect.
  1162. */
  1163. Effect.prototype.setFloat = function (uniformName, value) {
  1164. var cache = this._valueCache[uniformName];
  1165. if (cache !== undefined && cache === value)
  1166. return this;
  1167. this._valueCache[uniformName] = value;
  1168. this._engine.setFloat(this.getUniform(uniformName), value);
  1169. return this;
  1170. };
  1171. /**
  1172. * Sets a boolean on a uniform variable.
  1173. * @param uniformName Name of the variable.
  1174. * @param bool value to be set.
  1175. * @returns this effect.
  1176. */
  1177. Effect.prototype.setBool = function (uniformName, bool) {
  1178. var cache = this._valueCache[uniformName];
  1179. if (cache !== undefined && cache === bool)
  1180. return this;
  1181. this._valueCache[uniformName] = bool;
  1182. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1183. return this;
  1184. };
  1185. /**
  1186. * Sets a Vector2 on a uniform variable.
  1187. * @param uniformName Name of the variable.
  1188. * @param vector2 vector2 to be set.
  1189. * @returns this effect.
  1190. */
  1191. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1192. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1193. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1194. }
  1195. return this;
  1196. };
  1197. /**
  1198. * Sets a float2 on a uniform variable.
  1199. * @param uniformName Name of the variable.
  1200. * @param x First float in float2.
  1201. * @param y Second float in float2.
  1202. * @returns this effect.
  1203. */
  1204. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1205. if (this._cacheFloat2(uniformName, x, y)) {
  1206. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1207. }
  1208. return this;
  1209. };
  1210. /**
  1211. * Sets a Vector3 on a uniform variable.
  1212. * @param uniformName Name of the variable.
  1213. * @param vector3 Value to be set.
  1214. * @returns this effect.
  1215. */
  1216. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1217. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1218. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1219. }
  1220. return this;
  1221. };
  1222. /**
  1223. * Sets a float3 on a uniform variable.
  1224. * @param uniformName Name of the variable.
  1225. * @param x First float in float3.
  1226. * @param y Second float in float3.
  1227. * @param z Third float in float3.
  1228. * @returns this effect.
  1229. */
  1230. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1231. if (this._cacheFloat3(uniformName, x, y, z)) {
  1232. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1233. }
  1234. return this;
  1235. };
  1236. /**
  1237. * Sets a Vector4 on a uniform variable.
  1238. * @param uniformName Name of the variable.
  1239. * @param vector4 Value to be set.
  1240. * @returns this effect.
  1241. */
  1242. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1243. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1244. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1245. }
  1246. return this;
  1247. };
  1248. /**
  1249. * Sets a float4 on a uniform variable.
  1250. * @param uniformName Name of the variable.
  1251. * @param x First float in float4.
  1252. * @param y Second float in float4.
  1253. * @param z Third float in float4.
  1254. * @param w Fourth float in float4.
  1255. * @returns this effect.
  1256. */
  1257. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1258. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1259. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1260. }
  1261. return this;
  1262. };
  1263. /**
  1264. * Sets a Color3 on a uniform variable.
  1265. * @param uniformName Name of the variable.
  1266. * @param color3 Value to be set.
  1267. * @returns this effect.
  1268. */
  1269. Effect.prototype.setColor3 = function (uniformName, color3) {
  1270. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1271. this._engine.setColor3(this.getUniform(uniformName), color3);
  1272. }
  1273. return this;
  1274. };
  1275. /**
  1276. * Sets a Color4 on a uniform variable.
  1277. * @param uniformName Name of the variable.
  1278. * @param color3 Value to be set.
  1279. * @param alpha Alpha value to be set.
  1280. * @returns this effect.
  1281. */
  1282. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1283. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1284. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1285. }
  1286. return this;
  1287. };
  1288. /**
  1289. * Sets a Color4 on a uniform variable
  1290. * @param uniformName defines the name of the variable
  1291. * @param color4 defines the value to be set
  1292. * @returns this effect.
  1293. */
  1294. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1295. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1296. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1297. }
  1298. return this;
  1299. };
  1300. /**
  1301. * Resets the cache of effects.
  1302. */
  1303. Effect.ResetCache = function () {
  1304. Effect._baseCache = {};
  1305. };
  1306. Effect._uniqueIdSeed = 0;
  1307. Effect._baseCache = {};
  1308. /**
  1309. * Store of each shader (The can be looked up using effect.key)
  1310. */
  1311. Effect.ShadersStore = {};
  1312. /**
  1313. * Store of each included file for a shader (The can be looked up using effect.key)
  1314. */
  1315. Effect.IncludesShadersStore = {};
  1316. return Effect;
  1317. }());
  1318. BABYLON.Effect = Effect;
  1319. })(BABYLON || (BABYLON = {}));
  1320. //# sourceMappingURL=babylon.effect.js.map
  1321. //# sourceMappingURL=babylon.types.js.map
  1322. var BABYLON;
  1323. (function (BABYLON) {
  1324. var KeyboardEventTypes = /** @class */ (function () {
  1325. function KeyboardEventTypes() {
  1326. }
  1327. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1328. get: function () {
  1329. return KeyboardEventTypes._KEYDOWN;
  1330. },
  1331. enumerable: true,
  1332. configurable: true
  1333. });
  1334. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1335. get: function () {
  1336. return KeyboardEventTypes._KEYUP;
  1337. },
  1338. enumerable: true,
  1339. configurable: true
  1340. });
  1341. KeyboardEventTypes._KEYDOWN = 0x01;
  1342. KeyboardEventTypes._KEYUP = 0x02;
  1343. return KeyboardEventTypes;
  1344. }());
  1345. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1346. var KeyboardInfo = /** @class */ (function () {
  1347. function KeyboardInfo(type, event) {
  1348. this.type = type;
  1349. this.event = event;
  1350. }
  1351. return KeyboardInfo;
  1352. }());
  1353. BABYLON.KeyboardInfo = KeyboardInfo;
  1354. /**
  1355. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1356. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1357. */
  1358. var KeyboardInfoPre = /** @class */ (function (_super) {
  1359. __extends(KeyboardInfoPre, _super);
  1360. function KeyboardInfoPre(type, event) {
  1361. var _this = _super.call(this, type, event) || this;
  1362. _this.skipOnPointerObservable = false;
  1363. return _this;
  1364. }
  1365. return KeyboardInfoPre;
  1366. }(KeyboardInfo));
  1367. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1368. })(BABYLON || (BABYLON = {}));
  1369. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1370. var BABYLON;
  1371. (function (BABYLON) {
  1372. var PointerEventTypes = /** @class */ (function () {
  1373. function PointerEventTypes() {
  1374. }
  1375. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1376. get: function () {
  1377. return PointerEventTypes._POINTERDOWN;
  1378. },
  1379. enumerable: true,
  1380. configurable: true
  1381. });
  1382. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1383. get: function () {
  1384. return PointerEventTypes._POINTERUP;
  1385. },
  1386. enumerable: true,
  1387. configurable: true
  1388. });
  1389. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1390. get: function () {
  1391. return PointerEventTypes._POINTERMOVE;
  1392. },
  1393. enumerable: true,
  1394. configurable: true
  1395. });
  1396. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1397. get: function () {
  1398. return PointerEventTypes._POINTERWHEEL;
  1399. },
  1400. enumerable: true,
  1401. configurable: true
  1402. });
  1403. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1404. get: function () {
  1405. return PointerEventTypes._POINTERPICK;
  1406. },
  1407. enumerable: true,
  1408. configurable: true
  1409. });
  1410. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1411. get: function () {
  1412. return PointerEventTypes._POINTERTAP;
  1413. },
  1414. enumerable: true,
  1415. configurable: true
  1416. });
  1417. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1418. get: function () {
  1419. return PointerEventTypes._POINTERDOUBLETAP;
  1420. },
  1421. enumerable: true,
  1422. configurable: true
  1423. });
  1424. PointerEventTypes._POINTERDOWN = 0x01;
  1425. PointerEventTypes._POINTERUP = 0x02;
  1426. PointerEventTypes._POINTERMOVE = 0x04;
  1427. PointerEventTypes._POINTERWHEEL = 0x08;
  1428. PointerEventTypes._POINTERPICK = 0x10;
  1429. PointerEventTypes._POINTERTAP = 0x20;
  1430. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1431. return PointerEventTypes;
  1432. }());
  1433. BABYLON.PointerEventTypes = PointerEventTypes;
  1434. var PointerInfoBase = /** @class */ (function () {
  1435. function PointerInfoBase(type, event) {
  1436. this.type = type;
  1437. this.event = event;
  1438. }
  1439. return PointerInfoBase;
  1440. }());
  1441. BABYLON.PointerInfoBase = PointerInfoBase;
  1442. /**
  1443. * This class is used to store pointer related info for the onPrePointerObservable event.
  1444. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1445. */
  1446. var PointerInfoPre = /** @class */ (function (_super) {
  1447. __extends(PointerInfoPre, _super);
  1448. function PointerInfoPre(type, event, localX, localY) {
  1449. var _this = _super.call(this, type, event) || this;
  1450. _this.skipOnPointerObservable = false;
  1451. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1452. return _this;
  1453. }
  1454. return PointerInfoPre;
  1455. }(PointerInfoBase));
  1456. BABYLON.PointerInfoPre = PointerInfoPre;
  1457. /**
  1458. * This type contains all the data related to a pointer event in Babylon.js.
  1459. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1460. */
  1461. var PointerInfo = /** @class */ (function (_super) {
  1462. __extends(PointerInfo, _super);
  1463. function PointerInfo(type, event, pickInfo) {
  1464. var _this = _super.call(this, type, event) || this;
  1465. _this.pickInfo = pickInfo;
  1466. return _this;
  1467. }
  1468. return PointerInfo;
  1469. }(PointerInfoBase));
  1470. BABYLON.PointerInfo = PointerInfo;
  1471. })(BABYLON || (BABYLON = {}));
  1472. //# sourceMappingURL=babylon.pointerEvents.js.map
  1473. var BABYLON;
  1474. (function (BABYLON) {
  1475. BABYLON.ToGammaSpace = 1 / 2.2;
  1476. BABYLON.ToLinearSpace = 2.2;
  1477. BABYLON.Epsilon = 0.001;
  1478. /**
  1479. * Class used to hold a RBG color
  1480. */
  1481. var Color3 = /** @class */ (function () {
  1482. /**
  1483. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1484. * @param r defines the red component (between 0 and 1, default is 0)
  1485. * @param g defines the green component (between 0 and 1, default is 0)
  1486. * @param b defines the blue component (between 0 and 1, default is 0)
  1487. */
  1488. function Color3(
  1489. /**
  1490. * Defines the red component (between 0 and 1, default is 0)
  1491. */
  1492. r,
  1493. /**
  1494. * Defines the green component (between 0 and 1, default is 0)
  1495. */
  1496. g,
  1497. /**
  1498. * Defines the blue component (between 0 and 1, default is 0)
  1499. */
  1500. b) {
  1501. if (r === void 0) { r = 0; }
  1502. if (g === void 0) { g = 0; }
  1503. if (b === void 0) { b = 0; }
  1504. this.r = r;
  1505. this.g = g;
  1506. this.b = b;
  1507. }
  1508. /**
  1509. * Creates a string with the Color3 current values
  1510. * @returns the string representation of the Color3 object
  1511. */
  1512. Color3.prototype.toString = function () {
  1513. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1514. };
  1515. /**
  1516. * Returns the string "Color3"
  1517. * @returns "Color3"
  1518. */
  1519. Color3.prototype.getClassName = function () {
  1520. return "Color3";
  1521. };
  1522. /**
  1523. * Compute the Color3 hash code
  1524. * @returns an unique number that can be used to hash Color3 objects
  1525. */
  1526. Color3.prototype.getHashCode = function () {
  1527. var hash = this.r || 0;
  1528. hash = (hash * 397) ^ (this.g || 0);
  1529. hash = (hash * 397) ^ (this.b || 0);
  1530. return hash;
  1531. };
  1532. // Operators
  1533. /**
  1534. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1535. * @param array defines the array where to store the r,g,b components
  1536. * @param index defines an optional index in the target array to define where to start storing values
  1537. * @returns the current Color3 object
  1538. */
  1539. Color3.prototype.toArray = function (array, index) {
  1540. if (index === undefined) {
  1541. index = 0;
  1542. }
  1543. array[index] = this.r;
  1544. array[index + 1] = this.g;
  1545. array[index + 2] = this.b;
  1546. return this;
  1547. };
  1548. /**
  1549. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1550. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1551. * @returns a new {BABYLON.Color4} object
  1552. */
  1553. Color3.prototype.toColor4 = function (alpha) {
  1554. if (alpha === void 0) { alpha = 1; }
  1555. return new Color4(this.r, this.g, this.b, alpha);
  1556. };
  1557. /**
  1558. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1559. * @returns the new array
  1560. */
  1561. Color3.prototype.asArray = function () {
  1562. var result = new Array();
  1563. this.toArray(result, 0);
  1564. return result;
  1565. };
  1566. /**
  1567. * Returns the luminance value
  1568. * @returns a float value
  1569. */
  1570. Color3.prototype.toLuminance = function () {
  1571. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1572. };
  1573. /**
  1574. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1575. * @param otherColor defines the second operand
  1576. * @returns the new Color3 object
  1577. */
  1578. Color3.prototype.multiply = function (otherColor) {
  1579. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1580. };
  1581. /**
  1582. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1583. * @param otherColor defines the second operand
  1584. * @param result defines the Color3 object where to store the result
  1585. * @returns the current Color3
  1586. */
  1587. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1588. result.r = this.r * otherColor.r;
  1589. result.g = this.g * otherColor.g;
  1590. result.b = this.b * otherColor.b;
  1591. return this;
  1592. };
  1593. /**
  1594. * Determines equality between Color3 objects
  1595. * @param otherColor defines the second operand
  1596. * @returns true if the rgb values are equal to the given ones
  1597. */
  1598. Color3.prototype.equals = function (otherColor) {
  1599. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1600. };
  1601. /**
  1602. * Determines equality between the current Color3 object and a set of r,b,g values
  1603. * @param r defines the red component to check
  1604. * @param g defines the green component to check
  1605. * @param b defines the blue component to check
  1606. * @returns true if the rgb values are equal to the given ones
  1607. */
  1608. Color3.prototype.equalsFloats = function (r, g, b) {
  1609. return this.r === r && this.g === g && this.b === b;
  1610. };
  1611. /**
  1612. * Multiplies in place each rgb value by scale
  1613. * @param scale defines the scaling factor
  1614. * @returns the updated Color3
  1615. */
  1616. Color3.prototype.scale = function (scale) {
  1617. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1618. };
  1619. /**
  1620. * Multiplies the rgb values by scale and stores the result into "result"
  1621. * @param scale defines the scaling factor
  1622. * @param result defines the Color3 object where to store the result
  1623. * @returns the unmodified current Color3
  1624. */
  1625. Color3.prototype.scaleToRef = function (scale, result) {
  1626. result.r = this.r * scale;
  1627. result.g = this.g * scale;
  1628. result.b = this.b * scale;
  1629. return this;
  1630. };
  1631. /**
  1632. * Scale the current Color3 values by a factor and add the result to a given Color3
  1633. * @param scale defines the scale factor
  1634. * @param result defines color to store the result into
  1635. * @returns the unmodified current Color3
  1636. */
  1637. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1638. result.r += this.r * scale;
  1639. result.g += this.g * scale;
  1640. result.b += this.b * scale;
  1641. return this;
  1642. };
  1643. /**
  1644. * Clamps the rgb values by the min and max values and stores the result into "result"
  1645. * @param min defines minimum clamping value (default is 0)
  1646. * @param max defines maximum clamping value (default is 1)
  1647. * @param result defines color to store the result into
  1648. * @returns the original Color3
  1649. */
  1650. Color3.prototype.clampToRef = function (min, max, result) {
  1651. if (min === void 0) { min = 0; }
  1652. if (max === void 0) { max = 1; }
  1653. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1654. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1655. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1656. return this;
  1657. };
  1658. /**
  1659. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1660. * @param otherColor defines the second operand
  1661. * @returns the new Color3
  1662. */
  1663. Color3.prototype.add = function (otherColor) {
  1664. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1665. };
  1666. /**
  1667. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1668. * @param otherColor defines the second operand
  1669. * @param result defines Color3 object to store the result into
  1670. * @returns the unmodified current Color3
  1671. */
  1672. Color3.prototype.addToRef = function (otherColor, result) {
  1673. result.r = this.r + otherColor.r;
  1674. result.g = this.g + otherColor.g;
  1675. result.b = this.b + otherColor.b;
  1676. return this;
  1677. };
  1678. /**
  1679. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1680. * @param otherColor defines the second operand
  1681. * @returns the new Color3
  1682. */
  1683. Color3.prototype.subtract = function (otherColor) {
  1684. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1685. };
  1686. /**
  1687. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1688. * @param otherColor defines the second operand
  1689. * @param result defines Color3 object to store the result into
  1690. * @returns the unmodified current Color3
  1691. */
  1692. Color3.prototype.subtractToRef = function (otherColor, result) {
  1693. result.r = this.r - otherColor.r;
  1694. result.g = this.g - otherColor.g;
  1695. result.b = this.b - otherColor.b;
  1696. return this;
  1697. };
  1698. /**
  1699. * Copy the current object
  1700. * @returns a new Color3 copied the current one
  1701. */
  1702. Color3.prototype.clone = function () {
  1703. return new Color3(this.r, this.g, this.b);
  1704. };
  1705. /**
  1706. * Copies the rgb values from the source in the current Color3
  1707. * @param source defines the source Color3 object
  1708. * @returns the updated Color3 object
  1709. */
  1710. Color3.prototype.copyFrom = function (source) {
  1711. this.r = source.r;
  1712. this.g = source.g;
  1713. this.b = source.b;
  1714. return this;
  1715. };
  1716. /**
  1717. * Updates the Color3 rgb values from the given floats
  1718. * @param r defines the red component to read from
  1719. * @param g defines the green component to read from
  1720. * @param b defines the blue component to read from
  1721. * @returns the current Color3 object
  1722. */
  1723. Color3.prototype.copyFromFloats = function (r, g, b) {
  1724. this.r = r;
  1725. this.g = g;
  1726. this.b = b;
  1727. return this;
  1728. };
  1729. /**
  1730. * Updates the Color3 rgb values from the given floats
  1731. * @param r defines the red component to read from
  1732. * @param g defines the green component to read from
  1733. * @param b defines the blue component to read from
  1734. * @returns the current Color3 object
  1735. */
  1736. Color3.prototype.set = function (r, g, b) {
  1737. return this.copyFromFloats(r, g, b);
  1738. };
  1739. /**
  1740. * Compute the Color3 hexadecimal code as a string
  1741. * @returns a string containing the hexadecimal representation of the Color3 object
  1742. */
  1743. Color3.prototype.toHexString = function () {
  1744. var intR = (this.r * 255) | 0;
  1745. var intG = (this.g * 255) | 0;
  1746. var intB = (this.b * 255) | 0;
  1747. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1748. };
  1749. /**
  1750. * Computes a new Color3 converted from the current one to linear space
  1751. * @returns a new Color3 object
  1752. */
  1753. Color3.prototype.toLinearSpace = function () {
  1754. var convertedColor = new Color3();
  1755. this.toLinearSpaceToRef(convertedColor);
  1756. return convertedColor;
  1757. };
  1758. /**
  1759. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1760. * @param convertedColor defines the Color3 object where to store the linear space version
  1761. * @returns the unmodified Color3
  1762. */
  1763. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1764. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1765. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1766. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1767. return this;
  1768. };
  1769. /**
  1770. * Computes a new Color3 converted from the current one to gamma space
  1771. * @returns a new Color3 object
  1772. */
  1773. Color3.prototype.toGammaSpace = function () {
  1774. var convertedColor = new Color3();
  1775. this.toGammaSpaceToRef(convertedColor);
  1776. return convertedColor;
  1777. };
  1778. /**
  1779. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1780. * @param convertedColor defines the Color3 object where to store the gamma space version
  1781. * @returns the unmodified Color3
  1782. */
  1783. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1784. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1785. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1786. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1787. return this;
  1788. };
  1789. // Statics
  1790. /**
  1791. * Creates a new Color3 from the string containing valid hexadecimal values
  1792. * @param hex defines a string containing valid hexadecimal values
  1793. * @returns a new Color3 object
  1794. */
  1795. Color3.FromHexString = function (hex) {
  1796. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1797. return new Color3(0, 0, 0);
  1798. }
  1799. var r = parseInt(hex.substring(1, 3), 16);
  1800. var g = parseInt(hex.substring(3, 5), 16);
  1801. var b = parseInt(hex.substring(5, 7), 16);
  1802. return Color3.FromInts(r, g, b);
  1803. };
  1804. /**
  1805. * Creates a new Vector3 from the starting index of the given array
  1806. * @param array defines the source array
  1807. * @param offset defines an offset in the source array
  1808. * @returns a new Color3 object
  1809. */
  1810. Color3.FromArray = function (array, offset) {
  1811. if (offset === void 0) { offset = 0; }
  1812. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1813. };
  1814. /**
  1815. * Creates a new Color3 from integer values (< 256)
  1816. * @param r defines the red component to read from (value between 0 and 255)
  1817. * @param g defines the green component to read from (value between 0 and 255)
  1818. * @param b defines the blue component to read from (value between 0 and 255)
  1819. * @returns a new Color3 object
  1820. */
  1821. Color3.FromInts = function (r, g, b) {
  1822. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1823. };
  1824. /**
  1825. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1826. * @param start defines the start Color3 value
  1827. * @param end defines the end Color3 value
  1828. * @param amount defines the gradient value between start and end
  1829. * @returns a new Color3 object
  1830. */
  1831. Color3.Lerp = function (start, end, amount) {
  1832. var r = start.r + ((end.r - start.r) * amount);
  1833. var g = start.g + ((end.g - start.g) * amount);
  1834. var b = start.b + ((end.b - start.b) * amount);
  1835. return new Color3(r, g, b);
  1836. };
  1837. /**
  1838. * Returns a Color3 value containing a red color
  1839. * @returns a new Color3 object
  1840. */
  1841. Color3.Red = function () { return new Color3(1, 0, 0); };
  1842. /**
  1843. * Returns a Color3 value containing a green color
  1844. * @returns a new Color3 object
  1845. */
  1846. Color3.Green = function () { return new Color3(0, 1, 0); };
  1847. /**
  1848. * Returns a Color3 value containing a blue color
  1849. * @returns a new Color3 object
  1850. */
  1851. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1852. /**
  1853. * Returns a Color3 value containing a black color
  1854. * @returns a new Color3 object
  1855. */
  1856. Color3.Black = function () { return new Color3(0, 0, 0); };
  1857. /**
  1858. * Returns a Color3 value containing a white color
  1859. * @returns a new Color3 object
  1860. */
  1861. Color3.White = function () { return new Color3(1, 1, 1); };
  1862. /**
  1863. * Returns a Color3 value containing a purple color
  1864. * @returns a new Color3 object
  1865. */
  1866. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1867. /**
  1868. * Returns a Color3 value containing a magenta color
  1869. * @returns a new Color3 object
  1870. */
  1871. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1872. /**
  1873. * Returns a Color3 value containing a yellow color
  1874. * @returns a new Color3 object
  1875. */
  1876. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1877. /**
  1878. * Returns a Color3 value containing a gray color
  1879. * @returns a new Color3 object
  1880. */
  1881. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1882. /**
  1883. * Returns a Color3 value containing a teal color
  1884. * @returns a new Color3 object
  1885. */
  1886. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1887. /**
  1888. * Returns a Color3 value containing a random color
  1889. * @returns a new Color3 object
  1890. */
  1891. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1892. return Color3;
  1893. }());
  1894. BABYLON.Color3 = Color3;
  1895. /**
  1896. * Class used to hold a RBGA color
  1897. */
  1898. var Color4 = /** @class */ (function () {
  1899. /**
  1900. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1901. * @param r defines the red component (between 0 and 1, default is 0)
  1902. * @param g defines the green component (between 0 and 1, default is 0)
  1903. * @param b defines the blue component (between 0 and 1, default is 0)
  1904. * @param a defines the alpha component (between 0 and 1, default is 1)
  1905. */
  1906. function Color4(
  1907. /**
  1908. * Defines the red component (between 0 and 1, default is 0)
  1909. */
  1910. r,
  1911. /**
  1912. * Defines the green component (between 0 and 1, default is 0)
  1913. */
  1914. g,
  1915. /**
  1916. * Defines the blue component (between 0 and 1, default is 0)
  1917. */
  1918. b,
  1919. /**
  1920. * Defines the alpha component (between 0 and 1, default is 1)
  1921. */
  1922. a) {
  1923. if (r === void 0) { r = 0; }
  1924. if (g === void 0) { g = 0; }
  1925. if (b === void 0) { b = 0; }
  1926. if (a === void 0) { a = 1; }
  1927. this.r = r;
  1928. this.g = g;
  1929. this.b = b;
  1930. this.a = a;
  1931. }
  1932. // Operators
  1933. /**
  1934. * Adds in place the given Color4 values to the current Color4 object
  1935. * @param right defines the second operand
  1936. * @returns the current updated Color4 object
  1937. */
  1938. Color4.prototype.addInPlace = function (right) {
  1939. this.r += right.r;
  1940. this.g += right.g;
  1941. this.b += right.b;
  1942. this.a += right.a;
  1943. return this;
  1944. };
  1945. /**
  1946. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1947. * @returns the new array
  1948. */
  1949. Color4.prototype.asArray = function () {
  1950. var result = new Array();
  1951. this.toArray(result, 0);
  1952. return result;
  1953. };
  1954. /**
  1955. * Stores from the starting index in the given array the Color4 successive values
  1956. * @param array defines the array where to store the r,g,b components
  1957. * @param index defines an optional index in the target array to define where to start storing values
  1958. * @returns the current Color4 object
  1959. */
  1960. Color4.prototype.toArray = function (array, index) {
  1961. if (index === undefined) {
  1962. index = 0;
  1963. }
  1964. array[index] = this.r;
  1965. array[index + 1] = this.g;
  1966. array[index + 2] = this.b;
  1967. array[index + 3] = this.a;
  1968. return this;
  1969. };
  1970. /**
  1971. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1972. * @param right defines the second operand
  1973. * @returns a new Color4 object
  1974. */
  1975. Color4.prototype.add = function (right) {
  1976. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1977. };
  1978. /**
  1979. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1980. * @param right defines the second operand
  1981. * @returns a new Color4 object
  1982. */
  1983. Color4.prototype.subtract = function (right) {
  1984. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1985. };
  1986. /**
  1987. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1988. * @param right defines the second operand
  1989. * @param result defines the Color4 object where to store the result
  1990. * @returns the current Color4 object
  1991. */
  1992. Color4.prototype.subtractToRef = function (right, result) {
  1993. result.r = this.r - right.r;
  1994. result.g = this.g - right.g;
  1995. result.b = this.b - right.b;
  1996. result.a = this.a - right.a;
  1997. return this;
  1998. };
  1999. /**
  2000. * Creates a new Color4 with the current Color4 values multiplied by scale
  2001. * @param scale defines the scaling factor to apply
  2002. * @returns a new Color4 object
  2003. */
  2004. Color4.prototype.scale = function (scale) {
  2005. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2006. };
  2007. /**
  2008. * Multiplies the current Color4 values by scale and stores the result in "result"
  2009. * @param scale defines the scaling factor to apply
  2010. * @param result defines the Color4 object where to store the result
  2011. * @returns the current unmodified Color4
  2012. */
  2013. Color4.prototype.scaleToRef = function (scale, result) {
  2014. result.r = this.r * scale;
  2015. result.g = this.g * scale;
  2016. result.b = this.b * scale;
  2017. result.a = this.a * scale;
  2018. return this;
  2019. };
  2020. /**
  2021. * Scale the current Color4 values by a factor and add the result to a given Color4
  2022. * @param scale defines the scale factor
  2023. * @param result defines the Color4 object where to store the result
  2024. * @returns the unmodified current Color4
  2025. */
  2026. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2027. result.r += this.r * scale;
  2028. result.g += this.g * scale;
  2029. result.b += this.b * scale;
  2030. result.a += this.a * scale;
  2031. return this;
  2032. };
  2033. /**
  2034. * Clamps the rgb values by the min and max values and stores the result into "result"
  2035. * @param min defines minimum clamping value (default is 0)
  2036. * @param max defines maximum clamping value (default is 1)
  2037. * @param result defines color to store the result into.
  2038. * @returns the cuurent Color4
  2039. */
  2040. Color4.prototype.clampToRef = function (min, max, result) {
  2041. if (min === void 0) { min = 0; }
  2042. if (max === void 0) { max = 1; }
  2043. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2044. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2045. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2046. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2047. return this;
  2048. };
  2049. /**
  2050. * Multipy an Color4 value by another and return a new Color4 object
  2051. * @param color defines the Color4 value to multiply by
  2052. * @returns a new Color4 object
  2053. */
  2054. Color4.prototype.multiply = function (color) {
  2055. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2056. };
  2057. /**
  2058. * Multipy a Color4 value by another and push the result in a reference value
  2059. * @param color defines the Color4 value to multiply by
  2060. * @param result defines the Color4 to fill the result in
  2061. * @returns the result Color4
  2062. */
  2063. Color4.prototype.multiplyToRef = function (color, result) {
  2064. result.r = this.r * color.r;
  2065. result.g = this.g * color.g;
  2066. result.b = this.b * color.b;
  2067. result.a = this.a * color.a;
  2068. return result;
  2069. };
  2070. /**
  2071. * Creates a string with the Color4 current values
  2072. * @returns the string representation of the Color4 object
  2073. */
  2074. Color4.prototype.toString = function () {
  2075. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2076. };
  2077. /**
  2078. * Returns the string "Color4"
  2079. * @returns "Color4"
  2080. */
  2081. Color4.prototype.getClassName = function () {
  2082. return "Color4";
  2083. };
  2084. /**
  2085. * Compute the Color4 hash code
  2086. * @returns an unique number that can be used to hash Color4 objects
  2087. */
  2088. Color4.prototype.getHashCode = function () {
  2089. var hash = this.r || 0;
  2090. hash = (hash * 397) ^ (this.g || 0);
  2091. hash = (hash * 397) ^ (this.b || 0);
  2092. hash = (hash * 397) ^ (this.a || 0);
  2093. return hash;
  2094. };
  2095. /**
  2096. * Creates a new Color4 copied from the current one
  2097. * @returns a new Color4 object
  2098. */
  2099. Color4.prototype.clone = function () {
  2100. return new Color4(this.r, this.g, this.b, this.a);
  2101. };
  2102. /**
  2103. * Copies the given Color4 values into the current one
  2104. * @param source defines the source Color4 object
  2105. * @returns the current updated Color4 object
  2106. */
  2107. Color4.prototype.copyFrom = function (source) {
  2108. this.r = source.r;
  2109. this.g = source.g;
  2110. this.b = source.b;
  2111. this.a = source.a;
  2112. return this;
  2113. };
  2114. /**
  2115. * Copies the given float values into the current one
  2116. * @param r defines the red component to read from
  2117. * @param g defines the green component to read from
  2118. * @param b defines the blue component to read from
  2119. * @param a defines the alpha component to read from
  2120. * @returns the current updated Color4 object
  2121. */
  2122. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2123. this.r = r;
  2124. this.g = g;
  2125. this.b = b;
  2126. this.a = a;
  2127. return this;
  2128. };
  2129. /**
  2130. * Copies the given float values into the current one
  2131. * @param r defines the red component to read from
  2132. * @param g defines the green component to read from
  2133. * @param b defines the blue component to read from
  2134. * @param a defines the alpha component to read from
  2135. * @returns the current updated Color4 object
  2136. */
  2137. Color4.prototype.set = function (r, g, b, a) {
  2138. return this.copyFromFloats(r, g, b, a);
  2139. };
  2140. /**
  2141. * Compute the Color4 hexadecimal code as a string
  2142. * @returns a string containing the hexadecimal representation of the Color4 object
  2143. */
  2144. Color4.prototype.toHexString = function () {
  2145. var intR = (this.r * 255) | 0;
  2146. var intG = (this.g * 255) | 0;
  2147. var intB = (this.b * 255) | 0;
  2148. var intA = (this.a * 255) | 0;
  2149. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2150. };
  2151. /**
  2152. * Computes a new Color4 converted from the current one to linear space
  2153. * @returns a new Color4 object
  2154. */
  2155. Color4.prototype.toLinearSpace = function () {
  2156. var convertedColor = new Color4();
  2157. this.toLinearSpaceToRef(convertedColor);
  2158. return convertedColor;
  2159. };
  2160. /**
  2161. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2162. * @param convertedColor defines the Color4 object where to store the linear space version
  2163. * @returns the unmodified Color4
  2164. */
  2165. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2166. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2167. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2168. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2169. convertedColor.a = this.a;
  2170. return this;
  2171. };
  2172. /**
  2173. * Computes a new Color4 converted from the current one to gamma space
  2174. * @returns a new Color4 object
  2175. */
  2176. Color4.prototype.toGammaSpace = function () {
  2177. var convertedColor = new Color4();
  2178. this.toGammaSpaceToRef(convertedColor);
  2179. return convertedColor;
  2180. };
  2181. /**
  2182. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2183. * @param convertedColor defines the Color4 object where to store the gamma space version
  2184. * @returns the unmodified Color4
  2185. */
  2186. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2187. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2188. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2189. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2190. convertedColor.a = this.a;
  2191. return this;
  2192. };
  2193. // Statics
  2194. /**
  2195. * Creates a new Color4 from the string containing valid hexadecimal values
  2196. * @param hex defines a string containing valid hexadecimal values
  2197. * @returns a new Color4 object
  2198. */
  2199. Color4.FromHexString = function (hex) {
  2200. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2201. return new Color4(0.0, 0.0, 0.0, 0.0);
  2202. }
  2203. var r = parseInt(hex.substring(1, 3), 16);
  2204. var g = parseInt(hex.substring(3, 5), 16);
  2205. var b = parseInt(hex.substring(5, 7), 16);
  2206. var a = parseInt(hex.substring(7, 9), 16);
  2207. return Color4.FromInts(r, g, b, a);
  2208. };
  2209. /**
  2210. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2211. * @param left defines the start value
  2212. * @param right defines the end value
  2213. * @param amount defines the gradient factor
  2214. * @returns a new Color4 object
  2215. */
  2216. Color4.Lerp = function (left, right, amount) {
  2217. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2218. Color4.LerpToRef(left, right, amount, result);
  2219. return result;
  2220. };
  2221. /**
  2222. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2223. * @param left defines the start value
  2224. * @param right defines the end value
  2225. * @param amount defines the gradient factor
  2226. * @param result defines the Color4 object where to store data
  2227. */
  2228. Color4.LerpToRef = function (left, right, amount, result) {
  2229. result.r = left.r + (right.r - left.r) * amount;
  2230. result.g = left.g + (right.g - left.g) * amount;
  2231. result.b = left.b + (right.b - left.b) * amount;
  2232. result.a = left.a + (right.a - left.a) * amount;
  2233. };
  2234. /**
  2235. * Creates a new Color4 from the starting index element of the given array
  2236. * @param array defines the source array to read from
  2237. * @param offset defines the offset in the source array
  2238. * @returns a new Color4 object
  2239. */
  2240. Color4.FromArray = function (array, offset) {
  2241. if (offset === void 0) { offset = 0; }
  2242. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2243. };
  2244. /**
  2245. * Creates a new Color3 from integer values (< 256)
  2246. * @param r defines the red component to read from (value between 0 and 255)
  2247. * @param g defines the green component to read from (value between 0 and 255)
  2248. * @param b defines the blue component to read from (value between 0 and 255)
  2249. * @param a defines the alpha component to read from (value between 0 and 255)
  2250. * @returns a new Color3 object
  2251. */
  2252. Color4.FromInts = function (r, g, b, a) {
  2253. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2254. };
  2255. /**
  2256. * Check the content of a given array and convert it to an array containing RGBA data
  2257. * If the original array was already containing count * 4 values then it is returned directly
  2258. * @param colors defines the array to check
  2259. * @param count defines the number of RGBA data to expect
  2260. * @returns an array containing count * 4 values (RGBA)
  2261. */
  2262. Color4.CheckColors4 = function (colors, count) {
  2263. // Check if color3 was used
  2264. if (colors.length === count * 3) {
  2265. var colors4 = [];
  2266. for (var index = 0; index < colors.length; index += 3) {
  2267. var newIndex = (index / 3) * 4;
  2268. colors4[newIndex] = colors[index];
  2269. colors4[newIndex + 1] = colors[index + 1];
  2270. colors4[newIndex + 2] = colors[index + 2];
  2271. colors4[newIndex + 3] = 1.0;
  2272. }
  2273. return colors4;
  2274. }
  2275. return colors;
  2276. };
  2277. return Color4;
  2278. }());
  2279. BABYLON.Color4 = Color4;
  2280. /**
  2281. * Class representing a vector containing 2 coordinates
  2282. */
  2283. var Vector2 = /** @class */ (function () {
  2284. /**
  2285. * Creates a new Vector2 from the given x and y coordinates
  2286. * @param x defines the first coordinate
  2287. * @param y defines the second coordinate
  2288. */
  2289. function Vector2(
  2290. /** defines the first coordinate */
  2291. x,
  2292. /** defines the second coordinate */
  2293. y) {
  2294. this.x = x;
  2295. this.y = y;
  2296. }
  2297. /**
  2298. * Gets a string with the Vector2 coordinates
  2299. * @returns a string with the Vector2 coordinates
  2300. */
  2301. Vector2.prototype.toString = function () {
  2302. return "{X: " + this.x + " Y:" + this.y + "}";
  2303. };
  2304. /**
  2305. * Gets class name
  2306. * @returns the string "Vector2"
  2307. */
  2308. Vector2.prototype.getClassName = function () {
  2309. return "Vector2";
  2310. };
  2311. /**
  2312. * Gets current vector hash code
  2313. * @returns the Vector2 hash code as a number
  2314. */
  2315. Vector2.prototype.getHashCode = function () {
  2316. var hash = this.x || 0;
  2317. hash = (hash * 397) ^ (this.y || 0);
  2318. return hash;
  2319. };
  2320. // Operators
  2321. /**
  2322. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2323. * @param array defines the source array
  2324. * @param index defines the offset in source array
  2325. * @returns the current Vector2
  2326. */
  2327. Vector2.prototype.toArray = function (array, index) {
  2328. if (index === void 0) { index = 0; }
  2329. array[index] = this.x;
  2330. array[index + 1] = this.y;
  2331. return this;
  2332. };
  2333. /**
  2334. * Copy the current vector to an array
  2335. * @returns a new array with 2 elements: the Vector2 coordinates.
  2336. */
  2337. Vector2.prototype.asArray = function () {
  2338. var result = new Array();
  2339. this.toArray(result, 0);
  2340. return result;
  2341. };
  2342. /**
  2343. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2344. * @param source defines the source Vector2
  2345. * @returns the current updated Vector2
  2346. */
  2347. Vector2.prototype.copyFrom = function (source) {
  2348. this.x = source.x;
  2349. this.y = source.y;
  2350. return this;
  2351. };
  2352. /**
  2353. * Sets the Vector2 coordinates with the given floats
  2354. * @param x defines the first coordinate
  2355. * @param y defines the second coordinate
  2356. * @returns the current updated Vector2
  2357. */
  2358. Vector2.prototype.copyFromFloats = function (x, y) {
  2359. this.x = x;
  2360. this.y = y;
  2361. return this;
  2362. };
  2363. /**
  2364. * Sets the Vector2 coordinates with the given floats
  2365. * @param x defines the first coordinate
  2366. * @param y defines the second coordinate
  2367. * @returns the current updated Vector2
  2368. */
  2369. Vector2.prototype.set = function (x, y) {
  2370. return this.copyFromFloats(x, y);
  2371. };
  2372. /**
  2373. * Add another vector with the current one
  2374. * @param otherVector defines the other vector
  2375. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2376. */
  2377. Vector2.prototype.add = function (otherVector) {
  2378. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2379. };
  2380. /**
  2381. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2382. * @param otherVector defines the other vector
  2383. * @param result defines the target vector
  2384. * @returns the unmodified current Vector2
  2385. */
  2386. Vector2.prototype.addToRef = function (otherVector, result) {
  2387. result.x = this.x + otherVector.x;
  2388. result.y = this.y + otherVector.y;
  2389. return this;
  2390. };
  2391. /**
  2392. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2393. * @param otherVector defines the other vector
  2394. * @returns the current updated Vector2
  2395. */
  2396. Vector2.prototype.addInPlace = function (otherVector) {
  2397. this.x += otherVector.x;
  2398. this.y += otherVector.y;
  2399. return this;
  2400. };
  2401. /**
  2402. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2403. * @param otherVector defines the other vector
  2404. * @returns a new Vector2
  2405. */
  2406. Vector2.prototype.addVector3 = function (otherVector) {
  2407. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2408. };
  2409. /**
  2410. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2411. * @param otherVector defines the other vector
  2412. * @returns a new Vector2
  2413. */
  2414. Vector2.prototype.subtract = function (otherVector) {
  2415. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2416. };
  2417. /**
  2418. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2419. * @param otherVector defines the other vector
  2420. * @param result defines the target vector
  2421. * @returns the unmodified current Vector2
  2422. */
  2423. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2424. result.x = this.x - otherVector.x;
  2425. result.y = this.y - otherVector.y;
  2426. return this;
  2427. };
  2428. /**
  2429. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2430. * @param otherVector defines the other vector
  2431. * @returns the current updated Vector2
  2432. */
  2433. Vector2.prototype.subtractInPlace = function (otherVector) {
  2434. this.x -= otherVector.x;
  2435. this.y -= otherVector.y;
  2436. return this;
  2437. };
  2438. /**
  2439. * Multiplies in place the current Vector2 coordinates by the given ones
  2440. * @param otherVector defines the other vector
  2441. * @returns the current updated Vector2
  2442. */
  2443. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2444. this.x *= otherVector.x;
  2445. this.y *= otherVector.y;
  2446. return this;
  2447. };
  2448. /**
  2449. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2450. * @param otherVector defines the other vector
  2451. * @returns a new Vector2
  2452. */
  2453. Vector2.prototype.multiply = function (otherVector) {
  2454. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2455. };
  2456. /**
  2457. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2458. * @param otherVector defines the other vector
  2459. * @param result defines the target vector
  2460. * @returns the unmodified current Vector2
  2461. */
  2462. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2463. result.x = this.x * otherVector.x;
  2464. result.y = this.y * otherVector.y;
  2465. return this;
  2466. };
  2467. /**
  2468. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2469. * @param x defines the first coordinate
  2470. * @param y defines the second coordinate
  2471. * @returns a new Vector2
  2472. */
  2473. Vector2.prototype.multiplyByFloats = function (x, y) {
  2474. return new Vector2(this.x * x, this.y * y);
  2475. };
  2476. /**
  2477. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2478. * @param otherVector defines the other vector
  2479. * @returns a new Vector2
  2480. */
  2481. Vector2.prototype.divide = function (otherVector) {
  2482. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2483. };
  2484. /**
  2485. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2486. * @param otherVector defines the other vector
  2487. * @param result defines the target vector
  2488. * @returns the unmodified current Vector2
  2489. */
  2490. Vector2.prototype.divideToRef = function (otherVector, result) {
  2491. result.x = this.x / otherVector.x;
  2492. result.y = this.y / otherVector.y;
  2493. return this;
  2494. };
  2495. /**
  2496. * Divides the current Vector3 coordinates by the given ones
  2497. * @param otherVector defines the other vector
  2498. * @returns the current updated Vector2
  2499. */
  2500. Vector2.prototype.divideInPlace = function (otherVector) {
  2501. return this.divideToRef(otherVector, this);
  2502. };
  2503. /**
  2504. * Gets a new Vector2 with current Vector2 negated coordinates
  2505. * @returns a new Vector2
  2506. */
  2507. Vector2.prototype.negate = function () {
  2508. return new Vector2(-this.x, -this.y);
  2509. };
  2510. /**
  2511. * Multiply the Vector2 coordinates by scale
  2512. * @param scale defines the scaling factor
  2513. * @returns the current updated Vector2
  2514. */
  2515. Vector2.prototype.scaleInPlace = function (scale) {
  2516. this.x *= scale;
  2517. this.y *= scale;
  2518. return this;
  2519. };
  2520. /**
  2521. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2522. * @param scale defines the scaling factor
  2523. * @returns a new Vector2
  2524. */
  2525. Vector2.prototype.scale = function (scale) {
  2526. var result = new Vector2(0, 0);
  2527. this.scaleToRef(scale, result);
  2528. return result;
  2529. };
  2530. /**
  2531. * Scale the current Vector2 values by a factor to a given Vector2
  2532. * @param scale defines the scale factor
  2533. * @param result defines the Vector2 object where to store the result
  2534. * @returns the unmodified current Vector2
  2535. */
  2536. Vector2.prototype.scaleToRef = function (scale, result) {
  2537. result.x = this.x * scale;
  2538. result.y = this.y * scale;
  2539. return this;
  2540. };
  2541. /**
  2542. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2543. * @param scale defines the scale factor
  2544. * @param result defines the Vector2 object where to store the result
  2545. * @returns the unmodified current Vector2
  2546. */
  2547. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2548. result.x += this.x * scale;
  2549. result.y += this.y * scale;
  2550. return this;
  2551. };
  2552. /**
  2553. * Gets a boolean if two vectors are equals
  2554. * @param otherVector defines the other vector
  2555. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2556. */
  2557. Vector2.prototype.equals = function (otherVector) {
  2558. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2559. };
  2560. /**
  2561. * Gets a boolean if two vectors are equals (using an epsilon value)
  2562. * @param otherVector defines the other vector
  2563. * @param epsilon defines the minimal distance to consider equality
  2564. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2565. */
  2566. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2567. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2568. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2569. };
  2570. // Properties
  2571. /**
  2572. * Gets the length of the vector
  2573. * @returns the vector length (float)
  2574. */
  2575. Vector2.prototype.length = function () {
  2576. return Math.sqrt(this.x * this.x + this.y * this.y);
  2577. };
  2578. /**
  2579. * Gets the vector squared length
  2580. * @returns the vector squared length (float)
  2581. */
  2582. Vector2.prototype.lengthSquared = function () {
  2583. return (this.x * this.x + this.y * this.y);
  2584. };
  2585. // Methods
  2586. /**
  2587. * Normalize the vector
  2588. * @returns the current updated Vector2
  2589. */
  2590. Vector2.prototype.normalize = function () {
  2591. var len = this.length();
  2592. if (len === 0)
  2593. return this;
  2594. var num = 1.0 / len;
  2595. this.x *= num;
  2596. this.y *= num;
  2597. return this;
  2598. };
  2599. /**
  2600. * Gets a new Vector2 copied from the Vector2
  2601. * @returns a new Vector2
  2602. */
  2603. Vector2.prototype.clone = function () {
  2604. return new Vector2(this.x, this.y);
  2605. };
  2606. // Statics
  2607. /**
  2608. * Gets a new Vector2(0, 0)
  2609. * @returns a new Vector2
  2610. */
  2611. Vector2.Zero = function () {
  2612. return new Vector2(0, 0);
  2613. };
  2614. /**
  2615. * Gets a new Vector2(1, 1)
  2616. * @returns a new Vector2
  2617. */
  2618. Vector2.One = function () {
  2619. return new Vector2(1, 1);
  2620. };
  2621. /**
  2622. * Gets a new Vector2 set from the given index element of the given array
  2623. * @param array defines the data source
  2624. * @param offset defines the offset in the data source
  2625. * @returns a new Vector2
  2626. */
  2627. Vector2.FromArray = function (array, offset) {
  2628. if (offset === void 0) { offset = 0; }
  2629. return new Vector2(array[offset], array[offset + 1]);
  2630. };
  2631. /**
  2632. * Sets "result" from the given index element of the given array
  2633. * @param array defines the data source
  2634. * @param offset defines the offset in the data source
  2635. * @param result defines the target vector
  2636. */
  2637. Vector2.FromArrayToRef = function (array, offset, result) {
  2638. result.x = array[offset];
  2639. result.y = array[offset + 1];
  2640. };
  2641. /**
  2642. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2643. * @param value1 defines 1st point of control
  2644. * @param value2 defines 2nd point of control
  2645. * @param value3 defines 3rd point of control
  2646. * @param value4 defines 4th point of control
  2647. * @param amount defines the interpolation factor
  2648. * @returns a new Vector2
  2649. */
  2650. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2651. var squared = amount * amount;
  2652. var cubed = amount * squared;
  2653. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2654. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2655. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2656. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2657. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2658. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2659. return new Vector2(x, y);
  2660. };
  2661. /**
  2662. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2663. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2664. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2665. * @param value defines the value to clamp
  2666. * @param min defines the lower limit
  2667. * @param max defines the upper limit
  2668. * @returns a new Vector2
  2669. */
  2670. Vector2.Clamp = function (value, min, max) {
  2671. var x = value.x;
  2672. x = (x > max.x) ? max.x : x;
  2673. x = (x < min.x) ? min.x : x;
  2674. var y = value.y;
  2675. y = (y > max.y) ? max.y : y;
  2676. y = (y < min.y) ? min.y : y;
  2677. return new Vector2(x, y);
  2678. };
  2679. /**
  2680. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2681. * @param value1 defines the 1st control point
  2682. * @param tangent1 defines the outgoing tangent
  2683. * @param value2 defines the 2nd control point
  2684. * @param tangent2 defines the incoming tangent
  2685. * @param amount defines the interpolation factor
  2686. * @returns a new Vector2
  2687. */
  2688. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2689. var squared = amount * amount;
  2690. var cubed = amount * squared;
  2691. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2692. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2693. var part3 = (cubed - (2.0 * squared)) + amount;
  2694. var part4 = cubed - squared;
  2695. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2696. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2697. return new Vector2(x, y);
  2698. };
  2699. /**
  2700. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2701. * @param start defines the start vector
  2702. * @param end defines the end vector
  2703. * @param amount defines the interpolation factor
  2704. * @returns a new Vector2
  2705. */
  2706. Vector2.Lerp = function (start, end, amount) {
  2707. var x = start.x + ((end.x - start.x) * amount);
  2708. var y = start.y + ((end.y - start.y) * amount);
  2709. return new Vector2(x, y);
  2710. };
  2711. /**
  2712. * Gets the dot product of the vector "left" and the vector "right"
  2713. * @param left defines first vector
  2714. * @param right defines second vector
  2715. * @returns the dot product (float)
  2716. */
  2717. Vector2.Dot = function (left, right) {
  2718. return left.x * right.x + left.y * right.y;
  2719. };
  2720. /**
  2721. * Returns a new Vector2 equal to the normalized given vector
  2722. * @param vector defines the vector to normalize
  2723. * @returns a new Vector2
  2724. */
  2725. Vector2.Normalize = function (vector) {
  2726. var newVector = vector.clone();
  2727. newVector.normalize();
  2728. return newVector;
  2729. };
  2730. /**
  2731. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2732. * @param left defines 1st vector
  2733. * @param right defines 2nd vector
  2734. * @returns a new Vector2
  2735. */
  2736. Vector2.Minimize = function (left, right) {
  2737. var x = (left.x < right.x) ? left.x : right.x;
  2738. var y = (left.y < right.y) ? left.y : right.y;
  2739. return new Vector2(x, y);
  2740. };
  2741. /**
  2742. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2743. * @param left defines 1st vector
  2744. * @param right defines 2nd vector
  2745. * @returns a new Vector2
  2746. */
  2747. Vector2.Maximize = function (left, right) {
  2748. var x = (left.x > right.x) ? left.x : right.x;
  2749. var y = (left.y > right.y) ? left.y : right.y;
  2750. return new Vector2(x, y);
  2751. };
  2752. /**
  2753. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2754. * @param vector defines the vector to transform
  2755. * @param transformation defines the matrix to apply
  2756. * @returns a new Vector2
  2757. */
  2758. Vector2.Transform = function (vector, transformation) {
  2759. var r = Vector2.Zero();
  2760. Vector2.TransformToRef(vector, transformation, r);
  2761. return r;
  2762. };
  2763. /**
  2764. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2765. * @param vector defines the vector to transform
  2766. * @param transformation defines the matrix to apply
  2767. * @param result defines the target vector
  2768. */
  2769. Vector2.TransformToRef = function (vector, transformation, result) {
  2770. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2771. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2772. result.x = x;
  2773. result.y = y;
  2774. };
  2775. /**
  2776. * Determines if a given vector is included in a triangle
  2777. * @param p defines the vector to test
  2778. * @param p0 defines 1st triangle point
  2779. * @param p1 defines 2nd triangle point
  2780. * @param p2 defines 3rd triangle point
  2781. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2782. */
  2783. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2784. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2785. var sign = a < 0 ? -1 : 1;
  2786. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2787. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2788. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2789. };
  2790. /**
  2791. * Gets the distance between the vectors "value1" and "value2"
  2792. * @param value1 defines first vector
  2793. * @param value2 defines second vector
  2794. * @returns the distance between vectors
  2795. */
  2796. Vector2.Distance = function (value1, value2) {
  2797. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2798. };
  2799. /**
  2800. * Returns the squared distance between the vectors "value1" and "value2"
  2801. * @param value1 defines first vector
  2802. * @param value2 defines second vector
  2803. * @returns the squared distance between vectors
  2804. */
  2805. Vector2.DistanceSquared = function (value1, value2) {
  2806. var x = value1.x - value2.x;
  2807. var y = value1.y - value2.y;
  2808. return (x * x) + (y * y);
  2809. };
  2810. /**
  2811. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2812. * @param value1 defines first vector
  2813. * @param value2 defines second vector
  2814. * @returns a new Vector2
  2815. */
  2816. Vector2.Center = function (value1, value2) {
  2817. var center = value1.add(value2);
  2818. center.scaleInPlace(0.5);
  2819. return center;
  2820. };
  2821. /**
  2822. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2823. * @param p defines the middle point
  2824. * @param segA defines one point of the segment
  2825. * @param segB defines the other point of the segment
  2826. * @returns the shortest distance
  2827. */
  2828. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2829. var l2 = Vector2.DistanceSquared(segA, segB);
  2830. if (l2 === 0.0) {
  2831. return Vector2.Distance(p, segA);
  2832. }
  2833. var v = segB.subtract(segA);
  2834. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2835. var proj = segA.add(v.multiplyByFloats(t, t));
  2836. return Vector2.Distance(p, proj);
  2837. };
  2838. return Vector2;
  2839. }());
  2840. BABYLON.Vector2 = Vector2;
  2841. /**
  2842. * Classed used to store (x,y,z) vector representation
  2843. * A Vector3 is the main object used in 3D geometry
  2844. * It can represent etiher the coordinates of a point the space, either a direction
  2845. * Reminder: Babylon.js uses a left handed forward facing system
  2846. */
  2847. var Vector3 = /** @class */ (function () {
  2848. /**
  2849. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2850. * @param x defines the first coordinates (on X axis)
  2851. * @param y defines the second coordinates (on Y axis)
  2852. * @param z defines the third coordinates (on Z axis)
  2853. */
  2854. function Vector3(
  2855. /**
  2856. * Defines the first coordinates (on X axis)
  2857. */
  2858. x,
  2859. /**
  2860. * Defines the second coordinates (on Y axis)
  2861. */
  2862. y,
  2863. /**
  2864. * Defines the third coordinates (on Z axis)
  2865. */
  2866. z) {
  2867. this.x = x;
  2868. this.y = y;
  2869. this.z = z;
  2870. }
  2871. /**
  2872. * Creates a string representation of the Vector3
  2873. * @returns a string with the Vector3 coordinates.
  2874. */
  2875. Vector3.prototype.toString = function () {
  2876. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2877. };
  2878. /**
  2879. * Gets the class name
  2880. * @returns the string "Vector3"
  2881. */
  2882. Vector3.prototype.getClassName = function () {
  2883. return "Vector3";
  2884. };
  2885. /**
  2886. * Creates the Vector3 hash code
  2887. * @returns a number which tends to be unique between Vector3 instances
  2888. */
  2889. Vector3.prototype.getHashCode = function () {
  2890. var hash = this.x || 0;
  2891. hash = (hash * 397) ^ (this.y || 0);
  2892. hash = (hash * 397) ^ (this.z || 0);
  2893. return hash;
  2894. };
  2895. // Operators
  2896. /**
  2897. * Creates an array containing three elements : the coordinates of the Vector3
  2898. * @returns a new array of numbers
  2899. */
  2900. Vector3.prototype.asArray = function () {
  2901. var result = [];
  2902. this.toArray(result, 0);
  2903. return result;
  2904. };
  2905. /**
  2906. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2907. * @param array defines the destination array
  2908. * @param index defines the offset in the destination array
  2909. * @returns the current Vector3
  2910. */
  2911. Vector3.prototype.toArray = function (array, index) {
  2912. if (index === void 0) { index = 0; }
  2913. array[index] = this.x;
  2914. array[index + 1] = this.y;
  2915. array[index + 2] = this.z;
  2916. return this;
  2917. };
  2918. /**
  2919. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2920. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2921. */
  2922. Vector3.prototype.toQuaternion = function () {
  2923. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2924. };
  2925. /**
  2926. * Adds the given vector to the current Vector3
  2927. * @param otherVector defines the second operand
  2928. * @returns the current updated Vector3
  2929. */
  2930. Vector3.prototype.addInPlace = function (otherVector) {
  2931. this.x += otherVector.x;
  2932. this.y += otherVector.y;
  2933. this.z += otherVector.z;
  2934. return this;
  2935. };
  2936. /**
  2937. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2938. * @param otherVector defines the second operand
  2939. * @returns the resulting Vector3
  2940. */
  2941. Vector3.prototype.add = function (otherVector) {
  2942. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2943. };
  2944. /**
  2945. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2946. * @param otherVector defines the second operand
  2947. * @param result defines the Vector3 object where to store the result
  2948. * @returns the current Vector3
  2949. */
  2950. Vector3.prototype.addToRef = function (otherVector, result) {
  2951. result.x = this.x + otherVector.x;
  2952. result.y = this.y + otherVector.y;
  2953. result.z = this.z + otherVector.z;
  2954. return this;
  2955. };
  2956. /**
  2957. * Subtract the given vector from the current Vector3
  2958. * @param otherVector defines the second operand
  2959. * @returns the current updated Vector3
  2960. */
  2961. Vector3.prototype.subtractInPlace = function (otherVector) {
  2962. this.x -= otherVector.x;
  2963. this.y -= otherVector.y;
  2964. this.z -= otherVector.z;
  2965. return this;
  2966. };
  2967. /**
  2968. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2969. * @param otherVector defines the second operand
  2970. * @returns the resulting Vector3
  2971. */
  2972. Vector3.prototype.subtract = function (otherVector) {
  2973. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2974. };
  2975. /**
  2976. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2977. * @param otherVector defines the second operand
  2978. * @param result defines the Vector3 object where to store the result
  2979. * @returns the current Vector3
  2980. */
  2981. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2982. result.x = this.x - otherVector.x;
  2983. result.y = this.y - otherVector.y;
  2984. result.z = this.z - otherVector.z;
  2985. return this;
  2986. };
  2987. /**
  2988. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2989. * @param x defines the x coordinate of the operand
  2990. * @param y defines the y coordinate of the operand
  2991. * @param z defines the z coordinate of the operand
  2992. * @returns the resulting Vector3
  2993. */
  2994. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2995. return new Vector3(this.x - x, this.y - y, this.z - z);
  2996. };
  2997. /**
  2998. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2999. * @param x defines the x coordinate of the operand
  3000. * @param y defines the y coordinate of the operand
  3001. * @param z defines the z coordinate of the operand
  3002. * @param result defines the Vector3 object where to store the result
  3003. * @returns the current Vector3
  3004. */
  3005. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  3006. result.x = this.x - x;
  3007. result.y = this.y - y;
  3008. result.z = this.z - z;
  3009. return this;
  3010. };
  3011. /**
  3012. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3013. * @returns a new Vector3
  3014. */
  3015. Vector3.prototype.negate = function () {
  3016. return new Vector3(-this.x, -this.y, -this.z);
  3017. };
  3018. /**
  3019. * Multiplies the Vector3 coordinates by the float "scale"
  3020. * @param scale defines the multiplier factor
  3021. * @returns the current updated Vector3
  3022. */
  3023. Vector3.prototype.scaleInPlace = function (scale) {
  3024. this.x *= scale;
  3025. this.y *= scale;
  3026. this.z *= scale;
  3027. return this;
  3028. };
  3029. /**
  3030. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3031. * @param scale defines the multiplier factor
  3032. * @returns a new Vector3
  3033. */
  3034. Vector3.prototype.scale = function (scale) {
  3035. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3036. };
  3037. /**
  3038. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3039. * @param scale defines the multiplier factor
  3040. * @param result defines the Vector3 object where to store the result
  3041. * @returns the current Vector3
  3042. */
  3043. Vector3.prototype.scaleToRef = function (scale, result) {
  3044. result.x = this.x * scale;
  3045. result.y = this.y * scale;
  3046. result.z = this.z * scale;
  3047. return this;
  3048. };
  3049. /**
  3050. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3051. * @param scale defines the scale factor
  3052. * @param result defines the Vector3 object where to store the result
  3053. * @returns the unmodified current Vector3
  3054. */
  3055. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3056. result.x += this.x * scale;
  3057. result.y += this.y * scale;
  3058. result.z += this.z * scale;
  3059. return this;
  3060. };
  3061. /**
  3062. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3063. * @param otherVector defines the second operand
  3064. * @returns true if both vectors are equals
  3065. */
  3066. Vector3.prototype.equals = function (otherVector) {
  3067. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3068. };
  3069. /**
  3070. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3071. * @param otherVector defines the second operand
  3072. * @param epsilon defines the minimal distance to define values as equals
  3073. * @returns true if both vectors are distant less than epsilon
  3074. */
  3075. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3076. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3077. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  3078. };
  3079. /**
  3080. * Returns true if the current Vector3 coordinates equals the given floats
  3081. * @param x defines the x coordinate of the operand
  3082. * @param y defines the y coordinate of the operand
  3083. * @param z defines the z coordinate of the operand
  3084. * @returns true if both vectors are equals
  3085. */
  3086. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3087. return this.x === x && this.y === y && this.z === z;
  3088. };
  3089. /**
  3090. * Multiplies the current Vector3 coordinates by the given ones
  3091. * @param otherVector defines the second operand
  3092. * @returns the current updated Vector3
  3093. */
  3094. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3095. this.x *= otherVector.x;
  3096. this.y *= otherVector.y;
  3097. this.z *= otherVector.z;
  3098. return this;
  3099. };
  3100. /**
  3101. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3102. * @param otherVector defines the second operand
  3103. * @returns the new Vector3
  3104. */
  3105. Vector3.prototype.multiply = function (otherVector) {
  3106. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3107. };
  3108. /**
  3109. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3110. * @param otherVector defines the second operand
  3111. * @param result defines the Vector3 object where to store the result
  3112. * @returns the current Vector3
  3113. */
  3114. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3115. result.x = this.x * otherVector.x;
  3116. result.y = this.y * otherVector.y;
  3117. result.z = this.z * otherVector.z;
  3118. return this;
  3119. };
  3120. /**
  3121. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3122. * @param x defines the x coordinate of the operand
  3123. * @param y defines the y coordinate of the operand
  3124. * @param z defines the z coordinate of the operand
  3125. * @returns the new Vector3
  3126. */
  3127. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3128. return new Vector3(this.x * x, this.y * y, this.z * z);
  3129. };
  3130. /**
  3131. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3132. * @param otherVector defines the second operand
  3133. * @returns the new Vector3
  3134. */
  3135. Vector3.prototype.divide = function (otherVector) {
  3136. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3137. };
  3138. /**
  3139. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3140. * @param otherVector defines the second operand
  3141. * @param result defines the Vector3 object where to store the result
  3142. * @returns the current Vector3
  3143. */
  3144. Vector3.prototype.divideToRef = function (otherVector, result) {
  3145. result.x = this.x / otherVector.x;
  3146. result.y = this.y / otherVector.y;
  3147. result.z = this.z / otherVector.z;
  3148. return this;
  3149. };
  3150. /**
  3151. * Divides the current Vector3 coordinates by the given ones.
  3152. * @param otherVector defines the second operand
  3153. * @returns the current updated Vector3
  3154. */
  3155. Vector3.prototype.divideInPlace = function (otherVector) {
  3156. return this.divideToRef(otherVector, this);
  3157. };
  3158. /**
  3159. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3160. * @param other defines the second operand
  3161. * @returns the current updated Vector3
  3162. */
  3163. Vector3.prototype.minimizeInPlace = function (other) {
  3164. if (other.x < this.x)
  3165. this.x = other.x;
  3166. if (other.y < this.y)
  3167. this.y = other.y;
  3168. if (other.z < this.z)
  3169. this.z = other.z;
  3170. return this;
  3171. };
  3172. /**
  3173. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3174. * @param other defines the second operand
  3175. * @returns the current updated Vector3
  3176. */
  3177. Vector3.prototype.maximizeInPlace = function (other) {
  3178. if (other.x > this.x)
  3179. this.x = other.x;
  3180. if (other.y > this.y)
  3181. this.y = other.y;
  3182. if (other.z > this.z)
  3183. this.z = other.z;
  3184. return this;
  3185. };
  3186. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3187. /**
  3188. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3189. */
  3190. get: function () {
  3191. var absX = Math.abs(this.x);
  3192. var absY = Math.abs(this.y);
  3193. if (absX !== absY) {
  3194. return true;
  3195. }
  3196. var absZ = Math.abs(this.z);
  3197. if (absX !== absZ) {
  3198. return true;
  3199. }
  3200. if (absY !== absZ) {
  3201. return true;
  3202. }
  3203. return false;
  3204. },
  3205. enumerable: true,
  3206. configurable: true
  3207. });
  3208. // Properties
  3209. /**
  3210. * Gets the length of the Vector3
  3211. * @returns the length of the Vecto3
  3212. */
  3213. Vector3.prototype.length = function () {
  3214. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3215. };
  3216. /**
  3217. * Gets the squared length of the Vector3
  3218. * @returns squared length of the Vector3
  3219. */
  3220. Vector3.prototype.lengthSquared = function () {
  3221. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3222. };
  3223. /**
  3224. * Normalize the current Vector3.
  3225. * Please note that this is an in place operation.
  3226. * @returns the current updated Vector3
  3227. */
  3228. Vector3.prototype.normalize = function () {
  3229. var len = this.length();
  3230. if (len === 0 || len === 1.0)
  3231. return this;
  3232. var num = 1.0 / len;
  3233. this.x *= num;
  3234. this.y *= num;
  3235. this.z *= num;
  3236. return this;
  3237. };
  3238. /**
  3239. * Normalize the current Vector3 to a new vector
  3240. * @returns the new Vector3
  3241. */
  3242. Vector3.prototype.normalizeToNew = function () {
  3243. var normalized = new Vector3(0, 0, 0);
  3244. this.normalizeToRef(normalized);
  3245. return normalized;
  3246. };
  3247. /**
  3248. * Normalize the current Vector3 to the reference
  3249. * @param reference define the Vector3 to update
  3250. * @returns the updated Vector3
  3251. */
  3252. Vector3.prototype.normalizeToRef = function (reference) {
  3253. var len = this.length();
  3254. if (len === 0 || len === 1.0) {
  3255. reference.set(this.x, this.y, this.z);
  3256. return reference;
  3257. }
  3258. var scale = 1.0 / len;
  3259. this.scaleToRef(scale, reference);
  3260. return reference;
  3261. };
  3262. /**
  3263. * Creates a new Vector3 copied from the current Vector3
  3264. * @returns the new Vector3
  3265. */
  3266. Vector3.prototype.clone = function () {
  3267. return new Vector3(this.x, this.y, this.z);
  3268. };
  3269. /**
  3270. * Copies the given vector coordinates to the current Vector3 ones
  3271. * @param source defines the source Vector3
  3272. * @returns the current updated Vector3
  3273. */
  3274. Vector3.prototype.copyFrom = function (source) {
  3275. this.x = source.x;
  3276. this.y = source.y;
  3277. this.z = source.z;
  3278. return this;
  3279. };
  3280. /**
  3281. * Copies the given floats to the current Vector3 coordinates
  3282. * @param x defines the x coordinate of the operand
  3283. * @param y defines the y coordinate of the operand
  3284. * @param z defines the z coordinate of the operand
  3285. * @returns the current updated Vector3
  3286. */
  3287. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3288. this.x = x;
  3289. this.y = y;
  3290. this.z = z;
  3291. return this;
  3292. };
  3293. /**
  3294. * Copies the given floats to the current Vector3 coordinates
  3295. * @param x defines the x coordinate of the operand
  3296. * @param y defines the y coordinate of the operand
  3297. * @param z defines the z coordinate of the operand
  3298. * @returns the current updated Vector3
  3299. */
  3300. Vector3.prototype.set = function (x, y, z) {
  3301. return this.copyFromFloats(x, y, z);
  3302. };
  3303. // Statics
  3304. /**
  3305. * Get the clip factor between two vectors
  3306. * @param vector0 defines the first operand
  3307. * @param vector1 defines the second operand
  3308. * @param axis defines the axis to use
  3309. * @param size defines the size along the axis
  3310. * @returns the clip factor
  3311. */
  3312. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3313. var d0 = Vector3.Dot(vector0, axis) - size;
  3314. var d1 = Vector3.Dot(vector1, axis) - size;
  3315. var s = d0 / (d0 - d1);
  3316. return s;
  3317. };
  3318. /**
  3319. * Get angle between two vectors
  3320. * @param vector0 angle between vector0 and vector1
  3321. * @param vector1 angle between vector0 and vector1
  3322. * @param normal direction of the normal
  3323. * @return the angle between vector0 and vector1
  3324. */
  3325. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3326. var v0 = vector0.clone().normalize();
  3327. var v1 = vector1.clone().normalize();
  3328. var dot = Vector3.Dot(v0, v1);
  3329. var n = Vector3.Cross(v0, v1);
  3330. if (Vector3.Dot(n, normal) > 0) {
  3331. return Math.acos(dot);
  3332. }
  3333. return -Math.acos(dot);
  3334. };
  3335. /**
  3336. * Returns a new Vector3 set from the index "offset" of the given array
  3337. * @param array defines the source array
  3338. * @param offset defines the offset in the source array
  3339. * @returns the new Vector3
  3340. */
  3341. Vector3.FromArray = function (array, offset) {
  3342. if (!offset) {
  3343. offset = 0;
  3344. }
  3345. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3346. };
  3347. /**
  3348. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3349. * This function is deprecated. Use FromArray instead
  3350. * @param array defines the source array
  3351. * @param offset defines the offset in the source array
  3352. * @returns the new Vector3
  3353. */
  3354. Vector3.FromFloatArray = function (array, offset) {
  3355. return Vector3.FromArray(array, offset);
  3356. };
  3357. /**
  3358. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3359. * @param array defines the source array
  3360. * @param offset defines the offset in the source array
  3361. * @param result defines the Vector3 where to store the result
  3362. */
  3363. Vector3.FromArrayToRef = function (array, offset, result) {
  3364. result.x = array[offset];
  3365. result.y = array[offset + 1];
  3366. result.z = array[offset + 2];
  3367. };
  3368. /**
  3369. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3370. * This function is deprecated. Use FromArrayToRef instead.
  3371. * @param array defines the source array
  3372. * @param offset defines the offset in the source array
  3373. * @param result defines the Vector3 where to store the result
  3374. */
  3375. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3376. return Vector3.FromArrayToRef(array, offset, result);
  3377. };
  3378. /**
  3379. * Sets the given vector "result" with the given floats.
  3380. * @param x defines the x coordinate of the source
  3381. * @param y defines the y coordinate of the source
  3382. * @param z defines the z coordinate of the source
  3383. * @param result defines the Vector3 where to store the result
  3384. */
  3385. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3386. result.x = x;
  3387. result.y = y;
  3388. result.z = z;
  3389. };
  3390. /**
  3391. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3392. * @returns a new empty Vector3
  3393. */
  3394. Vector3.Zero = function () {
  3395. return new Vector3(0.0, 0.0, 0.0);
  3396. };
  3397. /**
  3398. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3399. * @returns a new unit Vector3
  3400. */
  3401. Vector3.One = function () {
  3402. return new Vector3(1.0, 1.0, 1.0);
  3403. };
  3404. /**
  3405. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3406. * @returns a new up Vector3
  3407. */
  3408. Vector3.Up = function () {
  3409. return new Vector3(0.0, 1.0, 0.0);
  3410. };
  3411. /**
  3412. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3413. * @returns a new forward Vector3
  3414. */
  3415. Vector3.Forward = function () {
  3416. return new Vector3(0.0, 0.0, 1.0);
  3417. };
  3418. /**
  3419. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3420. * @returns a new right Vector3
  3421. */
  3422. Vector3.Right = function () {
  3423. return new Vector3(1.0, 0.0, 0.0);
  3424. };
  3425. /**
  3426. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3427. * @returns a new left Vector3
  3428. */
  3429. Vector3.Left = function () {
  3430. return new Vector3(-1.0, 0.0, 0.0);
  3431. };
  3432. /**
  3433. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3434. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3435. * @param vector defines the Vector3 to transform
  3436. * @param transformation defines the transformation matrix
  3437. * @returns the transformed Vector3
  3438. */
  3439. Vector3.TransformCoordinates = function (vector, transformation) {
  3440. var result = Vector3.Zero();
  3441. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3442. return result;
  3443. };
  3444. /**
  3445. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3446. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3447. * @param vector defines the Vector3 to transform
  3448. * @param transformation defines the transformation matrix
  3449. * @param result defines the Vector3 where to store the result
  3450. */
  3451. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3452. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3453. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3454. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3455. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3456. result.x = x / w;
  3457. result.y = y / w;
  3458. result.z = z / w;
  3459. };
  3460. /**
  3461. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3462. * This method computes tranformed coordinates only, not transformed direction vectors
  3463. * @param x define the x coordinate of the source vector
  3464. * @param y define the y coordinate of the source vector
  3465. * @param z define the z coordinate of the source vector
  3466. * @param transformation defines the transformation matrix
  3467. * @param result defines the Vector3 where to store the result
  3468. */
  3469. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3470. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3471. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3472. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3473. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3474. result.x = rx / rw;
  3475. result.y = ry / rw;
  3476. result.z = rz / rw;
  3477. };
  3478. /**
  3479. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3480. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3481. * @param vector defines the Vector3 to transform
  3482. * @param transformation defines the transformation matrix
  3483. * @returns the new Vector3
  3484. */
  3485. Vector3.TransformNormal = function (vector, transformation) {
  3486. var result = Vector3.Zero();
  3487. Vector3.TransformNormalToRef(vector, transformation, result);
  3488. return result;
  3489. };
  3490. /**
  3491. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3492. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3493. * @param vector defines the Vector3 to transform
  3494. * @param transformation defines the transformation matrix
  3495. * @param result defines the Vector3 where to store the result
  3496. */
  3497. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3498. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3499. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3500. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3501. result.x = x;
  3502. result.y = y;
  3503. result.z = z;
  3504. };
  3505. /**
  3506. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3507. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3508. * @param x define the x coordinate of the source vector
  3509. * @param y define the y coordinate of the source vector
  3510. * @param z define the z coordinate of the source vector
  3511. * @param transformation defines the transformation matrix
  3512. * @param result defines the Vector3 where to store the result
  3513. */
  3514. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3515. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3516. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3517. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3518. };
  3519. /**
  3520. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3521. * @param value1 defines the first control point
  3522. * @param value2 defines the second control point
  3523. * @param value3 defines the third control point
  3524. * @param value4 defines the fourth control point
  3525. * @param amount defines the amount on the spline to use
  3526. * @returns the new Vector3
  3527. */
  3528. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3529. var squared = amount * amount;
  3530. var cubed = amount * squared;
  3531. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3532. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3533. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3534. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3535. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3536. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3537. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3538. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3539. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3540. return new Vector3(x, y, z);
  3541. };
  3542. /**
  3543. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3544. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3545. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3546. * @param value defines the current value
  3547. * @param min defines the lower range value
  3548. * @param max defines the upper range value
  3549. * @returns the new Vector3
  3550. */
  3551. Vector3.Clamp = function (value, min, max) {
  3552. var x = value.x;
  3553. x = (x > max.x) ? max.x : x;
  3554. x = (x < min.x) ? min.x : x;
  3555. var y = value.y;
  3556. y = (y > max.y) ? max.y : y;
  3557. y = (y < min.y) ? min.y : y;
  3558. var z = value.z;
  3559. z = (z > max.z) ? max.z : z;
  3560. z = (z < min.z) ? min.z : z;
  3561. return new Vector3(x, y, z);
  3562. };
  3563. /**
  3564. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3565. * @param value1 defines the first control point
  3566. * @param tangent1 defines the first tangent vector
  3567. * @param value2 defines the second control point
  3568. * @param tangent2 defines the second tangent vector
  3569. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3570. * @returns the new Vector3
  3571. */
  3572. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3573. var squared = amount * amount;
  3574. var cubed = amount * squared;
  3575. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3576. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3577. var part3 = (cubed - (2.0 * squared)) + amount;
  3578. var part4 = cubed - squared;
  3579. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3580. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3581. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3582. return new Vector3(x, y, z);
  3583. };
  3584. /**
  3585. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3586. * @param start defines the start value
  3587. * @param end defines the end value
  3588. * @param amount max defines amount between both (between 0 and 1)
  3589. * @returns the new Vector3
  3590. */
  3591. Vector3.Lerp = function (start, end, amount) {
  3592. var result = new Vector3(0, 0, 0);
  3593. Vector3.LerpToRef(start, end, amount, result);
  3594. return result;
  3595. };
  3596. /**
  3597. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3598. * @param start defines the start value
  3599. * @param end defines the end value
  3600. * @param amount max defines amount between both (between 0 and 1)
  3601. * @param result defines the Vector3 where to store the result
  3602. */
  3603. Vector3.LerpToRef = function (start, end, amount, result) {
  3604. result.x = start.x + ((end.x - start.x) * amount);
  3605. result.y = start.y + ((end.y - start.y) * amount);
  3606. result.z = start.z + ((end.z - start.z) * amount);
  3607. };
  3608. /**
  3609. * Returns the dot product (float) between the vectors "left" and "right"
  3610. * @param left defines the left operand
  3611. * @param right defines the right operand
  3612. * @returns the dot product
  3613. */
  3614. Vector3.Dot = function (left, right) {
  3615. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3616. };
  3617. /**
  3618. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3619. * The cross product is then orthogonal to both "left" and "right"
  3620. * @param left defines the left operand
  3621. * @param right defines the right operand
  3622. * @returns the cross product
  3623. */
  3624. Vector3.Cross = function (left, right) {
  3625. var result = Vector3.Zero();
  3626. Vector3.CrossToRef(left, right, result);
  3627. return result;
  3628. };
  3629. /**
  3630. * Sets the given vector "result" with the cross product of "left" and "right"
  3631. * The cross product is then orthogonal to both "left" and "right"
  3632. * @param left defines the left operand
  3633. * @param right defines the right operand
  3634. * @param result defines the Vector3 where to store the result
  3635. */
  3636. Vector3.CrossToRef = function (left, right, result) {
  3637. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3638. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3639. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3640. result.copyFrom(MathTmp.Vector3[0]);
  3641. };
  3642. /**
  3643. * Returns a new Vector3 as the normalization of the given vector
  3644. * @param vector defines the Vector3 to normalize
  3645. * @returns the new Vector3
  3646. */
  3647. Vector3.Normalize = function (vector) {
  3648. var result = Vector3.Zero();
  3649. Vector3.NormalizeToRef(vector, result);
  3650. return result;
  3651. };
  3652. /**
  3653. * Sets the given vector "result" with the normalization of the given first vector
  3654. * @param vector defines the Vector3 to normalize
  3655. * @param result defines the Vector3 where to store the result
  3656. */
  3657. Vector3.NormalizeToRef = function (vector, result) {
  3658. result.copyFrom(vector);
  3659. result.normalize();
  3660. };
  3661. /**
  3662. * Project a Vector3 onto screen space
  3663. * @param vector defines the Vector3 to project
  3664. * @param world defines the world matrix to use
  3665. * @param transform defines the transform (view x projection) matrix to use
  3666. * @param viewport defines the screen viewport to use
  3667. * @returns the new Vector3
  3668. */
  3669. Vector3.Project = function (vector, world, transform, viewport) {
  3670. var cw = viewport.width;
  3671. var ch = viewport.height;
  3672. var cx = viewport.x;
  3673. var cy = viewport.y;
  3674. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3675. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3676. var matrix = MathTmp.Matrix[0];
  3677. world.multiplyToRef(transform, matrix);
  3678. matrix.multiplyToRef(viewportMatrix, matrix);
  3679. return Vector3.TransformCoordinates(vector, matrix);
  3680. };
  3681. /**
  3682. * Unproject from screen space to object space
  3683. * @param source defines the screen space Vector3 to use
  3684. * @param viewportWidth defines the current width of the viewport
  3685. * @param viewportHeight defines the current height of the viewport
  3686. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3687. * @param transform defines the transform (view x projection) matrix to use
  3688. * @returns the new Vector3
  3689. */
  3690. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3691. var matrix = MathTmp.Matrix[0];
  3692. world.multiplyToRef(transform, matrix);
  3693. matrix.invert();
  3694. source.x = source.x / viewportWidth * 2 - 1;
  3695. source.y = -(source.y / viewportHeight * 2 - 1);
  3696. var vector = Vector3.TransformCoordinates(source, matrix);
  3697. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3698. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3699. vector = vector.scale(1.0 / num);
  3700. }
  3701. return vector;
  3702. };
  3703. /**
  3704. * Unproject from screen space to object space
  3705. * @param source defines the screen space Vector3 to use
  3706. * @param viewportWidth defines the current width of the viewport
  3707. * @param viewportHeight defines the current height of the viewport
  3708. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3709. * @param view defines the view matrix to use
  3710. * @param projection defines the projection matrix to use
  3711. * @returns the new Vector3
  3712. */
  3713. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3714. var result = Vector3.Zero();
  3715. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3716. return result;
  3717. };
  3718. /**
  3719. * Unproject from screen space to object space
  3720. * @param source defines the screen space Vector3 to use
  3721. * @param viewportWidth defines the current width of the viewport
  3722. * @param viewportHeight defines the current height of the viewport
  3723. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3724. * @param view defines the view matrix to use
  3725. * @param projection defines the projection matrix to use
  3726. * @param result defines the Vector3 where to store the result
  3727. */
  3728. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3729. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3730. };
  3731. /**
  3732. * Unproject from screen space to object space
  3733. * @param sourceX defines the screen space x coordinate to use
  3734. * @param sourceY defines the screen space y coordinate to use
  3735. * @param sourceZ defines the screen space z coordinate to use
  3736. * @param viewportWidth defines the current width of the viewport
  3737. * @param viewportHeight defines the current height of the viewport
  3738. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3739. * @param view defines the view matrix to use
  3740. * @param projection defines the projection matrix to use
  3741. * @param result defines the Vector3 where to store the result
  3742. */
  3743. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3744. var matrix = MathTmp.Matrix[0];
  3745. world.multiplyToRef(view, matrix);
  3746. matrix.multiplyToRef(projection, matrix);
  3747. matrix.invert();
  3748. var screenSource = MathTmp.Vector3[0];
  3749. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3750. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3751. screenSource.z = 2 * sourceZ - 1.0;
  3752. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3753. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3754. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3755. result.scaleInPlace(1.0 / num);
  3756. }
  3757. };
  3758. /**
  3759. * Gets the minimal coordinate values between two Vector3
  3760. * @param left defines the first operand
  3761. * @param right defines the second operand
  3762. * @returns the new Vector3
  3763. */
  3764. Vector3.Minimize = function (left, right) {
  3765. var min = left.clone();
  3766. min.minimizeInPlace(right);
  3767. return min;
  3768. };
  3769. /**
  3770. * Gets the maximal coordinate values between two Vector3
  3771. * @param left defines the first operand
  3772. * @param right defines the second operand
  3773. * @returns the new Vector3
  3774. */
  3775. Vector3.Maximize = function (left, right) {
  3776. var max = left.clone();
  3777. max.maximizeInPlace(right);
  3778. return max;
  3779. };
  3780. /**
  3781. * Returns the distance between the vectors "value1" and "value2"
  3782. * @param value1 defines the first operand
  3783. * @param value2 defines the second operand
  3784. * @returns the distance
  3785. */
  3786. Vector3.Distance = function (value1, value2) {
  3787. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3788. };
  3789. /**
  3790. * Returns the squared distance between the vectors "value1" and "value2"
  3791. * @param value1 defines the first operand
  3792. * @param value2 defines the second operand
  3793. * @returns the squared distance
  3794. */
  3795. Vector3.DistanceSquared = function (value1, value2) {
  3796. var x = value1.x - value2.x;
  3797. var y = value1.y - value2.y;
  3798. var z = value1.z - value2.z;
  3799. return (x * x) + (y * y) + (z * z);
  3800. };
  3801. /**
  3802. * Returns a new Vector3 located at the center between "value1" and "value2"
  3803. * @param value1 defines the first operand
  3804. * @param value2 defines the second operand
  3805. * @returns the new Vector3
  3806. */
  3807. Vector3.Center = function (value1, value2) {
  3808. var center = value1.add(value2);
  3809. center.scaleInPlace(0.5);
  3810. return center;
  3811. };
  3812. /**
  3813. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3814. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3815. * to something in order to rotate it from its local system to the given target system
  3816. * Note: axis1, axis2 and axis3 are normalized during this operation
  3817. * @param axis1 defines the first axis
  3818. * @param axis2 defines the second axis
  3819. * @param axis3 defines the third axis
  3820. * @returns a new Vector3
  3821. */
  3822. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3823. var rotation = Vector3.Zero();
  3824. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3825. return rotation;
  3826. };
  3827. /**
  3828. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3829. * @param axis1 defines the first axis
  3830. * @param axis2 defines the second axis
  3831. * @param axis3 defines the third axis
  3832. * @param ref defines the Vector3 where to store the result
  3833. */
  3834. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3835. var quat = MathTmp.Quaternion[0];
  3836. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3837. quat.toEulerAnglesToRef(ref);
  3838. };
  3839. return Vector3;
  3840. }());
  3841. BABYLON.Vector3 = Vector3;
  3842. //Vector4 class created for EulerAngle class conversion to Quaternion
  3843. var Vector4 = /** @class */ (function () {
  3844. /**
  3845. * Creates a Vector4 object from the given floats.
  3846. */
  3847. function Vector4(x, y, z, w) {
  3848. this.x = x;
  3849. this.y = y;
  3850. this.z = z;
  3851. this.w = w;
  3852. }
  3853. /**
  3854. * Returns the string with the Vector4 coordinates.
  3855. */
  3856. Vector4.prototype.toString = function () {
  3857. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3858. };
  3859. /**
  3860. * Returns the string "Vector4".
  3861. */
  3862. Vector4.prototype.getClassName = function () {
  3863. return "Vector4";
  3864. };
  3865. /**
  3866. * Returns the Vector4 hash code.
  3867. */
  3868. Vector4.prototype.getHashCode = function () {
  3869. var hash = this.x || 0;
  3870. hash = (hash * 397) ^ (this.y || 0);
  3871. hash = (hash * 397) ^ (this.z || 0);
  3872. hash = (hash * 397) ^ (this.w || 0);
  3873. return hash;
  3874. };
  3875. // Operators
  3876. /**
  3877. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3878. */
  3879. Vector4.prototype.asArray = function () {
  3880. var result = new Array();
  3881. this.toArray(result, 0);
  3882. return result;
  3883. };
  3884. /**
  3885. * Populates the given array from the given index with the Vector4 coordinates.
  3886. * Returns the Vector4.
  3887. */
  3888. Vector4.prototype.toArray = function (array, index) {
  3889. if (index === undefined) {
  3890. index = 0;
  3891. }
  3892. array[index] = this.x;
  3893. array[index + 1] = this.y;
  3894. array[index + 2] = this.z;
  3895. array[index + 3] = this.w;
  3896. return this;
  3897. };
  3898. /**
  3899. * Adds the given vector to the current Vector4.
  3900. * Returns the updated Vector4.
  3901. */
  3902. Vector4.prototype.addInPlace = function (otherVector) {
  3903. this.x += otherVector.x;
  3904. this.y += otherVector.y;
  3905. this.z += otherVector.z;
  3906. this.w += otherVector.w;
  3907. return this;
  3908. };
  3909. /**
  3910. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3911. */
  3912. Vector4.prototype.add = function (otherVector) {
  3913. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3914. };
  3915. /**
  3916. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3917. * Returns the current Vector4.
  3918. */
  3919. Vector4.prototype.addToRef = function (otherVector, result) {
  3920. result.x = this.x + otherVector.x;
  3921. result.y = this.y + otherVector.y;
  3922. result.z = this.z + otherVector.z;
  3923. result.w = this.w + otherVector.w;
  3924. return this;
  3925. };
  3926. /**
  3927. * Subtract in place the given vector from the current Vector4.
  3928. * Returns the updated Vector4.
  3929. */
  3930. Vector4.prototype.subtractInPlace = function (otherVector) {
  3931. this.x -= otherVector.x;
  3932. this.y -= otherVector.y;
  3933. this.z -= otherVector.z;
  3934. this.w -= otherVector.w;
  3935. return this;
  3936. };
  3937. /**
  3938. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3939. */
  3940. Vector4.prototype.subtract = function (otherVector) {
  3941. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3942. };
  3943. /**
  3944. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3945. * Returns the current Vector4.
  3946. */
  3947. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3948. result.x = this.x - otherVector.x;
  3949. result.y = this.y - otherVector.y;
  3950. result.z = this.z - otherVector.z;
  3951. result.w = this.w - otherVector.w;
  3952. return this;
  3953. };
  3954. /**
  3955. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3956. */
  3957. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3958. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3959. };
  3960. /**
  3961. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3962. * Returns the current Vector4.
  3963. */
  3964. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3965. result.x = this.x - x;
  3966. result.y = this.y - y;
  3967. result.z = this.z - z;
  3968. result.w = this.w - w;
  3969. return this;
  3970. };
  3971. /**
  3972. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3973. */
  3974. Vector4.prototype.negate = function () {
  3975. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3976. };
  3977. /**
  3978. * Multiplies the current Vector4 coordinates by scale (float).
  3979. * Returns the updated Vector4.
  3980. */
  3981. Vector4.prototype.scaleInPlace = function (scale) {
  3982. this.x *= scale;
  3983. this.y *= scale;
  3984. this.z *= scale;
  3985. this.w *= scale;
  3986. return this;
  3987. };
  3988. /**
  3989. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3990. */
  3991. Vector4.prototype.scale = function (scale) {
  3992. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3993. };
  3994. /**
  3995. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3996. * Returns the current Vector4.
  3997. */
  3998. Vector4.prototype.scaleToRef = function (scale, result) {
  3999. result.x = this.x * scale;
  4000. result.y = this.y * scale;
  4001. result.z = this.z * scale;
  4002. result.w = this.w * scale;
  4003. return this;
  4004. };
  4005. /**
  4006. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4007. * @param scale defines the scale factor
  4008. * @param result defines the Vector4 object where to store the result
  4009. * @returns the unmodified current Vector4
  4010. */
  4011. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4012. result.x += this.x * scale;
  4013. result.y += this.y * scale;
  4014. result.z += this.z * scale;
  4015. result.w += this.w * scale;
  4016. return this;
  4017. };
  4018. /**
  4019. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4020. */
  4021. Vector4.prototype.equals = function (otherVector) {
  4022. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4023. };
  4024. /**
  4025. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4026. */
  4027. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4028. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4029. return otherVector
  4030. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4031. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4032. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4033. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4034. };
  4035. /**
  4036. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4037. */
  4038. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4039. return this.x === x && this.y === y && this.z === z && this.w === w;
  4040. };
  4041. /**
  4042. * Multiplies in place the current Vector4 by the given one.
  4043. * Returns the updated Vector4.
  4044. */
  4045. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4046. this.x *= otherVector.x;
  4047. this.y *= otherVector.y;
  4048. this.z *= otherVector.z;
  4049. this.w *= otherVector.w;
  4050. return this;
  4051. };
  4052. /**
  4053. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4054. */
  4055. Vector4.prototype.multiply = function (otherVector) {
  4056. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4057. };
  4058. /**
  4059. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4060. * Returns the current Vector4.
  4061. */
  4062. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4063. result.x = this.x * otherVector.x;
  4064. result.y = this.y * otherVector.y;
  4065. result.z = this.z * otherVector.z;
  4066. result.w = this.w * otherVector.w;
  4067. return this;
  4068. };
  4069. /**
  4070. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4071. */
  4072. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4073. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4074. };
  4075. /**
  4076. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4077. */
  4078. Vector4.prototype.divide = function (otherVector) {
  4079. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4080. };
  4081. /**
  4082. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4083. * Returns the current Vector4.
  4084. */
  4085. Vector4.prototype.divideToRef = function (otherVector, result) {
  4086. result.x = this.x / otherVector.x;
  4087. result.y = this.y / otherVector.y;
  4088. result.z = this.z / otherVector.z;
  4089. result.w = this.w / otherVector.w;
  4090. return this;
  4091. };
  4092. /**
  4093. * Divides the current Vector3 coordinates by the given ones.
  4094. * @returns the updated Vector3.
  4095. */
  4096. Vector4.prototype.divideInPlace = function (otherVector) {
  4097. return this.divideToRef(otherVector, this);
  4098. };
  4099. /**
  4100. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4101. * @param other defines the second operand
  4102. * @returns the current updated Vector4
  4103. */
  4104. Vector4.prototype.minimizeInPlace = function (other) {
  4105. if (other.x < this.x)
  4106. this.x = other.x;
  4107. if (other.y < this.y)
  4108. this.y = other.y;
  4109. if (other.z < this.z)
  4110. this.z = other.z;
  4111. if (other.w < this.w)
  4112. this.w = other.w;
  4113. return this;
  4114. };
  4115. /**
  4116. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4117. * @param other defines the second operand
  4118. * @returns the current updated Vector4
  4119. */
  4120. Vector4.prototype.maximizeInPlace = function (other) {
  4121. if (other.x > this.x)
  4122. this.x = other.x;
  4123. if (other.y > this.y)
  4124. this.y = other.y;
  4125. if (other.z > this.z)
  4126. this.z = other.z;
  4127. if (other.w > this.w)
  4128. this.w = other.w;
  4129. return this;
  4130. };
  4131. // Properties
  4132. /**
  4133. * Returns the Vector4 length (float).
  4134. */
  4135. Vector4.prototype.length = function () {
  4136. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4137. };
  4138. /**
  4139. * Returns the Vector4 squared length (float).
  4140. */
  4141. Vector4.prototype.lengthSquared = function () {
  4142. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4143. };
  4144. // Methods
  4145. /**
  4146. * Normalizes in place the Vector4.
  4147. * Returns the updated Vector4.
  4148. */
  4149. Vector4.prototype.normalize = function () {
  4150. var len = this.length();
  4151. if (len === 0)
  4152. return this;
  4153. var num = 1.0 / len;
  4154. this.x *= num;
  4155. this.y *= num;
  4156. this.z *= num;
  4157. this.w *= num;
  4158. return this;
  4159. };
  4160. /**
  4161. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4162. */
  4163. Vector4.prototype.toVector3 = function () {
  4164. return new Vector3(this.x, this.y, this.z);
  4165. };
  4166. /**
  4167. * Returns a new Vector4 copied from the current one.
  4168. */
  4169. Vector4.prototype.clone = function () {
  4170. return new Vector4(this.x, this.y, this.z, this.w);
  4171. };
  4172. /**
  4173. * Updates the current Vector4 with the given one coordinates.
  4174. * Returns the updated Vector4.
  4175. */
  4176. Vector4.prototype.copyFrom = function (source) {
  4177. this.x = source.x;
  4178. this.y = source.y;
  4179. this.z = source.z;
  4180. this.w = source.w;
  4181. return this;
  4182. };
  4183. /**
  4184. * Updates the current Vector4 coordinates with the given floats.
  4185. * Returns the updated Vector4.
  4186. */
  4187. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4188. this.x = x;
  4189. this.y = y;
  4190. this.z = z;
  4191. this.w = w;
  4192. return this;
  4193. };
  4194. /**
  4195. * Updates the current Vector4 coordinates with the given floats.
  4196. * Returns the updated Vector4.
  4197. */
  4198. Vector4.prototype.set = function (x, y, z, w) {
  4199. return this.copyFromFloats(x, y, z, w);
  4200. };
  4201. // Statics
  4202. /**
  4203. * Returns a new Vector4 set from the starting index of the given array.
  4204. */
  4205. Vector4.FromArray = function (array, offset) {
  4206. if (!offset) {
  4207. offset = 0;
  4208. }
  4209. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4210. };
  4211. /**
  4212. * Updates the given vector "result" from the starting index of the given array.
  4213. */
  4214. Vector4.FromArrayToRef = function (array, offset, result) {
  4215. result.x = array[offset];
  4216. result.y = array[offset + 1];
  4217. result.z = array[offset + 2];
  4218. result.w = array[offset + 3];
  4219. };
  4220. /**
  4221. * Updates the given vector "result" from the starting index of the given Float32Array.
  4222. */
  4223. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4224. Vector4.FromArrayToRef(array, offset, result);
  4225. };
  4226. /**
  4227. * Updates the given vector "result" coordinates from the given floats.
  4228. */
  4229. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4230. result.x = x;
  4231. result.y = y;
  4232. result.z = z;
  4233. result.w = w;
  4234. };
  4235. /**
  4236. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4237. */
  4238. Vector4.Zero = function () {
  4239. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4240. };
  4241. /**
  4242. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4243. */
  4244. Vector4.One = function () {
  4245. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4246. };
  4247. /**
  4248. * Returns a new normalized Vector4 from the given one.
  4249. */
  4250. Vector4.Normalize = function (vector) {
  4251. var result = Vector4.Zero();
  4252. Vector4.NormalizeToRef(vector, result);
  4253. return result;
  4254. };
  4255. /**
  4256. * Updates the given vector "result" from the normalization of the given one.
  4257. */
  4258. Vector4.NormalizeToRef = function (vector, result) {
  4259. result.copyFrom(vector);
  4260. result.normalize();
  4261. };
  4262. Vector4.Minimize = function (left, right) {
  4263. var min = left.clone();
  4264. min.minimizeInPlace(right);
  4265. return min;
  4266. };
  4267. Vector4.Maximize = function (left, right) {
  4268. var max = left.clone();
  4269. max.maximizeInPlace(right);
  4270. return max;
  4271. };
  4272. /**
  4273. * Returns the distance (float) between the vectors "value1" and "value2".
  4274. */
  4275. Vector4.Distance = function (value1, value2) {
  4276. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4277. };
  4278. /**
  4279. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4280. */
  4281. Vector4.DistanceSquared = function (value1, value2) {
  4282. var x = value1.x - value2.x;
  4283. var y = value1.y - value2.y;
  4284. var z = value1.z - value2.z;
  4285. var w = value1.w - value2.w;
  4286. return (x * x) + (y * y) + (z * z) + (w * w);
  4287. };
  4288. /**
  4289. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4290. */
  4291. Vector4.Center = function (value1, value2) {
  4292. var center = value1.add(value2);
  4293. center.scaleInPlace(0.5);
  4294. return center;
  4295. };
  4296. /**
  4297. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4298. * This methods computes transformed normalized direction vectors only.
  4299. */
  4300. Vector4.TransformNormal = function (vector, transformation) {
  4301. var result = Vector4.Zero();
  4302. Vector4.TransformNormalToRef(vector, transformation, result);
  4303. return result;
  4304. };
  4305. /**
  4306. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4307. * This methods computes transformed normalized direction vectors only.
  4308. */
  4309. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4310. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4311. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4312. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4313. result.x = x;
  4314. result.y = y;
  4315. result.z = z;
  4316. result.w = vector.w;
  4317. };
  4318. /**
  4319. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4320. * This methods computes transformed normalized direction vectors only.
  4321. */
  4322. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4323. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4324. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4325. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4326. result.w = w;
  4327. };
  4328. return Vector4;
  4329. }());
  4330. BABYLON.Vector4 = Vector4;
  4331. var Size = /** @class */ (function () {
  4332. /**
  4333. * Creates a Size object from the given width and height (floats).
  4334. */
  4335. function Size(width, height) {
  4336. this.width = width;
  4337. this.height = height;
  4338. }
  4339. // Returns a string with the Size width and height.
  4340. Size.prototype.toString = function () {
  4341. return "{W: " + this.width + ", H: " + this.height + "}";
  4342. };
  4343. /**
  4344. * Returns the string "Size"
  4345. */
  4346. Size.prototype.getClassName = function () {
  4347. return "Size";
  4348. };
  4349. /**
  4350. * Returns the Size hash code.
  4351. */
  4352. Size.prototype.getHashCode = function () {
  4353. var hash = this.width || 0;
  4354. hash = (hash * 397) ^ (this.height || 0);
  4355. return hash;
  4356. };
  4357. /**
  4358. * Updates the current size from the given one.
  4359. * Returns the updated Size.
  4360. */
  4361. Size.prototype.copyFrom = function (src) {
  4362. this.width = src.width;
  4363. this.height = src.height;
  4364. };
  4365. /**
  4366. * Updates in place the current Size from the given floats.
  4367. * Returns the updated Size.
  4368. */
  4369. Size.prototype.copyFromFloats = function (width, height) {
  4370. this.width = width;
  4371. this.height = height;
  4372. return this;
  4373. };
  4374. /**
  4375. * Updates in place the current Size from the given floats.
  4376. * Returns the updated Size.
  4377. */
  4378. Size.prototype.set = function (width, height) {
  4379. return this.copyFromFloats(width, height);
  4380. };
  4381. /**
  4382. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4383. */
  4384. Size.prototype.multiplyByFloats = function (w, h) {
  4385. return new Size(this.width * w, this.height * h);
  4386. };
  4387. /**
  4388. * Returns a new Size copied from the given one.
  4389. */
  4390. Size.prototype.clone = function () {
  4391. return new Size(this.width, this.height);
  4392. };
  4393. /**
  4394. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4395. */
  4396. Size.prototype.equals = function (other) {
  4397. if (!other) {
  4398. return false;
  4399. }
  4400. return (this.width === other.width) && (this.height === other.height);
  4401. };
  4402. Object.defineProperty(Size.prototype, "surface", {
  4403. /**
  4404. * Returns the surface of the Size : width * height (float).
  4405. */
  4406. get: function () {
  4407. return this.width * this.height;
  4408. },
  4409. enumerable: true,
  4410. configurable: true
  4411. });
  4412. /**
  4413. * Returns a new Size set to (0.0, 0.0)
  4414. */
  4415. Size.Zero = function () {
  4416. return new Size(0.0, 0.0);
  4417. };
  4418. /**
  4419. * Returns a new Size set as the addition result of the current Size and the given one.
  4420. */
  4421. Size.prototype.add = function (otherSize) {
  4422. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4423. return r;
  4424. };
  4425. /**
  4426. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4427. */
  4428. Size.prototype.subtract = function (otherSize) {
  4429. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4430. return r;
  4431. };
  4432. /**
  4433. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4434. */
  4435. Size.Lerp = function (start, end, amount) {
  4436. var w = start.width + ((end.width - start.width) * amount);
  4437. var h = start.height + ((end.height - start.height) * amount);
  4438. return new Size(w, h);
  4439. };
  4440. return Size;
  4441. }());
  4442. BABYLON.Size = Size;
  4443. /**
  4444. * Class used to store quaternion data
  4445. * @see https://en.wikipedia.org/wiki/Quaternion
  4446. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4447. */
  4448. var Quaternion = /** @class */ (function () {
  4449. /**
  4450. * Creates a new Quaternion from the given floats
  4451. * @param x defines the first component (0 by default)
  4452. * @param y defines the second component (0 by default)
  4453. * @param z defines the third component (0 by default)
  4454. * @param w defines the fourth component (1.0 by default)
  4455. */
  4456. function Quaternion(
  4457. /** defines the first component (0 by default) */
  4458. x,
  4459. /** defines the second component (0 by default) */
  4460. y,
  4461. /** defines the third component (0 by default) */
  4462. z,
  4463. /** defines the fourth component (1.0 by default) */
  4464. w) {
  4465. if (x === void 0) { x = 0.0; }
  4466. if (y === void 0) { y = 0.0; }
  4467. if (z === void 0) { z = 0.0; }
  4468. if (w === void 0) { w = 1.0; }
  4469. this.x = x;
  4470. this.y = y;
  4471. this.z = z;
  4472. this.w = w;
  4473. }
  4474. /**
  4475. * Gets a string representation for the current quaternion
  4476. * @returns a string with the Quaternion coordinates
  4477. */
  4478. Quaternion.prototype.toString = function () {
  4479. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4480. };
  4481. /**
  4482. * Gets the class name of the quaternion
  4483. * @returns the string "Quaternion"
  4484. */
  4485. Quaternion.prototype.getClassName = function () {
  4486. return "Quaternion";
  4487. };
  4488. /**
  4489. * Gets a hash code for this quaternion
  4490. * @returns the quaternion hash code
  4491. */
  4492. Quaternion.prototype.getHashCode = function () {
  4493. var hash = this.x || 0;
  4494. hash = (hash * 397) ^ (this.y || 0);
  4495. hash = (hash * 397) ^ (this.z || 0);
  4496. hash = (hash * 397) ^ (this.w || 0);
  4497. return hash;
  4498. };
  4499. /**
  4500. * Copy the quaternion to an array
  4501. * @returns a new array populated with 4 elements from the quaternion coordinates
  4502. */
  4503. Quaternion.prototype.asArray = function () {
  4504. return [this.x, this.y, this.z, this.w];
  4505. };
  4506. /**
  4507. * Check if two quaternions are equals
  4508. * @param otherQuaternion defines the second operand
  4509. * @return true if the current quaternion and the given one coordinates are strictly equals
  4510. */
  4511. Quaternion.prototype.equals = function (otherQuaternion) {
  4512. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4513. };
  4514. /**
  4515. * Clone the current quaternion
  4516. * @returns a new quaternion copied from the current one
  4517. */
  4518. Quaternion.prototype.clone = function () {
  4519. return new Quaternion(this.x, this.y, this.z, this.w);
  4520. };
  4521. /**
  4522. * Copy a quaternion to the current one
  4523. * @param other defines the other quaternion
  4524. * @returns the updated current quaternion
  4525. */
  4526. Quaternion.prototype.copyFrom = function (other) {
  4527. this.x = other.x;
  4528. this.y = other.y;
  4529. this.z = other.z;
  4530. this.w = other.w;
  4531. return this;
  4532. };
  4533. /**
  4534. * Updates the current quaternion with the given float coordinates
  4535. * @param x defines the x coordinate
  4536. * @param y defines the y coordinate
  4537. * @param z defines the z coordinate
  4538. * @param w defines the w coordinate
  4539. * @returns the updated current quaternion
  4540. */
  4541. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4542. this.x = x;
  4543. this.y = y;
  4544. this.z = z;
  4545. this.w = w;
  4546. return this;
  4547. };
  4548. /**
  4549. * Updates the current quaternion from the given float coordinates
  4550. * @param x defines the x coordinate
  4551. * @param y defines the y coordinate
  4552. * @param z defines the z coordinate
  4553. * @param w defines the w coordinate
  4554. * @returns the updated current quaternion
  4555. */
  4556. Quaternion.prototype.set = function (x, y, z, w) {
  4557. return this.copyFromFloats(x, y, z, w);
  4558. };
  4559. /**
  4560. * Adds two quaternions
  4561. * @param other defines the second operand
  4562. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4563. */
  4564. Quaternion.prototype.add = function (other) {
  4565. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4566. };
  4567. /**
  4568. * Add a quaternion to the current one
  4569. * @param other defines the quaternion to add
  4570. * @returns the current quaternion
  4571. */
  4572. Quaternion.prototype.addInPlace = function (other) {
  4573. this.x += other.x;
  4574. this.y += other.y;
  4575. this.z += other.z;
  4576. this.w += other.w;
  4577. return this;
  4578. };
  4579. /**
  4580. * Subtract two quaternions
  4581. * @param other defines the second operand
  4582. * @returns a new quaternion as the subtraction result of the given one from the current one
  4583. */
  4584. Quaternion.prototype.subtract = function (other) {
  4585. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4586. };
  4587. /**
  4588. * Multiplies the current quaternion by a scale factor
  4589. * @param value defines the scale factor
  4590. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4591. */
  4592. Quaternion.prototype.scale = function (value) {
  4593. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4594. };
  4595. /**
  4596. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4597. * @param scale defines the scale factor
  4598. * @param result defines the Quaternion object where to store the result
  4599. * @returns the unmodified current quaternion
  4600. */
  4601. Quaternion.prototype.scaleToRef = function (scale, result) {
  4602. result.x = this.x * scale;
  4603. result.y = this.y * scale;
  4604. result.z = this.z * scale;
  4605. result.w = this.w * scale;
  4606. return this;
  4607. };
  4608. /**
  4609. * Multiplies in place the current quaternion by a scale factor
  4610. * @param value defines the scale factor
  4611. * @returns the current modified quaternion
  4612. */
  4613. Quaternion.prototype.scaleInPlace = function (value) {
  4614. this.x *= value;
  4615. this.y *= value;
  4616. this.z *= value;
  4617. this.w *= value;
  4618. return this;
  4619. };
  4620. /**
  4621. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4622. * @param scale defines the scale factor
  4623. * @param result defines the Quaternion object where to store the result
  4624. * @returns the unmodified current quaternion
  4625. */
  4626. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4627. result.x += this.x * scale;
  4628. result.y += this.y * scale;
  4629. result.z += this.z * scale;
  4630. result.w += this.w * scale;
  4631. return this;
  4632. };
  4633. /**
  4634. * Multiplies two quaternions
  4635. * @param q1 defines the second operand
  4636. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4637. */
  4638. Quaternion.prototype.multiply = function (q1) {
  4639. var result = new Quaternion(0, 0, 0, 1.0);
  4640. this.multiplyToRef(q1, result);
  4641. return result;
  4642. };
  4643. /**
  4644. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4645. * @param q1 defines the second operand
  4646. * @param result defines the target quaternion
  4647. * @returns the current quaternion
  4648. */
  4649. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4650. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4651. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4652. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4653. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4654. result.copyFromFloats(x, y, z, w);
  4655. return this;
  4656. };
  4657. /**
  4658. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4659. * @param q1 defines the second operand
  4660. * @returns the currentupdated quaternion
  4661. */
  4662. Quaternion.prototype.multiplyInPlace = function (q1) {
  4663. this.multiplyToRef(q1, this);
  4664. return this;
  4665. };
  4666. /**
  4667. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4668. * @param ref defines the target quaternion
  4669. * @returns the current quaternion
  4670. */
  4671. Quaternion.prototype.conjugateToRef = function (ref) {
  4672. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4673. return this;
  4674. };
  4675. /**
  4676. * Conjugates in place (1-q) the current quaternion
  4677. * @returns the current updated quaternion
  4678. */
  4679. Quaternion.prototype.conjugateInPlace = function () {
  4680. this.x *= -1;
  4681. this.y *= -1;
  4682. this.z *= -1;
  4683. return this;
  4684. };
  4685. /**
  4686. * Conjugates in place (1-q) the current quaternion
  4687. * @returns a new quaternion
  4688. */
  4689. Quaternion.prototype.conjugate = function () {
  4690. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4691. return result;
  4692. };
  4693. /**
  4694. * Gets length of current quaternion
  4695. * @returns the quaternion length (float)
  4696. */
  4697. Quaternion.prototype.length = function () {
  4698. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4699. };
  4700. /**
  4701. * Normalize in place the current quaternion
  4702. * @returns the current updated quaternion
  4703. */
  4704. Quaternion.prototype.normalize = function () {
  4705. var length = 1.0 / this.length();
  4706. this.x *= length;
  4707. this.y *= length;
  4708. this.z *= length;
  4709. this.w *= length;
  4710. return this;
  4711. };
  4712. /**
  4713. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4714. * @param order is a reserved parameter and is ignore for now
  4715. * @returns a new Vector3 containing the Euler angles
  4716. */
  4717. Quaternion.prototype.toEulerAngles = function (order) {
  4718. if (order === void 0) { order = "YZX"; }
  4719. var result = Vector3.Zero();
  4720. this.toEulerAnglesToRef(result, order);
  4721. return result;
  4722. };
  4723. /**
  4724. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4725. * @param result defines the vector which will be filled with the Euler angles
  4726. * @param order is a reserved parameter and is ignore for now
  4727. * @returns the current unchanged quaternion
  4728. */
  4729. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4730. if (order === void 0) { order = "YZX"; }
  4731. var qz = this.z;
  4732. var qx = this.x;
  4733. var qy = this.y;
  4734. var qw = this.w;
  4735. var sqw = qw * qw;
  4736. var sqz = qz * qz;
  4737. var sqx = qx * qx;
  4738. var sqy = qy * qy;
  4739. var zAxisY = qy * qz - qx * qw;
  4740. var limit = .4999999;
  4741. if (zAxisY < -limit) {
  4742. result.y = 2 * Math.atan2(qy, qw);
  4743. result.x = Math.PI / 2;
  4744. result.z = 0;
  4745. }
  4746. else if (zAxisY > limit) {
  4747. result.y = 2 * Math.atan2(qy, qw);
  4748. result.x = -Math.PI / 2;
  4749. result.z = 0;
  4750. }
  4751. else {
  4752. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4753. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4754. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4755. }
  4756. return this;
  4757. };
  4758. /**
  4759. * Updates the given rotation matrix with the current quaternion values
  4760. * @param result defines the target matrix
  4761. * @returns the current unchanged quaternion
  4762. */
  4763. Quaternion.prototype.toRotationMatrix = function (result) {
  4764. var xx = this.x * this.x;
  4765. var yy = this.y * this.y;
  4766. var zz = this.z * this.z;
  4767. var xy = this.x * this.y;
  4768. var zw = this.z * this.w;
  4769. var zx = this.z * this.x;
  4770. var yw = this.y * this.w;
  4771. var yz = this.y * this.z;
  4772. var xw = this.x * this.w;
  4773. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4774. result.m[1] = 2.0 * (xy + zw);
  4775. result.m[2] = 2.0 * (zx - yw);
  4776. result.m[3] = 0;
  4777. result.m[4] = 2.0 * (xy - zw);
  4778. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4779. result.m[6] = 2.0 * (yz + xw);
  4780. result.m[7] = 0;
  4781. result.m[8] = 2.0 * (zx + yw);
  4782. result.m[9] = 2.0 * (yz - xw);
  4783. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4784. result.m[11] = 0;
  4785. result.m[12] = 0;
  4786. result.m[13] = 0;
  4787. result.m[14] = 0;
  4788. result.m[15] = 1.0;
  4789. result._markAsUpdated();
  4790. return this;
  4791. };
  4792. /**
  4793. * Updates the current quaternion from the given rotation matrix values
  4794. * @param matrix defines the source matrix
  4795. * @returns the current updated quaternion
  4796. */
  4797. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4798. Quaternion.FromRotationMatrixToRef(matrix, this);
  4799. return this;
  4800. };
  4801. // Statics
  4802. /**
  4803. * Creates a new quaternion from a rotation matrix
  4804. * @param matrix defines the source matrix
  4805. * @returns a new quaternion created from the given rotation matrix values
  4806. */
  4807. Quaternion.FromRotationMatrix = function (matrix) {
  4808. var result = new Quaternion();
  4809. Quaternion.FromRotationMatrixToRef(matrix, result);
  4810. return result;
  4811. };
  4812. /**
  4813. * Updates the given quaternion with the given rotation matrix values
  4814. * @param matrix defines the source matrix
  4815. * @param result defines the target quaternion
  4816. */
  4817. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4818. var data = matrix.m;
  4819. var m11 = data[0], m12 = data[4], m13 = data[8];
  4820. var m21 = data[1], m22 = data[5], m23 = data[9];
  4821. var m31 = data[2], m32 = data[6], m33 = data[10];
  4822. var trace = m11 + m22 + m33;
  4823. var s;
  4824. if (trace > 0) {
  4825. s = 0.5 / Math.sqrt(trace + 1.0);
  4826. result.w = 0.25 / s;
  4827. result.x = (m32 - m23) * s;
  4828. result.y = (m13 - m31) * s;
  4829. result.z = (m21 - m12) * s;
  4830. }
  4831. else if (m11 > m22 && m11 > m33) {
  4832. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4833. result.w = (m32 - m23) / s;
  4834. result.x = 0.25 * s;
  4835. result.y = (m12 + m21) / s;
  4836. result.z = (m13 + m31) / s;
  4837. }
  4838. else if (m22 > m33) {
  4839. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4840. result.w = (m13 - m31) / s;
  4841. result.x = (m12 + m21) / s;
  4842. result.y = 0.25 * s;
  4843. result.z = (m23 + m32) / s;
  4844. }
  4845. else {
  4846. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4847. result.w = (m21 - m12) / s;
  4848. result.x = (m13 + m31) / s;
  4849. result.y = (m23 + m32) / s;
  4850. result.z = 0.25 * s;
  4851. }
  4852. };
  4853. /**
  4854. * Returns the dot product (float) between the quaternions "left" and "right"
  4855. * @param left defines the left operand
  4856. * @param right defines the right operand
  4857. * @returns the dot product
  4858. */
  4859. Quaternion.Dot = function (left, right) {
  4860. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4861. };
  4862. /**
  4863. * Checks if the two quaternions are close to each other
  4864. * @param quat0 defines the first quaternion to check
  4865. * @param quat1 defines the second quaternion to check
  4866. * @returns true if the two quaternions are close to each other
  4867. */
  4868. Quaternion.AreClose = function (quat0, quat1) {
  4869. var dot = Quaternion.Dot(quat0, quat1);
  4870. return dot >= 0;
  4871. };
  4872. /**
  4873. * Creates an empty quaternion
  4874. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4875. */
  4876. Quaternion.Zero = function () {
  4877. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4878. };
  4879. /**
  4880. * Inverse a given quaternion
  4881. * @param q defines the source quaternion
  4882. * @returns a new quaternion as the inverted current quaternion
  4883. */
  4884. Quaternion.Inverse = function (q) {
  4885. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4886. };
  4887. /**
  4888. * Creates an identity quaternion
  4889. * @returns the identity quaternion
  4890. */
  4891. Quaternion.Identity = function () {
  4892. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4893. };
  4894. /**
  4895. * Gets a boolean indicating if the given quaternion is identity
  4896. * @param quaternion defines the quaternion to check
  4897. * @returns true if the quaternion is identity
  4898. */
  4899. Quaternion.IsIdentity = function (quaternion) {
  4900. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4901. };
  4902. /**
  4903. * Creates a quaternion from a rotation around an axis
  4904. * @param axis defines the axis to use
  4905. * @param angle defines the angle to use
  4906. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4907. */
  4908. Quaternion.RotationAxis = function (axis, angle) {
  4909. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4910. };
  4911. /**
  4912. * Creates a rotation around an axis and stores it into the given quaternion
  4913. * @param axis defines the axis to use
  4914. * @param angle defines the angle to use
  4915. * @param result defines the target quaternion
  4916. * @returns the target quaternion
  4917. */
  4918. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4919. var sin = Math.sin(angle / 2);
  4920. axis.normalize();
  4921. result.w = Math.cos(angle / 2);
  4922. result.x = axis.x * sin;
  4923. result.y = axis.y * sin;
  4924. result.z = axis.z * sin;
  4925. return result;
  4926. };
  4927. /**
  4928. * Creates a new quaternion from data stored into an array
  4929. * @param array defines the data source
  4930. * @param offset defines the offset in the source array where the data starts
  4931. * @returns a new quaternion
  4932. */
  4933. Quaternion.FromArray = function (array, offset) {
  4934. if (!offset) {
  4935. offset = 0;
  4936. }
  4937. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4938. };
  4939. /**
  4940. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4941. * @param yaw defines the rotation around Y axis
  4942. * @param pitch defines the rotation around X axis
  4943. * @param roll defines the rotation around Z axis
  4944. * @returns the new quaternion
  4945. */
  4946. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4947. var q = new Quaternion();
  4948. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4949. return q;
  4950. };
  4951. /**
  4952. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4953. * @param yaw defines the rotation around Y axis
  4954. * @param pitch defines the rotation around X axis
  4955. * @param roll defines the rotation around Z axis
  4956. * @param result defines the target quaternion
  4957. */
  4958. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4959. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4960. var halfRoll = roll * 0.5;
  4961. var halfPitch = pitch * 0.5;
  4962. var halfYaw = yaw * 0.5;
  4963. var sinRoll = Math.sin(halfRoll);
  4964. var cosRoll = Math.cos(halfRoll);
  4965. var sinPitch = Math.sin(halfPitch);
  4966. var cosPitch = Math.cos(halfPitch);
  4967. var sinYaw = Math.sin(halfYaw);
  4968. var cosYaw = Math.cos(halfYaw);
  4969. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4970. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4971. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4972. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4973. };
  4974. /**
  4975. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4976. * @param alpha defines the rotation around first axis
  4977. * @param beta defines the rotation around second axis
  4978. * @param gamma defines the rotation around third axis
  4979. * @returns the new quaternion
  4980. */
  4981. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4982. var result = new Quaternion();
  4983. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4984. return result;
  4985. };
  4986. /**
  4987. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4988. * @param alpha defines the rotation around first axis
  4989. * @param beta defines the rotation around second axis
  4990. * @param gamma defines the rotation around third axis
  4991. * @param result defines the target quaternion
  4992. */
  4993. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4994. // Produces a quaternion from Euler angles in the z-x-z orientation
  4995. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4996. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4997. var halfBeta = beta * 0.5;
  4998. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4999. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5000. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5001. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5002. };
  5003. /**
  5004. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  5005. * @param axis1 defines the first axis
  5006. * @param axis2 defines the second axis
  5007. * @param axis3 defines the third axis
  5008. * @returns the new quaternion
  5009. */
  5010. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5011. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5012. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5013. return quat;
  5014. };
  5015. /**
  5016. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  5017. * @param axis1 defines the first axis
  5018. * @param axis2 defines the second axis
  5019. * @param axis3 defines the third axis
  5020. * @param ref defines the target quaternion
  5021. */
  5022. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5023. var rotMat = MathTmp.Matrix[0];
  5024. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5025. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5026. };
  5027. /**
  5028. * Interpolates between two quaternions
  5029. * @param left defines first quaternion
  5030. * @param right defines second quaternion
  5031. * @param amount defines the gradient to use
  5032. * @returns the new interpolated quaternion
  5033. */
  5034. Quaternion.Slerp = function (left, right, amount) {
  5035. var result = Quaternion.Identity();
  5036. Quaternion.SlerpToRef(left, right, amount, result);
  5037. return result;
  5038. };
  5039. /**
  5040. * Interpolates between two quaternions and stores it into a target quaternion
  5041. * @param left defines first quaternion
  5042. * @param right defines second quaternion
  5043. * @param amount defines the gradient to use
  5044. * @param result defines the target quaternion
  5045. */
  5046. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5047. var num2;
  5048. var num3;
  5049. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5050. var flag = false;
  5051. if (num4 < 0) {
  5052. flag = true;
  5053. num4 = -num4;
  5054. }
  5055. if (num4 > 0.999999) {
  5056. num3 = 1 - amount;
  5057. num2 = flag ? -amount : amount;
  5058. }
  5059. else {
  5060. var num5 = Math.acos(num4);
  5061. var num6 = (1.0 / Math.sin(num5));
  5062. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5063. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5064. }
  5065. result.x = (num3 * left.x) + (num2 * right.x);
  5066. result.y = (num3 * left.y) + (num2 * right.y);
  5067. result.z = (num3 * left.z) + (num2 * right.z);
  5068. result.w = (num3 * left.w) + (num2 * right.w);
  5069. };
  5070. /**
  5071. * Interpolate between two quaternions using Hermite interpolation
  5072. * @param value1 defines first quaternion
  5073. * @param tangent1 defines the incoming tangent
  5074. * @param value2 defines second quaternion
  5075. * @param tangent2 defines the outgoing tangent
  5076. * @param amount defines the target quaternion
  5077. * @returns the new interpolated quaternion
  5078. */
  5079. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5080. var squared = amount * amount;
  5081. var cubed = amount * squared;
  5082. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5083. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5084. var part3 = (cubed - (2.0 * squared)) + amount;
  5085. var part4 = cubed - squared;
  5086. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5087. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5088. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5089. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5090. return new Quaternion(x, y, z, w);
  5091. };
  5092. return Quaternion;
  5093. }());
  5094. BABYLON.Quaternion = Quaternion;
  5095. /**
  5096. * Class used to store matrix data (4x4)
  5097. */
  5098. var Matrix = /** @class */ (function () {
  5099. /**
  5100. * Creates an empty matrix (filled with zeros)
  5101. */
  5102. function Matrix() {
  5103. this._isIdentity = false;
  5104. this._isIdentityDirty = true;
  5105. /**
  5106. * Gets or sets the internal data of the matrix
  5107. */
  5108. this.m = new Float32Array(16);
  5109. this._markAsUpdated();
  5110. }
  5111. /** @hidden */
  5112. Matrix.prototype._markAsUpdated = function () {
  5113. this.updateFlag = Matrix._updateFlagSeed++;
  5114. this._isIdentityDirty = true;
  5115. };
  5116. // Properties
  5117. /**
  5118. * Check if the current matrix is indentity
  5119. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5120. * @returns true is the matrix is the identity matrix
  5121. */
  5122. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5123. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5124. if (this._isIdentityDirty) {
  5125. this._isIdentityDirty = false;
  5126. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5127. this._isIdentity = false;
  5128. }
  5129. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5130. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5131. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5132. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5133. this._isIdentity = false;
  5134. }
  5135. else {
  5136. this._isIdentity = true;
  5137. }
  5138. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5139. this._isIdentity = false;
  5140. }
  5141. }
  5142. return this._isIdentity;
  5143. };
  5144. /**
  5145. * Gets the determinant of the matrix
  5146. * @returns the matrix determinant
  5147. */
  5148. Matrix.prototype.determinant = function () {
  5149. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5150. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5151. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5152. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5153. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5154. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5155. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5156. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5157. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5158. };
  5159. // Methods
  5160. /**
  5161. * Returns the matrix as a Float32Array
  5162. * @returns the matrix underlying array
  5163. */
  5164. Matrix.prototype.toArray = function () {
  5165. return this.m;
  5166. };
  5167. /**
  5168. * Returns the matrix as a Float32Array
  5169. * @returns the matrix underlying array.
  5170. */
  5171. Matrix.prototype.asArray = function () {
  5172. return this.toArray();
  5173. };
  5174. /**
  5175. * Inverts the current matrix in place
  5176. * @returns the current inverted matrix
  5177. */
  5178. Matrix.prototype.invert = function () {
  5179. this.invertToRef(this);
  5180. return this;
  5181. };
  5182. /**
  5183. * Sets all the matrix elements to zero
  5184. * @returns the current matrix
  5185. */
  5186. Matrix.prototype.reset = function () {
  5187. for (var index = 0; index < 16; index++) {
  5188. this.m[index] = 0.0;
  5189. }
  5190. this._markAsUpdated();
  5191. return this;
  5192. };
  5193. /**
  5194. * Adds the current matrix with a second one
  5195. * @param other defines the matrix to add
  5196. * @returns a new matrix as the addition of the current matrix and the given one
  5197. */
  5198. Matrix.prototype.add = function (other) {
  5199. var result = new Matrix();
  5200. this.addToRef(other, result);
  5201. return result;
  5202. };
  5203. /**
  5204. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5205. * @param other defines the matrix to add
  5206. * @param result defines the target matrix
  5207. * @returns the current matrix
  5208. */
  5209. Matrix.prototype.addToRef = function (other, result) {
  5210. for (var index = 0; index < 16; index++) {
  5211. result.m[index] = this.m[index] + other.m[index];
  5212. }
  5213. result._markAsUpdated();
  5214. return this;
  5215. };
  5216. /**
  5217. * Adds in place the given matrix to the current matrix
  5218. * @param other defines the second operand
  5219. * @returns the current updated matrix
  5220. */
  5221. Matrix.prototype.addToSelf = function (other) {
  5222. for (var index = 0; index < 16; index++) {
  5223. this.m[index] += other.m[index];
  5224. }
  5225. this._markAsUpdated();
  5226. return this;
  5227. };
  5228. /**
  5229. * Sets the given matrix to the current inverted Matrix
  5230. * @param other defines the target matrix
  5231. * @returns the unmodified current matrix
  5232. */
  5233. Matrix.prototype.invertToRef = function (other) {
  5234. var l1 = this.m[0];
  5235. var l2 = this.m[1];
  5236. var l3 = this.m[2];
  5237. var l4 = this.m[3];
  5238. var l5 = this.m[4];
  5239. var l6 = this.m[5];
  5240. var l7 = this.m[6];
  5241. var l8 = this.m[7];
  5242. var l9 = this.m[8];
  5243. var l10 = this.m[9];
  5244. var l11 = this.m[10];
  5245. var l12 = this.m[11];
  5246. var l13 = this.m[12];
  5247. var l14 = this.m[13];
  5248. var l15 = this.m[14];
  5249. var l16 = this.m[15];
  5250. var l17 = (l11 * l16) - (l12 * l15);
  5251. var l18 = (l10 * l16) - (l12 * l14);
  5252. var l19 = (l10 * l15) - (l11 * l14);
  5253. var l20 = (l9 * l16) - (l12 * l13);
  5254. var l21 = (l9 * l15) - (l11 * l13);
  5255. var l22 = (l9 * l14) - (l10 * l13);
  5256. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5257. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5258. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5259. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5260. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5261. var l28 = (l7 * l16) - (l8 * l15);
  5262. var l29 = (l6 * l16) - (l8 * l14);
  5263. var l30 = (l6 * l15) - (l7 * l14);
  5264. var l31 = (l5 * l16) - (l8 * l13);
  5265. var l32 = (l5 * l15) - (l7 * l13);
  5266. var l33 = (l5 * l14) - (l6 * l13);
  5267. var l34 = (l7 * l12) - (l8 * l11);
  5268. var l35 = (l6 * l12) - (l8 * l10);
  5269. var l36 = (l6 * l11) - (l7 * l10);
  5270. var l37 = (l5 * l12) - (l8 * l9);
  5271. var l38 = (l5 * l11) - (l7 * l9);
  5272. var l39 = (l5 * l10) - (l6 * l9);
  5273. other.m[0] = l23 * l27;
  5274. other.m[4] = l24 * l27;
  5275. other.m[8] = l25 * l27;
  5276. other.m[12] = l26 * l27;
  5277. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5278. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5279. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5280. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5281. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5282. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5283. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5284. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5285. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5286. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5287. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5288. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5289. other._markAsUpdated();
  5290. return this;
  5291. };
  5292. /**
  5293. * Inserts the translation vector (using 3 floats) in the current matrix
  5294. * @param x defines the 1st component of the translation
  5295. * @param y defines the 2nd component of the translation
  5296. * @param z defines the 3rd component of the translation
  5297. * @returns the current updated matrix
  5298. */
  5299. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5300. this.m[12] = x;
  5301. this.m[13] = y;
  5302. this.m[14] = z;
  5303. this._markAsUpdated();
  5304. return this;
  5305. };
  5306. /**
  5307. * Inserts the translation vector in the current matrix
  5308. * @param vector3 defines the translation to insert
  5309. * @returns the current updated matrix
  5310. */
  5311. Matrix.prototype.setTranslation = function (vector3) {
  5312. this.m[12] = vector3.x;
  5313. this.m[13] = vector3.y;
  5314. this.m[14] = vector3.z;
  5315. this._markAsUpdated();
  5316. return this;
  5317. };
  5318. /**
  5319. * Gets the translation value of the current matrix
  5320. * @returns a new Vector3 as the extracted translation from the matrix
  5321. */
  5322. Matrix.prototype.getTranslation = function () {
  5323. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5324. };
  5325. /**
  5326. * Fill a Vector3 with the extracted translation from the matrix
  5327. * @param result defines the Vector3 where to store the translation
  5328. * @returns the current matrix
  5329. */
  5330. Matrix.prototype.getTranslationToRef = function (result) {
  5331. result.x = this.m[12];
  5332. result.y = this.m[13];
  5333. result.z = this.m[14];
  5334. return this;
  5335. };
  5336. /**
  5337. * Remove rotation and scaling part from the matrix
  5338. * @returns the updated matrix
  5339. */
  5340. Matrix.prototype.removeRotationAndScaling = function () {
  5341. this.setRowFromFloats(0, 1, 0, 0, 0);
  5342. this.setRowFromFloats(1, 0, 1, 0, 0);
  5343. this.setRowFromFloats(2, 0, 0, 1, 0);
  5344. return this;
  5345. };
  5346. /**
  5347. * Multiply two matrices
  5348. * @param other defines the second operand
  5349. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5350. */
  5351. Matrix.prototype.multiply = function (other) {
  5352. var result = new Matrix();
  5353. this.multiplyToRef(other, result);
  5354. return result;
  5355. };
  5356. /**
  5357. * Copy the current matrix from the given one
  5358. * @param other defines the source matrix
  5359. * @returns the current updated matrix
  5360. */
  5361. Matrix.prototype.copyFrom = function (other) {
  5362. for (var index = 0; index < 16; index++) {
  5363. this.m[index] = other.m[index];
  5364. }
  5365. this._markAsUpdated();
  5366. return this;
  5367. };
  5368. /**
  5369. * Populates the given array from the starting index with the current matrix values
  5370. * @param array defines the target array
  5371. * @param offset defines the offset in the target array where to start storing values
  5372. * @returns the current matrix
  5373. */
  5374. Matrix.prototype.copyToArray = function (array, offset) {
  5375. if (offset === void 0) { offset = 0; }
  5376. for (var index = 0; index < 16; index++) {
  5377. array[offset + index] = this.m[index];
  5378. }
  5379. return this;
  5380. };
  5381. /**
  5382. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5383. * @param other defines the second operand
  5384. * @param result defines the matrix where to store the multiplication
  5385. * @returns the current matrix
  5386. */
  5387. Matrix.prototype.multiplyToRef = function (other, result) {
  5388. this.multiplyToArray(other, result.m, 0);
  5389. result._markAsUpdated();
  5390. return this;
  5391. };
  5392. /**
  5393. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5394. * @param other defines the second operand
  5395. * @param result defines the array where to store the multiplication
  5396. * @param offset defines the offset in the target array where to start storing values
  5397. * @returns the current matrix
  5398. */
  5399. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5400. var tm0 = this.m[0];
  5401. var tm1 = this.m[1];
  5402. var tm2 = this.m[2];
  5403. var tm3 = this.m[3];
  5404. var tm4 = this.m[4];
  5405. var tm5 = this.m[5];
  5406. var tm6 = this.m[6];
  5407. var tm7 = this.m[7];
  5408. var tm8 = this.m[8];
  5409. var tm9 = this.m[9];
  5410. var tm10 = this.m[10];
  5411. var tm11 = this.m[11];
  5412. var tm12 = this.m[12];
  5413. var tm13 = this.m[13];
  5414. var tm14 = this.m[14];
  5415. var tm15 = this.m[15];
  5416. var om0 = other.m[0];
  5417. var om1 = other.m[1];
  5418. var om2 = other.m[2];
  5419. var om3 = other.m[3];
  5420. var om4 = other.m[4];
  5421. var om5 = other.m[5];
  5422. var om6 = other.m[6];
  5423. var om7 = other.m[7];
  5424. var om8 = other.m[8];
  5425. var om9 = other.m[9];
  5426. var om10 = other.m[10];
  5427. var om11 = other.m[11];
  5428. var om12 = other.m[12];
  5429. var om13 = other.m[13];
  5430. var om14 = other.m[14];
  5431. var om15 = other.m[15];
  5432. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5433. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5434. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5435. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5436. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5437. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5438. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5439. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5440. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5441. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5442. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5443. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5444. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5445. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5446. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5447. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5448. return this;
  5449. };
  5450. /**
  5451. * Check equality between this matrix and a second one
  5452. * @param value defines the second matrix to compare
  5453. * @returns true is the current matrix and the given one values are strictly equal
  5454. */
  5455. Matrix.prototype.equals = function (value) {
  5456. return value &&
  5457. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5458. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5459. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5460. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5461. };
  5462. /**
  5463. * Clone the current matrix
  5464. * @returns a new matrix from the current matrix
  5465. */
  5466. Matrix.prototype.clone = function () {
  5467. 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]);
  5468. };
  5469. /**
  5470. * Returns the name of the current matrix class
  5471. * @returns the string "Matrix"
  5472. */
  5473. Matrix.prototype.getClassName = function () {
  5474. return "Matrix";
  5475. };
  5476. /**
  5477. * Gets the hash code of the current matrix
  5478. * @returns the hash code
  5479. */
  5480. Matrix.prototype.getHashCode = function () {
  5481. var hash = this.m[0] || 0;
  5482. for (var i = 1; i < 16; i++) {
  5483. hash = (hash * 397) ^ (this.m[i] || 0);
  5484. }
  5485. return hash;
  5486. };
  5487. /**
  5488. * Decomposes the current Matrix into a translation, rotation and scaling components
  5489. * @param scale defines the scale vector3 given as a reference to update
  5490. * @param rotation defines the rotation quaternion given as a reference to update
  5491. * @param translation defines the translation vector3 given as a reference to update
  5492. * @returns true if operation was successful
  5493. */
  5494. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5495. if (translation) {
  5496. translation.x = this.m[12];
  5497. translation.y = this.m[13];
  5498. translation.z = this.m[14];
  5499. }
  5500. scale = scale || MathTmp.Vector3[0];
  5501. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5502. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5503. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5504. if (this.determinant() <= 0) {
  5505. scale.y *= -1;
  5506. }
  5507. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5508. if (rotation) {
  5509. rotation.x = 0;
  5510. rotation.y = 0;
  5511. rotation.z = 0;
  5512. rotation.w = 1;
  5513. }
  5514. return false;
  5515. }
  5516. if (rotation) {
  5517. Matrix.FromValuesToRef(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, MathTmp.Matrix[0]);
  5518. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5519. }
  5520. return true;
  5521. };
  5522. /**
  5523. * Gets specific row of the matrix
  5524. * @param index defines the number of the row to get
  5525. * @returns the index-th row of the current matrix as a new Vector4
  5526. */
  5527. Matrix.prototype.getRow = function (index) {
  5528. if (index < 0 || index > 3) {
  5529. return null;
  5530. }
  5531. var i = index * 4;
  5532. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5533. };
  5534. /**
  5535. * Sets the index-th row of the current matrix to the vector4 values
  5536. * @param index defines the number of the row to set
  5537. * @param row defines the target vector4
  5538. * @returns the updated current matrix
  5539. */
  5540. Matrix.prototype.setRow = function (index, row) {
  5541. if (index < 0 || index > 3) {
  5542. return this;
  5543. }
  5544. var i = index * 4;
  5545. this.m[i + 0] = row.x;
  5546. this.m[i + 1] = row.y;
  5547. this.m[i + 2] = row.z;
  5548. this.m[i + 3] = row.w;
  5549. this._markAsUpdated();
  5550. return this;
  5551. };
  5552. /**
  5553. * Compute the transpose of the matrix
  5554. * @returns the new transposed matrix
  5555. */
  5556. Matrix.prototype.transpose = function () {
  5557. return Matrix.Transpose(this);
  5558. };
  5559. /**
  5560. * Compute the transpose of the matrix and store it in a given matrix
  5561. * @param result defines the target matrix
  5562. * @returns the current matrix
  5563. */
  5564. Matrix.prototype.transposeToRef = function (result) {
  5565. Matrix.TransposeToRef(this, result);
  5566. return this;
  5567. };
  5568. /**
  5569. * Sets the index-th row of the current matrix with the given 4 x float values
  5570. * @param index defines the row index
  5571. * @param x defines the x component to set
  5572. * @param y defines the y component to set
  5573. * @param z defines the z component to set
  5574. * @param w defines the w component to set
  5575. * @returns the updated current matrix
  5576. */
  5577. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5578. if (index < 0 || index > 3) {
  5579. return this;
  5580. }
  5581. var i = index * 4;
  5582. this.m[i + 0] = x;
  5583. this.m[i + 1] = y;
  5584. this.m[i + 2] = z;
  5585. this.m[i + 3] = w;
  5586. this._markAsUpdated();
  5587. return this;
  5588. };
  5589. /**
  5590. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5591. * @param scale defines the scale factor
  5592. * @returns a new matrix
  5593. */
  5594. Matrix.prototype.scale = function (scale) {
  5595. var result = new Matrix();
  5596. this.scaleToRef(scale, result);
  5597. return result;
  5598. };
  5599. /**
  5600. * Scale the current matrix values by a factor to a given result matrix
  5601. * @param scale defines the scale factor
  5602. * @param result defines the matrix to store the result
  5603. * @returns the current matrix
  5604. */
  5605. Matrix.prototype.scaleToRef = function (scale, result) {
  5606. for (var index = 0; index < 16; index++) {
  5607. result.m[index] = this.m[index] * scale;
  5608. }
  5609. result._markAsUpdated();
  5610. return this;
  5611. };
  5612. /**
  5613. * Scale the current matrix values by a factor and add the result to a given matrix
  5614. * @param scale defines the scale factor
  5615. * @param result defines the Matrix to store the result
  5616. * @returns the current matrix
  5617. */
  5618. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5619. for (var index = 0; index < 16; index++) {
  5620. result.m[index] += this.m[index] * scale;
  5621. }
  5622. result._markAsUpdated();
  5623. return this;
  5624. };
  5625. /**
  5626. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5627. * @param ref matrix to store the result
  5628. */
  5629. Matrix.prototype.toNormalMatrix = function (ref) {
  5630. this.invertToRef(ref);
  5631. ref.transpose();
  5632. var m = ref.m;
  5633. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5634. };
  5635. /**
  5636. * Gets only rotation part of the current matrix
  5637. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5638. */
  5639. Matrix.prototype.getRotationMatrix = function () {
  5640. var result = Matrix.Identity();
  5641. this.getRotationMatrixToRef(result);
  5642. return result;
  5643. };
  5644. /**
  5645. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5646. * @param result defines the target matrix to store data to
  5647. * @returns the current matrix
  5648. */
  5649. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5650. var m = this.m;
  5651. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5652. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5653. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5654. if (this.determinant() <= 0) {
  5655. sy *= -1;
  5656. }
  5657. if (sx === 0 || sy === 0 || sz === 0) {
  5658. Matrix.IdentityToRef(result);
  5659. }
  5660. else {
  5661. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  5662. }
  5663. return this;
  5664. };
  5665. // Statics
  5666. /**
  5667. * Creates a matrix from an array
  5668. * @param array defines the source array
  5669. * @param offset defines an offset in the source array
  5670. * @returns a new Matrix set from the starting index of the given array
  5671. */
  5672. Matrix.FromArray = function (array, offset) {
  5673. var result = new Matrix();
  5674. if (!offset) {
  5675. offset = 0;
  5676. }
  5677. Matrix.FromArrayToRef(array, offset, result);
  5678. return result;
  5679. };
  5680. /**
  5681. * Copy the content of an array into a given matrix
  5682. * @param array defines the source array
  5683. * @param offset defines an offset in the source array
  5684. * @param result defines the target matrix
  5685. */
  5686. Matrix.FromArrayToRef = function (array, offset, result) {
  5687. for (var index = 0; index < 16; index++) {
  5688. result.m[index] = array[index + offset];
  5689. }
  5690. result._markAsUpdated();
  5691. };
  5692. /**
  5693. * Stores an array into a matrix after having multiplied each component by a given factor
  5694. * @param array defines the source array
  5695. * @param offset defines the offset in the source array
  5696. * @param scale defines the scaling factor
  5697. * @param result defines the target matrix
  5698. */
  5699. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5700. for (var index = 0; index < 16; index++) {
  5701. result.m[index] = array[index + offset] * scale;
  5702. }
  5703. result._markAsUpdated();
  5704. };
  5705. /**
  5706. * Stores a list of values (16) inside a given matrix
  5707. * @param initialM11 defines 1st value of 1st row
  5708. * @param initialM12 defines 2nd value of 1st row
  5709. * @param initialM13 defines 3rd value of 1st row
  5710. * @param initialM14 defines 4th value of 1st row
  5711. * @param initialM21 defines 1st value of 2nd row
  5712. * @param initialM22 defines 2nd value of 2nd row
  5713. * @param initialM23 defines 3rd value of 2nd row
  5714. * @param initialM24 defines 4th value of 2nd row
  5715. * @param initialM31 defines 1st value of 3rd row
  5716. * @param initialM32 defines 2nd value of 3rd row
  5717. * @param initialM33 defines 3rd value of 3rd row
  5718. * @param initialM34 defines 4th value of 3rd row
  5719. * @param initialM41 defines 1st value of 4th row
  5720. * @param initialM42 defines 2nd value of 4th row
  5721. * @param initialM43 defines 3rd value of 4th row
  5722. * @param initialM44 defines 4th value of 4th row
  5723. * @param result defines the target matrix
  5724. */
  5725. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5726. result.m[0] = initialM11;
  5727. result.m[1] = initialM12;
  5728. result.m[2] = initialM13;
  5729. result.m[3] = initialM14;
  5730. result.m[4] = initialM21;
  5731. result.m[5] = initialM22;
  5732. result.m[6] = initialM23;
  5733. result.m[7] = initialM24;
  5734. result.m[8] = initialM31;
  5735. result.m[9] = initialM32;
  5736. result.m[10] = initialM33;
  5737. result.m[11] = initialM34;
  5738. result.m[12] = initialM41;
  5739. result.m[13] = initialM42;
  5740. result.m[14] = initialM43;
  5741. result.m[15] = initialM44;
  5742. result._markAsUpdated();
  5743. };
  5744. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5745. /**
  5746. * Gets an identity matrix that must not be updated
  5747. */
  5748. get: function () {
  5749. return Matrix._identityReadOnly;
  5750. },
  5751. enumerable: true,
  5752. configurable: true
  5753. });
  5754. /**
  5755. * Creates new matrix from a list of values (16)
  5756. * @param initialM11 defines 1st value of 1st row
  5757. * @param initialM12 defines 2nd value of 1st row
  5758. * @param initialM13 defines 3rd value of 1st row
  5759. * @param initialM14 defines 4th value of 1st row
  5760. * @param initialM21 defines 1st value of 2nd row
  5761. * @param initialM22 defines 2nd value of 2nd row
  5762. * @param initialM23 defines 3rd value of 2nd row
  5763. * @param initialM24 defines 4th value of 2nd row
  5764. * @param initialM31 defines 1st value of 3rd row
  5765. * @param initialM32 defines 2nd value of 3rd row
  5766. * @param initialM33 defines 3rd value of 3rd row
  5767. * @param initialM34 defines 4th value of 3rd row
  5768. * @param initialM41 defines 1st value of 4th row
  5769. * @param initialM42 defines 2nd value of 4th row
  5770. * @param initialM43 defines 3rd value of 4th row
  5771. * @param initialM44 defines 4th value of 4th row
  5772. * @returns the new matrix
  5773. */
  5774. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5775. var result = new Matrix();
  5776. result.m[0] = initialM11;
  5777. result.m[1] = initialM12;
  5778. result.m[2] = initialM13;
  5779. result.m[3] = initialM14;
  5780. result.m[4] = initialM21;
  5781. result.m[5] = initialM22;
  5782. result.m[6] = initialM23;
  5783. result.m[7] = initialM24;
  5784. result.m[8] = initialM31;
  5785. result.m[9] = initialM32;
  5786. result.m[10] = initialM33;
  5787. result.m[11] = initialM34;
  5788. result.m[12] = initialM41;
  5789. result.m[13] = initialM42;
  5790. result.m[14] = initialM43;
  5791. result.m[15] = initialM44;
  5792. return result;
  5793. };
  5794. /**
  5795. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5796. * @param scale defines the scale vector3
  5797. * @param rotation defines the rotation quaternion
  5798. * @param translation defines the translation vector3
  5799. * @returns a new matrix
  5800. */
  5801. Matrix.Compose = function (scale, rotation, translation) {
  5802. var result = Matrix.Identity();
  5803. Matrix.ComposeToRef(scale, rotation, translation, result);
  5804. return result;
  5805. };
  5806. /**
  5807. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5808. * @param scale defines the scale vector3
  5809. * @param rotation defines the rotation quaternion
  5810. * @param translation defines the translation vector3
  5811. * @param result defines the target matrix
  5812. */
  5813. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5814. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5815. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5816. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5817. result.setTranslation(translation);
  5818. };
  5819. /**
  5820. * Creates a new identity matrix
  5821. * @returns a new identity matrix
  5822. */
  5823. Matrix.Identity = function () {
  5824. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5825. };
  5826. /**
  5827. * Creates a new identity matrix and stores the result in a given matrix
  5828. * @param result defines the target matrix
  5829. */
  5830. Matrix.IdentityToRef = function (result) {
  5831. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  5832. };
  5833. /**
  5834. * Creates a new zero matrix
  5835. * @returns a new zero matrix
  5836. */
  5837. Matrix.Zero = function () {
  5838. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5839. };
  5840. /**
  5841. * Creates a new rotation matrix for "angle" radians around the X axis
  5842. * @param angle defines the angle (in radians) to use
  5843. * @return the new matrix
  5844. */
  5845. Matrix.RotationX = function (angle) {
  5846. var result = new Matrix();
  5847. Matrix.RotationXToRef(angle, result);
  5848. return result;
  5849. };
  5850. /**
  5851. * Creates a new matrix as the invert of a given matrix
  5852. * @param source defines the source matrix
  5853. * @returns the new matrix
  5854. */
  5855. Matrix.Invert = function (source) {
  5856. var result = new Matrix();
  5857. source.invertToRef(result);
  5858. return result;
  5859. };
  5860. /**
  5861. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5862. * @param angle defines the angle (in radians) to use
  5863. * @param result defines the target matrix
  5864. */
  5865. Matrix.RotationXToRef = function (angle, result) {
  5866. var s = Math.sin(angle);
  5867. var c = Math.cos(angle);
  5868. result.m[0] = 1.0;
  5869. result.m[15] = 1.0;
  5870. result.m[5] = c;
  5871. result.m[10] = c;
  5872. result.m[9] = -s;
  5873. result.m[6] = s;
  5874. result.m[1] = 0.0;
  5875. result.m[2] = 0.0;
  5876. result.m[3] = 0.0;
  5877. result.m[4] = 0.0;
  5878. result.m[7] = 0.0;
  5879. result.m[8] = 0.0;
  5880. result.m[11] = 0.0;
  5881. result.m[12] = 0.0;
  5882. result.m[13] = 0.0;
  5883. result.m[14] = 0.0;
  5884. result._markAsUpdated();
  5885. };
  5886. /**
  5887. * Creates a new rotation matrix for "angle" radians around the Y axis
  5888. * @param angle defines the angle (in radians) to use
  5889. * @return the new matrix
  5890. */
  5891. Matrix.RotationY = function (angle) {
  5892. var result = new Matrix();
  5893. Matrix.RotationYToRef(angle, result);
  5894. return result;
  5895. };
  5896. /**
  5897. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5898. * @param angle defines the angle (in radians) to use
  5899. * @param result defines the target matrix
  5900. */
  5901. Matrix.RotationYToRef = function (angle, result) {
  5902. var s = Math.sin(angle);
  5903. var c = Math.cos(angle);
  5904. result.m[5] = 1.0;
  5905. result.m[15] = 1.0;
  5906. result.m[0] = c;
  5907. result.m[2] = -s;
  5908. result.m[8] = s;
  5909. result.m[10] = c;
  5910. result.m[1] = 0.0;
  5911. result.m[3] = 0.0;
  5912. result.m[4] = 0.0;
  5913. result.m[6] = 0.0;
  5914. result.m[7] = 0.0;
  5915. result.m[9] = 0.0;
  5916. result.m[11] = 0.0;
  5917. result.m[12] = 0.0;
  5918. result.m[13] = 0.0;
  5919. result.m[14] = 0.0;
  5920. result._markAsUpdated();
  5921. };
  5922. /**
  5923. * Creates a new rotation matrix for "angle" radians around the Z axis
  5924. * @param angle defines the angle (in radians) to use
  5925. * @return the new matrix
  5926. */
  5927. Matrix.RotationZ = function (angle) {
  5928. var result = new Matrix();
  5929. Matrix.RotationZToRef(angle, result);
  5930. return result;
  5931. };
  5932. /**
  5933. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5934. * @param angle defines the angle (in radians) to use
  5935. * @param result defines the target matrix
  5936. */
  5937. Matrix.RotationZToRef = function (angle, result) {
  5938. var s = Math.sin(angle);
  5939. var c = Math.cos(angle);
  5940. result.m[10] = 1.0;
  5941. result.m[15] = 1.0;
  5942. result.m[0] = c;
  5943. result.m[1] = s;
  5944. result.m[4] = -s;
  5945. result.m[5] = c;
  5946. result.m[2] = 0.0;
  5947. result.m[3] = 0.0;
  5948. result.m[6] = 0.0;
  5949. result.m[7] = 0.0;
  5950. result.m[8] = 0.0;
  5951. result.m[9] = 0.0;
  5952. result.m[11] = 0.0;
  5953. result.m[12] = 0.0;
  5954. result.m[13] = 0.0;
  5955. result.m[14] = 0.0;
  5956. result._markAsUpdated();
  5957. };
  5958. /**
  5959. * Creates a new rotation matrix for "angle" radians around the given axis
  5960. * @param axis defines the axis to use
  5961. * @param angle defines the angle (in radians) to use
  5962. * @return the new matrix
  5963. */
  5964. Matrix.RotationAxis = function (axis, angle) {
  5965. var result = Matrix.Zero();
  5966. Matrix.RotationAxisToRef(axis, angle, result);
  5967. return result;
  5968. };
  5969. /**
  5970. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5971. * @param axis defines the axis to use
  5972. * @param angle defines the angle (in radians) to use
  5973. * @param result defines the target matrix
  5974. */
  5975. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5976. var s = Math.sin(-angle);
  5977. var c = Math.cos(-angle);
  5978. var c1 = 1 - c;
  5979. axis.normalize();
  5980. result.m[0] = (axis.x * axis.x) * c1 + c;
  5981. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5982. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5983. result.m[3] = 0.0;
  5984. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5985. result.m[5] = (axis.y * axis.y) * c1 + c;
  5986. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5987. result.m[7] = 0.0;
  5988. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5989. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5990. result.m[10] = (axis.z * axis.z) * c1 + c;
  5991. result.m[11] = 0.0;
  5992. result.m[15] = 1.0;
  5993. result._markAsUpdated();
  5994. };
  5995. /**
  5996. * Creates a rotation matrix
  5997. * @param yaw defines the yaw angle in radians (Y axis)
  5998. * @param pitch defines the pitch angle in radians (X axis)
  5999. * @param roll defines the roll angle in radians (X axis)
  6000. * @returns the new rotation matrix
  6001. */
  6002. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6003. var result = new Matrix();
  6004. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6005. return result;
  6006. };
  6007. /**
  6008. * Creates a rotation matrix and stores it in a given matrix
  6009. * @param yaw defines the yaw angle in radians (Y axis)
  6010. * @param pitch defines the pitch angle in radians (X axis)
  6011. * @param roll defines the roll angle in radians (X axis)
  6012. * @param result defines the target matrix
  6013. */
  6014. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6015. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6016. this._tempQuaternion.toRotationMatrix(result);
  6017. };
  6018. /**
  6019. * Creates a scaling matrix
  6020. * @param x defines the scale factor on X axis
  6021. * @param y defines the scale factor on Y axis
  6022. * @param z defines the scale factor on Z axis
  6023. * @returns the new matrix
  6024. */
  6025. Matrix.Scaling = function (x, y, z) {
  6026. var result = Matrix.Zero();
  6027. Matrix.ScalingToRef(x, y, z, result);
  6028. return result;
  6029. };
  6030. /**
  6031. * Creates a scaling matrix and stores it in a given matrix
  6032. * @param x defines the scale factor on X axis
  6033. * @param y defines the scale factor on Y axis
  6034. * @param z defines the scale factor on Z axis
  6035. * @param result defines the target matrix
  6036. */
  6037. Matrix.ScalingToRef = function (x, y, z, result) {
  6038. result.m[0] = x;
  6039. result.m[1] = 0.0;
  6040. result.m[2] = 0.0;
  6041. result.m[3] = 0.0;
  6042. result.m[4] = 0.0;
  6043. result.m[5] = y;
  6044. result.m[6] = 0.0;
  6045. result.m[7] = 0.0;
  6046. result.m[8] = 0.0;
  6047. result.m[9] = 0.0;
  6048. result.m[10] = z;
  6049. result.m[11] = 0.0;
  6050. result.m[12] = 0.0;
  6051. result.m[13] = 0.0;
  6052. result.m[14] = 0.0;
  6053. result.m[15] = 1.0;
  6054. result._markAsUpdated();
  6055. };
  6056. /**
  6057. * Creates a translation matrix
  6058. * @param x defines the translation on X axis
  6059. * @param y defines the translation on Y axis
  6060. * @param z defines the translationon Z axis
  6061. * @returns the new matrix
  6062. */
  6063. Matrix.Translation = function (x, y, z) {
  6064. var result = Matrix.Identity();
  6065. Matrix.TranslationToRef(x, y, z, result);
  6066. return result;
  6067. };
  6068. /**
  6069. * Creates a translation matrix and stores it in a given matrix
  6070. * @param x defines the translation on X axis
  6071. * @param y defines the translation on Y axis
  6072. * @param z defines the translationon Z axis
  6073. * @param result defines the target matrix
  6074. */
  6075. Matrix.TranslationToRef = function (x, y, z, result) {
  6076. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  6077. };
  6078. /**
  6079. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6080. * @param startValue defines the start value
  6081. * @param endValue defines the end value
  6082. * @param gradient defines the gradient factor
  6083. * @returns the new matrix
  6084. */
  6085. Matrix.Lerp = function (startValue, endValue, gradient) {
  6086. var result = Matrix.Zero();
  6087. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6088. return result;
  6089. };
  6090. /**
  6091. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6092. * @param startValue defines the start value
  6093. * @param endValue defines the end value
  6094. * @param gradient defines the gradient factor
  6095. * @param result defines the Matrix object where to store data
  6096. */
  6097. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6098. for (var index = 0; index < 16; index++) {
  6099. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6100. }
  6101. result._markAsUpdated();
  6102. };
  6103. /**
  6104. * Builds a new matrix whose values are computed by:
  6105. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6106. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6107. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6108. * @param startValue defines the first matrix
  6109. * @param endValue defines the second matrix
  6110. * @param gradient defines the gradient between the two matrices
  6111. * @returns the new matrix
  6112. */
  6113. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6114. var result = Matrix.Zero();
  6115. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6116. return result;
  6117. };
  6118. /**
  6119. * Update a matrix to values which are computed by:
  6120. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6121. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6122. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6123. * @param startValue defines the first matrix
  6124. * @param endValue defines the second matrix
  6125. * @param gradient defines the gradient between the two matrices
  6126. * @param result defines the target matrix
  6127. */
  6128. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6129. var startScale = MathTmp.Vector3[0];
  6130. var startRotation = MathTmp.Quaternion[0];
  6131. var startTranslation = MathTmp.Vector3[1];
  6132. startValue.decompose(startScale, startRotation, startTranslation);
  6133. var endScale = MathTmp.Vector3[2];
  6134. var endRotation = MathTmp.Quaternion[1];
  6135. var endTranslation = MathTmp.Vector3[3];
  6136. endValue.decompose(endScale, endRotation, endTranslation);
  6137. var resultScale = MathTmp.Vector3[4];
  6138. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6139. var resultRotation = MathTmp.Quaternion[2];
  6140. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6141. var resultTranslation = MathTmp.Vector3[5];
  6142. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6143. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6144. };
  6145. /**
  6146. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6147. * This function works in left handed mode
  6148. * @param eye defines the final position of the entity
  6149. * @param target defines where the entity should look at
  6150. * @param up defines the up vector for the entity
  6151. * @returns the new matrix
  6152. */
  6153. Matrix.LookAtLH = function (eye, target, up) {
  6154. var result = Matrix.Zero();
  6155. Matrix.LookAtLHToRef(eye, target, up, result);
  6156. return result;
  6157. };
  6158. /**
  6159. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6160. * This function works in left handed mode
  6161. * @param eye defines the final position of the entity
  6162. * @param target defines where the entity should look at
  6163. * @param up defines the up vector for the entity
  6164. * @param result defines the target matrix
  6165. */
  6166. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6167. // Z axis
  6168. target.subtractToRef(eye, this._zAxis);
  6169. this._zAxis.normalize();
  6170. // X axis
  6171. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6172. if (this._xAxis.lengthSquared() === 0) {
  6173. this._xAxis.x = 1.0;
  6174. }
  6175. else {
  6176. this._xAxis.normalize();
  6177. }
  6178. // Y axis
  6179. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6180. this._yAxis.normalize();
  6181. // Eye angles
  6182. var ex = -Vector3.Dot(this._xAxis, eye);
  6183. var ey = -Vector3.Dot(this._yAxis, eye);
  6184. var ez = -Vector3.Dot(this._zAxis, eye);
  6185. 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);
  6186. };
  6187. /**
  6188. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6189. * This function works in right handed mode
  6190. * @param eye defines the final position of the entity
  6191. * @param target defines where the entity should look at
  6192. * @param up defines the up vector for the entity
  6193. * @returns the new matrix
  6194. */
  6195. Matrix.LookAtRH = function (eye, target, up) {
  6196. var result = Matrix.Zero();
  6197. Matrix.LookAtRHToRef(eye, target, up, result);
  6198. return result;
  6199. };
  6200. /**
  6201. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6202. * This function works in right handed mode
  6203. * @param eye defines the final position of the entity
  6204. * @param target defines where the entity should look at
  6205. * @param up defines the up vector for the entity
  6206. * @param result defines the target matrix
  6207. */
  6208. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6209. // Z axis
  6210. eye.subtractToRef(target, this._zAxis);
  6211. this._zAxis.normalize();
  6212. // X axis
  6213. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6214. if (this._xAxis.lengthSquared() === 0) {
  6215. this._xAxis.x = 1.0;
  6216. }
  6217. else {
  6218. this._xAxis.normalize();
  6219. }
  6220. // Y axis
  6221. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6222. this._yAxis.normalize();
  6223. // Eye angles
  6224. var ex = -Vector3.Dot(this._xAxis, eye);
  6225. var ey = -Vector3.Dot(this._yAxis, eye);
  6226. var ez = -Vector3.Dot(this._zAxis, eye);
  6227. 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);
  6228. };
  6229. /**
  6230. * Create a left-handed orthographic projection matrix
  6231. * @param width defines the viewport width
  6232. * @param height defines the viewport height
  6233. * @param znear defines the near clip plane
  6234. * @param zfar defines the far clip plane
  6235. * @returns a new matrix as a left-handed orthographic projection matrix
  6236. */
  6237. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6238. var matrix = Matrix.Zero();
  6239. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6240. return matrix;
  6241. };
  6242. /**
  6243. * Store a left-handed orthographic projection to a given matrix
  6244. * @param width defines the viewport width
  6245. * @param height defines the viewport height
  6246. * @param znear defines the near clip plane
  6247. * @param zfar defines the far clip plane
  6248. * @param result defines the target matrix
  6249. */
  6250. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6251. var n = znear;
  6252. var f = zfar;
  6253. var a = 2.0 / width;
  6254. var b = 2.0 / height;
  6255. var c = 2.0 / (f - n);
  6256. var d = -(f + n) / (f - n);
  6257. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  6258. };
  6259. /**
  6260. * Create a left-handed orthographic projection matrix
  6261. * @param left defines the viewport left coordinate
  6262. * @param right defines the viewport right coordinate
  6263. * @param bottom defines the viewport bottom coordinate
  6264. * @param top defines the viewport top coordinate
  6265. * @param znear defines the near clip plane
  6266. * @param zfar defines the far clip plane
  6267. * @returns a new matrix as a left-handed orthographic projection matrix
  6268. */
  6269. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6270. var matrix = Matrix.Zero();
  6271. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6272. return matrix;
  6273. };
  6274. /**
  6275. * Stores a left-handed orthographic projection into a given matrix
  6276. * @param left defines the viewport left coordinate
  6277. * @param right defines the viewport right coordinate
  6278. * @param bottom defines the viewport bottom coordinate
  6279. * @param top defines the viewport top coordinate
  6280. * @param znear defines the near clip plane
  6281. * @param zfar defines the far clip plane
  6282. * @param result defines the target matrix
  6283. */
  6284. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6285. var n = znear;
  6286. var f = zfar;
  6287. var a = 2.0 / (right - left);
  6288. var b = 2.0 / (top - bottom);
  6289. var c = 2.0 / (f - n);
  6290. var d = -(f + n) / (f - n);
  6291. var i0 = (left + right) / (left - right);
  6292. var i1 = (top + bottom) / (bottom - top);
  6293. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  6294. };
  6295. /**
  6296. * Creates a right-handed orthographic projection matrix
  6297. * @param left defines the viewport left coordinate
  6298. * @param right defines the viewport right coordinate
  6299. * @param bottom defines the viewport bottom coordinate
  6300. * @param top defines the viewport top coordinate
  6301. * @param znear defines the near clip plane
  6302. * @param zfar defines the far clip plane
  6303. * @returns a new matrix as a right-handed orthographic projection matrix
  6304. */
  6305. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6306. var matrix = Matrix.Zero();
  6307. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6308. return matrix;
  6309. };
  6310. /**
  6311. * Stores a right-handed orthographic projection into a given matrix
  6312. * @param left defines the viewport left coordinate
  6313. * @param right defines the viewport right coordinate
  6314. * @param bottom defines the viewport bottom coordinate
  6315. * @param top defines the viewport top coordinate
  6316. * @param znear defines the near clip plane
  6317. * @param zfar defines the far clip plane
  6318. * @param result defines the target matrix
  6319. */
  6320. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6321. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6322. result.m[10] *= -1.0;
  6323. };
  6324. /**
  6325. * Creates a left-handed perspective projection matrix
  6326. * @param width defines the viewport width
  6327. * @param height defines the viewport height
  6328. * @param znear defines the near clip plane
  6329. * @param zfar defines the far clip plane
  6330. * @returns a new matrix as a left-handed perspective projection matrix
  6331. */
  6332. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6333. var matrix = Matrix.Zero();
  6334. var n = znear;
  6335. var f = zfar;
  6336. var a = 2.0 * n / width;
  6337. var b = 2.0 * n / height;
  6338. var c = (f + n) / (f - n);
  6339. var d = -2.0 * f * n / (f - n);
  6340. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  6341. return matrix;
  6342. };
  6343. /**
  6344. * Creates a left-handed perspective projection matrix
  6345. * @param fov defines the horizontal field of view
  6346. * @param aspect defines the aspect ratio
  6347. * @param znear defines the near clip plane
  6348. * @param zfar defines the far clip plane
  6349. * @returns a new matrix as a left-handed perspective projection matrix
  6350. */
  6351. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6352. var matrix = Matrix.Zero();
  6353. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6354. return matrix;
  6355. };
  6356. /**
  6357. * Stores a left-handed perspective projection into a given matrix
  6358. * @param fov defines the horizontal field of view
  6359. * @param aspect defines the aspect ratio
  6360. * @param znear defines the near clip plane
  6361. * @param zfar defines the far clip plane
  6362. * @param result defines the target matrix
  6363. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6364. */
  6365. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6366. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6367. var n = znear;
  6368. var f = zfar;
  6369. var t = 1.0 / (Math.tan(fov * 0.5));
  6370. var a = isVerticalFovFixed ? (t / aspect) : t;
  6371. var b = isVerticalFovFixed ? t : (t * aspect);
  6372. var c = (f + n) / (f - n);
  6373. var d = -2.0 * f * n / (f - n);
  6374. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  6375. };
  6376. /**
  6377. * Creates a right-handed perspective projection matrix
  6378. * @param fov defines the horizontal field of view
  6379. * @param aspect defines the aspect ratio
  6380. * @param znear defines the near clip plane
  6381. * @param zfar defines the far clip plane
  6382. * @returns a new matrix as a right-handed perspective projection matrix
  6383. */
  6384. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6385. var matrix = Matrix.Zero();
  6386. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6387. return matrix;
  6388. };
  6389. /**
  6390. * Stores a right-handed perspective projection into a given matrix
  6391. * @param fov defines the horizontal field of view
  6392. * @param aspect defines the aspect ratio
  6393. * @param znear defines the near clip plane
  6394. * @param zfar defines the far clip plane
  6395. * @param result defines the target matrix
  6396. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6397. */
  6398. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6399. //alternatively this could be expressed as:
  6400. // m = PerspectiveFovLHToRef
  6401. // m[10] *= -1.0;
  6402. // m[11] *= -1.0;
  6403. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6404. var n = znear;
  6405. var f = zfar;
  6406. var t = 1.0 / (Math.tan(fov * 0.5));
  6407. var a = isVerticalFovFixed ? (t / aspect) : t;
  6408. var b = isVerticalFovFixed ? t : (t * aspect);
  6409. var c = -(f + n) / (f - n);
  6410. var d = -2 * f * n / (f - n);
  6411. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  6412. };
  6413. /**
  6414. * Stores a perspective projection for WebVR info a given matrix
  6415. * @param fov defines the field of view
  6416. * @param znear defines the near clip plane
  6417. * @param zfar defines the far clip plane
  6418. * @param result defines the target matrix
  6419. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6420. */
  6421. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6422. if (rightHanded === void 0) { rightHanded = false; }
  6423. var rightHandedFactor = rightHanded ? -1 : 1;
  6424. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6425. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6426. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6427. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6428. var xScale = 2.0 / (leftTan + rightTan);
  6429. var yScale = 2.0 / (upTan + downTan);
  6430. result.m[0] = xScale;
  6431. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6432. result.m[5] = yScale;
  6433. result.m[6] = result.m[7] = 0.0;
  6434. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6435. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6436. result.m[10] = -zfar / (znear - zfar);
  6437. result.m[11] = 1.0 * rightHandedFactor;
  6438. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6439. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6440. result._markAsUpdated();
  6441. };
  6442. /**
  6443. * Computes a complete transformation matrix
  6444. * @param viewport defines the viewport to use
  6445. * @param world defines the world matrix
  6446. * @param view defines the view matrix
  6447. * @param projection defines the projection matrix
  6448. * @param zmin defines the near clip plane
  6449. * @param zmax defines the far clip plane
  6450. * @returns the transformation matrix
  6451. */
  6452. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6453. var cw = viewport.width;
  6454. var ch = viewport.height;
  6455. var cx = viewport.x;
  6456. var cy = viewport.y;
  6457. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  6458. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6459. };
  6460. /**
  6461. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6462. * @param matrix defines the matrix to use
  6463. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6464. */
  6465. Matrix.GetAsMatrix2x2 = function (matrix) {
  6466. return new Float32Array([
  6467. matrix.m[0], matrix.m[1],
  6468. matrix.m[4], matrix.m[5]
  6469. ]);
  6470. };
  6471. /**
  6472. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6473. * @param matrix defines the matrix to use
  6474. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6475. */
  6476. Matrix.GetAsMatrix3x3 = function (matrix) {
  6477. return new Float32Array([
  6478. matrix.m[0], matrix.m[1], matrix.m[2],
  6479. matrix.m[4], matrix.m[5], matrix.m[6],
  6480. matrix.m[8], matrix.m[9], matrix.m[10]
  6481. ]);
  6482. };
  6483. /**
  6484. * Compute the transpose of a given matrix
  6485. * @param matrix defines the matrix to transpose
  6486. * @returns the new matrix
  6487. */
  6488. Matrix.Transpose = function (matrix) {
  6489. var result = new Matrix();
  6490. Matrix.TransposeToRef(matrix, result);
  6491. return result;
  6492. };
  6493. /**
  6494. * Compute the transpose of a matrix and store it in a target matrix
  6495. * @param matrix defines the matrix to transpose
  6496. * @param result defines the target matrix
  6497. */
  6498. Matrix.TransposeToRef = function (matrix, result) {
  6499. result.m[0] = matrix.m[0];
  6500. result.m[1] = matrix.m[4];
  6501. result.m[2] = matrix.m[8];
  6502. result.m[3] = matrix.m[12];
  6503. result.m[4] = matrix.m[1];
  6504. result.m[5] = matrix.m[5];
  6505. result.m[6] = matrix.m[9];
  6506. result.m[7] = matrix.m[13];
  6507. result.m[8] = matrix.m[2];
  6508. result.m[9] = matrix.m[6];
  6509. result.m[10] = matrix.m[10];
  6510. result.m[11] = matrix.m[14];
  6511. result.m[12] = matrix.m[3];
  6512. result.m[13] = matrix.m[7];
  6513. result.m[14] = matrix.m[11];
  6514. result.m[15] = matrix.m[15];
  6515. };
  6516. /**
  6517. * Computes a reflection matrix from a plane
  6518. * @param plane defines the reflection plane
  6519. * @returns a new matrix
  6520. */
  6521. Matrix.Reflection = function (plane) {
  6522. var matrix = new Matrix();
  6523. Matrix.ReflectionToRef(plane, matrix);
  6524. return matrix;
  6525. };
  6526. /**
  6527. * Computes a reflection matrix from a plane
  6528. * @param plane defines the reflection plane
  6529. * @param result defines the target matrix
  6530. */
  6531. Matrix.ReflectionToRef = function (plane, result) {
  6532. plane.normalize();
  6533. var x = plane.normal.x;
  6534. var y = plane.normal.y;
  6535. var z = plane.normal.z;
  6536. var temp = -2 * x;
  6537. var temp2 = -2 * y;
  6538. var temp3 = -2 * z;
  6539. result.m[0] = (temp * x) + 1;
  6540. result.m[1] = temp2 * x;
  6541. result.m[2] = temp3 * x;
  6542. result.m[3] = 0.0;
  6543. result.m[4] = temp * y;
  6544. result.m[5] = (temp2 * y) + 1;
  6545. result.m[6] = temp3 * y;
  6546. result.m[7] = 0.0;
  6547. result.m[8] = temp * z;
  6548. result.m[9] = temp2 * z;
  6549. result.m[10] = (temp3 * z) + 1;
  6550. result.m[11] = 0.0;
  6551. result.m[12] = temp * plane.d;
  6552. result.m[13] = temp2 * plane.d;
  6553. result.m[14] = temp3 * plane.d;
  6554. result.m[15] = 1.0;
  6555. result._markAsUpdated();
  6556. };
  6557. /**
  6558. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6559. * @param xaxis defines the value of the 1st axis
  6560. * @param yaxis defines the value of the 2nd axis
  6561. * @param zaxis defines the value of the 3rd axis
  6562. * @param result defines the target matrix
  6563. */
  6564. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6565. result.m[0] = xaxis.x;
  6566. result.m[1] = xaxis.y;
  6567. result.m[2] = xaxis.z;
  6568. result.m[3] = 0.0;
  6569. result.m[4] = yaxis.x;
  6570. result.m[5] = yaxis.y;
  6571. result.m[6] = yaxis.z;
  6572. result.m[7] = 0.0;
  6573. result.m[8] = zaxis.x;
  6574. result.m[9] = zaxis.y;
  6575. result.m[10] = zaxis.z;
  6576. result.m[11] = 0.0;
  6577. result.m[12] = 0.0;
  6578. result.m[13] = 0.0;
  6579. result.m[14] = 0.0;
  6580. result.m[15] = 1.0;
  6581. result._markAsUpdated();
  6582. };
  6583. /**
  6584. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6585. * @param quat defines the quaternion to use
  6586. * @param result defines the target matrix
  6587. */
  6588. Matrix.FromQuaternionToRef = function (quat, result) {
  6589. var xx = quat.x * quat.x;
  6590. var yy = quat.y * quat.y;
  6591. var zz = quat.z * quat.z;
  6592. var xy = quat.x * quat.y;
  6593. var zw = quat.z * quat.w;
  6594. var zx = quat.z * quat.x;
  6595. var yw = quat.y * quat.w;
  6596. var yz = quat.y * quat.z;
  6597. var xw = quat.x * quat.w;
  6598. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6599. result.m[1] = 2.0 * (xy + zw);
  6600. result.m[2] = 2.0 * (zx - yw);
  6601. result.m[3] = 0.0;
  6602. result.m[4] = 2.0 * (xy - zw);
  6603. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6604. result.m[6] = 2.0 * (yz + xw);
  6605. result.m[7] = 0.0;
  6606. result.m[8] = 2.0 * (zx + yw);
  6607. result.m[9] = 2.0 * (yz - xw);
  6608. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6609. result.m[11] = 0.0;
  6610. result.m[12] = 0.0;
  6611. result.m[13] = 0.0;
  6612. result.m[14] = 0.0;
  6613. result.m[15] = 1.0;
  6614. result._markAsUpdated();
  6615. };
  6616. Matrix._tempQuaternion = new Quaternion();
  6617. Matrix._xAxis = Vector3.Zero();
  6618. Matrix._yAxis = Vector3.Zero();
  6619. Matrix._zAxis = Vector3.Zero();
  6620. Matrix._updateFlagSeed = 0;
  6621. Matrix._identityReadOnly = Matrix.Identity();
  6622. return Matrix;
  6623. }());
  6624. BABYLON.Matrix = Matrix;
  6625. var Plane = /** @class */ (function () {
  6626. /**
  6627. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6628. */
  6629. function Plane(a, b, c, d) {
  6630. this.normal = new Vector3(a, b, c);
  6631. this.d = d;
  6632. }
  6633. /**
  6634. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6635. */
  6636. Plane.prototype.asArray = function () {
  6637. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6638. };
  6639. // Methods
  6640. /**
  6641. * Returns a new plane copied from the current Plane.
  6642. */
  6643. Plane.prototype.clone = function () {
  6644. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6645. };
  6646. /**
  6647. * Returns the string "Plane".
  6648. */
  6649. Plane.prototype.getClassName = function () {
  6650. return "Plane";
  6651. };
  6652. /**
  6653. * Returns the Plane hash code.
  6654. */
  6655. Plane.prototype.getHashCode = function () {
  6656. var hash = this.normal.getHashCode();
  6657. hash = (hash * 397) ^ (this.d || 0);
  6658. return hash;
  6659. };
  6660. /**
  6661. * Normalize the current Plane in place.
  6662. * Returns the updated Plane.
  6663. */
  6664. Plane.prototype.normalize = function () {
  6665. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6666. var magnitude = 0.0;
  6667. if (norm !== 0) {
  6668. magnitude = 1.0 / norm;
  6669. }
  6670. this.normal.x *= magnitude;
  6671. this.normal.y *= magnitude;
  6672. this.normal.z *= magnitude;
  6673. this.d *= magnitude;
  6674. return this;
  6675. };
  6676. /**
  6677. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6678. */
  6679. Plane.prototype.transform = function (transformation) {
  6680. var transposedMatrix = Matrix.Transpose(transformation);
  6681. var x = this.normal.x;
  6682. var y = this.normal.y;
  6683. var z = this.normal.z;
  6684. var d = this.d;
  6685. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6686. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6687. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6688. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6689. return new Plane(normalX, normalY, normalZ, finalD);
  6690. };
  6691. /**
  6692. * Returns the dot product (float) of the point coordinates and the plane normal.
  6693. */
  6694. Plane.prototype.dotCoordinate = function (point) {
  6695. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6696. };
  6697. /**
  6698. * Updates the current Plane from the plane defined by the three given points.
  6699. * Returns the updated Plane.
  6700. */
  6701. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6702. var x1 = point2.x - point1.x;
  6703. var y1 = point2.y - point1.y;
  6704. var z1 = point2.z - point1.z;
  6705. var x2 = point3.x - point1.x;
  6706. var y2 = point3.y - point1.y;
  6707. var z2 = point3.z - point1.z;
  6708. var yz = (y1 * z2) - (z1 * y2);
  6709. var xz = (z1 * x2) - (x1 * z2);
  6710. var xy = (x1 * y2) - (y1 * x2);
  6711. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6712. var invPyth;
  6713. if (pyth !== 0) {
  6714. invPyth = 1.0 / pyth;
  6715. }
  6716. else {
  6717. invPyth = 0.0;
  6718. }
  6719. this.normal.x = yz * invPyth;
  6720. this.normal.y = xz * invPyth;
  6721. this.normal.z = xy * invPyth;
  6722. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6723. return this;
  6724. };
  6725. /**
  6726. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6727. */
  6728. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6729. var dot = Vector3.Dot(this.normal, direction);
  6730. return (dot <= epsilon);
  6731. };
  6732. /**
  6733. * Returns the signed distance (float) from the given point to the Plane.
  6734. */
  6735. Plane.prototype.signedDistanceTo = function (point) {
  6736. return Vector3.Dot(point, this.normal) + this.d;
  6737. };
  6738. // Statics
  6739. /**
  6740. * Returns a new Plane from the given array.
  6741. */
  6742. Plane.FromArray = function (array) {
  6743. return new Plane(array[0], array[1], array[2], array[3]);
  6744. };
  6745. /**
  6746. * Returns a new Plane defined by the three given points.
  6747. */
  6748. Plane.FromPoints = function (point1, point2, point3) {
  6749. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6750. result.copyFromPoints(point1, point2, point3);
  6751. return result;
  6752. };
  6753. /**
  6754. * Returns a new Plane the normal vector to this plane at the given origin point.
  6755. * Note : the vector "normal" is updated because normalized.
  6756. */
  6757. Plane.FromPositionAndNormal = function (origin, normal) {
  6758. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6759. normal.normalize();
  6760. result.normal = normal;
  6761. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6762. return result;
  6763. };
  6764. /**
  6765. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6766. */
  6767. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6768. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6769. return Vector3.Dot(point, normal) + d;
  6770. };
  6771. return Plane;
  6772. }());
  6773. BABYLON.Plane = Plane;
  6774. var Viewport = /** @class */ (function () {
  6775. /**
  6776. * Creates a Viewport object located at (x, y) and sized (width, height).
  6777. */
  6778. function Viewport(x, y, width, height) {
  6779. this.x = x;
  6780. this.y = y;
  6781. this.width = width;
  6782. this.height = height;
  6783. }
  6784. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6785. if (renderWidthOrEngine.getRenderWidth) {
  6786. var engine = renderWidthOrEngine;
  6787. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6788. }
  6789. var renderWidth = renderWidthOrEngine;
  6790. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6791. };
  6792. /**
  6793. * Returns a new Viewport copied from the current one.
  6794. */
  6795. Viewport.prototype.clone = function () {
  6796. return new Viewport(this.x, this.y, this.width, this.height);
  6797. };
  6798. return Viewport;
  6799. }());
  6800. BABYLON.Viewport = Viewport;
  6801. var Frustum = /** @class */ (function () {
  6802. function Frustum() {
  6803. }
  6804. /**
  6805. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6806. */
  6807. Frustum.GetPlanes = function (transform) {
  6808. var frustumPlanes = [];
  6809. for (var index = 0; index < 6; index++) {
  6810. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6811. }
  6812. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6813. return frustumPlanes;
  6814. };
  6815. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6816. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6817. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6818. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6819. frustumPlane.d = transform.m[15] + transform.m[14];
  6820. frustumPlane.normalize();
  6821. };
  6822. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6823. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6824. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6825. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6826. frustumPlane.d = transform.m[15] - transform.m[14];
  6827. frustumPlane.normalize();
  6828. };
  6829. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6830. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6831. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6832. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6833. frustumPlane.d = transform.m[15] + transform.m[12];
  6834. frustumPlane.normalize();
  6835. };
  6836. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6837. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6838. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6839. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6840. frustumPlane.d = transform.m[15] - transform.m[12];
  6841. frustumPlane.normalize();
  6842. };
  6843. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6844. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6845. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6846. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6847. frustumPlane.d = transform.m[15] - transform.m[13];
  6848. frustumPlane.normalize();
  6849. };
  6850. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6851. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6852. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6853. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6854. frustumPlane.d = transform.m[15] + transform.m[13];
  6855. frustumPlane.normalize();
  6856. };
  6857. /**
  6858. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6859. */
  6860. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6861. // Near
  6862. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6863. // Far
  6864. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6865. // Left
  6866. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6867. // Right
  6868. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6869. // Top
  6870. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6871. // Bottom
  6872. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6873. };
  6874. return Frustum;
  6875. }());
  6876. BABYLON.Frustum = Frustum;
  6877. /** Defines supported spaces */
  6878. var Space;
  6879. (function (Space) {
  6880. /** Local (object) space */
  6881. Space[Space["LOCAL"] = 0] = "LOCAL";
  6882. /** World space */
  6883. Space[Space["WORLD"] = 1] = "WORLD";
  6884. /** Bone space */
  6885. Space[Space["BONE"] = 2] = "BONE";
  6886. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6887. /** Defines the 3 main axes */
  6888. var Axis = /** @class */ (function () {
  6889. function Axis() {
  6890. }
  6891. /** X axis */
  6892. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6893. /** Y axis */
  6894. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6895. /** Z axis */
  6896. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6897. return Axis;
  6898. }());
  6899. BABYLON.Axis = Axis;
  6900. ;
  6901. var BezierCurve = /** @class */ (function () {
  6902. function BezierCurve() {
  6903. }
  6904. /**
  6905. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6906. */
  6907. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6908. // Extract X (which is equal to time here)
  6909. var f0 = 1 - 3 * x2 + 3 * x1;
  6910. var f1 = 3 * x2 - 6 * x1;
  6911. var f2 = 3 * x1;
  6912. var refinedT = t;
  6913. for (var i = 0; i < 5; i++) {
  6914. var refinedT2 = refinedT * refinedT;
  6915. var refinedT3 = refinedT2 * refinedT;
  6916. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6917. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6918. refinedT -= (x - t) * slope;
  6919. refinedT = Math.min(1, Math.max(0, refinedT));
  6920. }
  6921. // Resolve cubic bezier for the given x
  6922. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6923. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6924. Math.pow(refinedT, 3);
  6925. };
  6926. return BezierCurve;
  6927. }());
  6928. BABYLON.BezierCurve = BezierCurve;
  6929. /**
  6930. * Defines potential orientation for back face culling
  6931. */
  6932. var Orientation;
  6933. (function (Orientation) {
  6934. /**
  6935. * Clockwise
  6936. */
  6937. Orientation[Orientation["CW"] = 0] = "CW";
  6938. /** Counter clockwise */
  6939. Orientation[Orientation["CCW"] = 1] = "CCW";
  6940. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6941. /**
  6942. * Defines angle representation
  6943. */
  6944. var Angle = /** @class */ (function () {
  6945. /**
  6946. * Creates an Angle object of "radians" radians (float).
  6947. */
  6948. function Angle(radians) {
  6949. this._radians = radians;
  6950. if (this._radians < 0.0)
  6951. this._radians += (2.0 * Math.PI);
  6952. }
  6953. /**
  6954. * Get value in degrees
  6955. * @returns the Angle value in degrees (float)
  6956. */
  6957. Angle.prototype.degrees = function () {
  6958. return this._radians * 180.0 / Math.PI;
  6959. };
  6960. /**
  6961. * Get value in radians
  6962. * @returns the Angle value in radians (float)
  6963. */
  6964. Angle.prototype.radians = function () {
  6965. return this._radians;
  6966. };
  6967. /**
  6968. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6969. * @param a defines first vector
  6970. * @param b defines second vector
  6971. * @returns a new Angle
  6972. */
  6973. Angle.BetweenTwoPoints = function (a, b) {
  6974. var delta = b.subtract(a);
  6975. var theta = Math.atan2(delta.y, delta.x);
  6976. return new Angle(theta);
  6977. };
  6978. /**
  6979. * Gets a new Angle object from the given float in radians
  6980. * @param radians defines the angle value in radians
  6981. * @returns a new Angle
  6982. */
  6983. Angle.FromRadians = function (radians) {
  6984. return new Angle(radians);
  6985. };
  6986. /**
  6987. * Gets a new Angle object from the given float in degrees
  6988. * @param degrees defines the angle value in degrees
  6989. * @returns a new Angle
  6990. */
  6991. Angle.FromDegrees = function (degrees) {
  6992. return new Angle(degrees * Math.PI / 180.0);
  6993. };
  6994. return Angle;
  6995. }());
  6996. BABYLON.Angle = Angle;
  6997. var Arc2 = /** @class */ (function () {
  6998. /**
  6999. * Creates an Arc object from the three given points : start, middle and end.
  7000. */
  7001. function Arc2(startPoint, midPoint, endPoint) {
  7002. this.startPoint = startPoint;
  7003. this.midPoint = midPoint;
  7004. this.endPoint = endPoint;
  7005. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7006. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7007. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7008. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7009. 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);
  7010. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7011. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7012. var a1 = this.startAngle.degrees();
  7013. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7014. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7015. // angles correction
  7016. if (a2 - a1 > +180.0)
  7017. a2 -= 360.0;
  7018. if (a2 - a1 < -180.0)
  7019. a2 += 360.0;
  7020. if (a3 - a2 > +180.0)
  7021. a3 -= 360.0;
  7022. if (a3 - a2 < -180.0)
  7023. a3 += 360.0;
  7024. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7025. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7026. }
  7027. return Arc2;
  7028. }());
  7029. BABYLON.Arc2 = Arc2;
  7030. var Path2 = /** @class */ (function () {
  7031. /**
  7032. * Creates a Path2 object from the starting 2D coordinates x and y.
  7033. */
  7034. function Path2(x, y) {
  7035. this._points = new Array();
  7036. this._length = 0.0;
  7037. this.closed = false;
  7038. this._points.push(new Vector2(x, y));
  7039. }
  7040. /**
  7041. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7042. * Returns the updated Path2.
  7043. */
  7044. Path2.prototype.addLineTo = function (x, y) {
  7045. if (this.closed) {
  7046. return this;
  7047. }
  7048. var newPoint = new Vector2(x, y);
  7049. var previousPoint = this._points[this._points.length - 1];
  7050. this._points.push(newPoint);
  7051. this._length += newPoint.subtract(previousPoint).length();
  7052. return this;
  7053. };
  7054. /**
  7055. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  7056. * Returns the updated Path2.
  7057. */
  7058. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7059. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7060. if (this.closed) {
  7061. return this;
  7062. }
  7063. var startPoint = this._points[this._points.length - 1];
  7064. var midPoint = new Vector2(midX, midY);
  7065. var endPoint = new Vector2(endX, endY);
  7066. var arc = new Arc2(startPoint, midPoint, endPoint);
  7067. var increment = arc.angle.radians() / numberOfSegments;
  7068. if (arc.orientation === Orientation.CW)
  7069. increment *= -1;
  7070. var currentAngle = arc.startAngle.radians() + increment;
  7071. for (var i = 0; i < numberOfSegments; i++) {
  7072. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7073. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7074. this.addLineTo(x, y);
  7075. currentAngle += increment;
  7076. }
  7077. return this;
  7078. };
  7079. /**
  7080. * Closes the Path2.
  7081. * Returns the Path2.
  7082. */
  7083. Path2.prototype.close = function () {
  7084. this.closed = true;
  7085. return this;
  7086. };
  7087. /**
  7088. * Returns the Path2 total length (float).
  7089. */
  7090. Path2.prototype.length = function () {
  7091. var result = this._length;
  7092. if (!this.closed) {
  7093. var lastPoint = this._points[this._points.length - 1];
  7094. var firstPoint = this._points[0];
  7095. result += (firstPoint.subtract(lastPoint).length());
  7096. }
  7097. return result;
  7098. };
  7099. /**
  7100. * Returns the Path2 internal array of points.
  7101. */
  7102. Path2.prototype.getPoints = function () {
  7103. return this._points;
  7104. };
  7105. /**
  7106. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7107. */
  7108. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7109. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7110. return Vector2.Zero();
  7111. }
  7112. var lengthPosition = normalizedLengthPosition * this.length();
  7113. var previousOffset = 0;
  7114. for (var i = 0; i < this._points.length; i++) {
  7115. var j = (i + 1) % this._points.length;
  7116. var a = this._points[i];
  7117. var b = this._points[j];
  7118. var bToA = b.subtract(a);
  7119. var nextOffset = (bToA.length() + previousOffset);
  7120. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7121. var dir = bToA.normalize();
  7122. var localOffset = lengthPosition - previousOffset;
  7123. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7124. }
  7125. previousOffset = nextOffset;
  7126. }
  7127. return Vector2.Zero();
  7128. };
  7129. /**
  7130. * Returns a new Path2 starting at the coordinates (x, y).
  7131. */
  7132. Path2.StartingAt = function (x, y) {
  7133. return new Path2(x, y);
  7134. };
  7135. return Path2;
  7136. }());
  7137. BABYLON.Path2 = Path2;
  7138. var Path3D = /** @class */ (function () {
  7139. /**
  7140. * new Path3D(path, normal, raw)
  7141. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7142. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7143. * path : an array of Vector3, the curve axis of the Path3D
  7144. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7145. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7146. */
  7147. function Path3D(path, firstNormal, raw) {
  7148. if (firstNormal === void 0) { firstNormal = null; }
  7149. this.path = path;
  7150. this._curve = new Array();
  7151. this._distances = new Array();
  7152. this._tangents = new Array();
  7153. this._normals = new Array();
  7154. this._binormals = new Array();
  7155. for (var p = 0; p < path.length; p++) {
  7156. this._curve[p] = path[p].clone(); // hard copy
  7157. }
  7158. this._raw = raw || false;
  7159. this._compute(firstNormal);
  7160. }
  7161. /**
  7162. * Returns the Path3D array of successive Vector3 designing its curve.
  7163. */
  7164. Path3D.prototype.getCurve = function () {
  7165. return this._curve;
  7166. };
  7167. /**
  7168. * Returns an array populated with tangent vectors on each Path3D curve point.
  7169. */
  7170. Path3D.prototype.getTangents = function () {
  7171. return this._tangents;
  7172. };
  7173. /**
  7174. * Returns an array populated with normal vectors on each Path3D curve point.
  7175. */
  7176. Path3D.prototype.getNormals = function () {
  7177. return this._normals;
  7178. };
  7179. /**
  7180. * Returns an array populated with binormal vectors on each Path3D curve point.
  7181. */
  7182. Path3D.prototype.getBinormals = function () {
  7183. return this._binormals;
  7184. };
  7185. /**
  7186. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7187. */
  7188. Path3D.prototype.getDistances = function () {
  7189. return this._distances;
  7190. };
  7191. /**
  7192. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7193. * Returns the same object updated.
  7194. */
  7195. Path3D.prototype.update = function (path, firstNormal) {
  7196. if (firstNormal === void 0) { firstNormal = null; }
  7197. for (var p = 0; p < path.length; p++) {
  7198. this._curve[p].x = path[p].x;
  7199. this._curve[p].y = path[p].y;
  7200. this._curve[p].z = path[p].z;
  7201. }
  7202. this._compute(firstNormal);
  7203. return this;
  7204. };
  7205. // private function compute() : computes tangents, normals and binormals
  7206. Path3D.prototype._compute = function (firstNormal) {
  7207. var l = this._curve.length;
  7208. // first and last tangents
  7209. this._tangents[0] = this._getFirstNonNullVector(0);
  7210. if (!this._raw) {
  7211. this._tangents[0].normalize();
  7212. }
  7213. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7214. if (!this._raw) {
  7215. this._tangents[l - 1].normalize();
  7216. }
  7217. // normals and binormals at first point : arbitrary vector with _normalVector()
  7218. var tg0 = this._tangents[0];
  7219. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7220. this._normals[0] = pp0;
  7221. if (!this._raw) {
  7222. this._normals[0].normalize();
  7223. }
  7224. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7225. if (!this._raw) {
  7226. this._binormals[0].normalize();
  7227. }
  7228. this._distances[0] = 0.0;
  7229. // normals and binormals : next points
  7230. var prev; // previous vector (segment)
  7231. var cur; // current vector (segment)
  7232. var curTang; // current tangent
  7233. // previous normal
  7234. var prevBinor; // previous binormal
  7235. for (var i = 1; i < l; i++) {
  7236. // tangents
  7237. prev = this._getLastNonNullVector(i);
  7238. if (i < l - 1) {
  7239. cur = this._getFirstNonNullVector(i);
  7240. this._tangents[i] = prev.add(cur);
  7241. this._tangents[i].normalize();
  7242. }
  7243. this._distances[i] = this._distances[i - 1] + prev.length();
  7244. // normals and binormals
  7245. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7246. curTang = this._tangents[i];
  7247. prevBinor = this._binormals[i - 1];
  7248. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7249. if (!this._raw) {
  7250. this._normals[i].normalize();
  7251. }
  7252. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7253. if (!this._raw) {
  7254. this._binormals[i].normalize();
  7255. }
  7256. }
  7257. };
  7258. // private function getFirstNonNullVector(index)
  7259. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7260. Path3D.prototype._getFirstNonNullVector = function (index) {
  7261. var i = 1;
  7262. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7263. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7264. i++;
  7265. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7266. }
  7267. return nNVector;
  7268. };
  7269. // private function getLastNonNullVector(index)
  7270. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7271. Path3D.prototype._getLastNonNullVector = function (index) {
  7272. var i = 1;
  7273. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7274. while (nLVector.length() === 0 && index > i + 1) {
  7275. i++;
  7276. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7277. }
  7278. return nLVector;
  7279. };
  7280. // private function normalVector(v0, vt, va) :
  7281. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7282. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7283. Path3D.prototype._normalVector = function (v0, vt, va) {
  7284. var normal0;
  7285. var tgl = vt.length();
  7286. if (tgl === 0.0) {
  7287. tgl = 1.0;
  7288. }
  7289. if (va === undefined || va === null) {
  7290. var point;
  7291. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7292. point = new Vector3(0.0, -1.0, 0.0);
  7293. }
  7294. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7295. point = new Vector3(1.0, 0.0, 0.0);
  7296. }
  7297. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7298. point = new Vector3(0.0, 0.0, 1.0);
  7299. }
  7300. else {
  7301. point = Vector3.Zero();
  7302. }
  7303. normal0 = Vector3.Cross(vt, point);
  7304. }
  7305. else {
  7306. normal0 = Vector3.Cross(vt, va);
  7307. Vector3.CrossToRef(normal0, vt, normal0);
  7308. }
  7309. normal0.normalize();
  7310. return normal0;
  7311. };
  7312. return Path3D;
  7313. }());
  7314. BABYLON.Path3D = Path3D;
  7315. var Curve3 = /** @class */ (function () {
  7316. /**
  7317. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7318. * A Curve3 is designed from a series of successive Vector3.
  7319. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7320. */
  7321. function Curve3(points) {
  7322. this._length = 0.0;
  7323. this._points = points;
  7324. this._length = this._computeLength(points);
  7325. }
  7326. /**
  7327. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7328. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7329. * @param v1 (Vector3) the control point
  7330. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7331. * @param nbPoints (integer) the wanted number of points in the curve
  7332. */
  7333. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7334. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7335. var bez = new Array();
  7336. var equation = function (t, val0, val1, val2) {
  7337. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7338. return res;
  7339. };
  7340. for (var i = 0; i <= nbPoints; i++) {
  7341. 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)));
  7342. }
  7343. return new Curve3(bez);
  7344. };
  7345. /**
  7346. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7347. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7348. * @param v1 (Vector3) the first control point
  7349. * @param v2 (Vector3) the second control point
  7350. * @param v3 (Vector3) the end point of the Cubic Bezier
  7351. * @param nbPoints (integer) the wanted number of points in the curve
  7352. */
  7353. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7354. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7355. var bez = new Array();
  7356. var equation = function (t, val0, val1, val2, val3) {
  7357. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  7358. return res;
  7359. };
  7360. for (var i = 0; i <= nbPoints; i++) {
  7361. 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)));
  7362. }
  7363. return new Curve3(bez);
  7364. };
  7365. /**
  7366. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7367. * @param p1 (Vector3) the origin point of the Hermite Spline
  7368. * @param t1 (Vector3) the tangent vector at the origin point
  7369. * @param p2 (Vector3) the end point of the Hermite Spline
  7370. * @param t2 (Vector3) the tangent vector at the end point
  7371. * @param nbPoints (integer) the wanted number of points in the curve
  7372. */
  7373. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7374. var hermite = new Array();
  7375. var step = 1.0 / nbPoints;
  7376. for (var i = 0; i <= nbPoints; i++) {
  7377. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7378. }
  7379. return new Curve3(hermite);
  7380. };
  7381. /**
  7382. * Returns a Curve3 object along a CatmullRom Spline curve :
  7383. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7384. * @param nbPoints (integer) the wanted number of points between each curve control points
  7385. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7386. */
  7387. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7388. var catmullRom = new Array();
  7389. var step = 1.0 / nbPoints;
  7390. var amount = 0.0;
  7391. if (closed) {
  7392. var pointsCount = points.length;
  7393. for (var i = 0; i < pointsCount; i++) {
  7394. amount = 0;
  7395. for (var c = 0; c < nbPoints; c++) {
  7396. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7397. amount += step;
  7398. }
  7399. }
  7400. catmullRom.push(catmullRom[0]);
  7401. }
  7402. else {
  7403. var totalPoints = new Array();
  7404. totalPoints.push(points[0].clone());
  7405. Array.prototype.push.apply(totalPoints, points);
  7406. totalPoints.push(points[points.length - 1].clone());
  7407. for (var i = 0; i < totalPoints.length - 3; i++) {
  7408. amount = 0;
  7409. for (var c = 0; c < nbPoints; c++) {
  7410. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7411. amount += step;
  7412. }
  7413. }
  7414. i--;
  7415. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7416. }
  7417. return new Curve3(catmullRom);
  7418. };
  7419. /**
  7420. * Returns the Curve3 stored array of successive Vector3
  7421. */
  7422. Curve3.prototype.getPoints = function () {
  7423. return this._points;
  7424. };
  7425. /**
  7426. * Returns the computed length (float) of the curve.
  7427. */
  7428. Curve3.prototype.length = function () {
  7429. return this._length;
  7430. };
  7431. /**
  7432. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7433. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7434. * curveA and curveB keep unchanged.
  7435. */
  7436. Curve3.prototype.continue = function (curve) {
  7437. var lastPoint = this._points[this._points.length - 1];
  7438. var continuedPoints = this._points.slice();
  7439. var curvePoints = curve.getPoints();
  7440. for (var i = 1; i < curvePoints.length; i++) {
  7441. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7442. }
  7443. var continuedCurve = new Curve3(continuedPoints);
  7444. return continuedCurve;
  7445. };
  7446. Curve3.prototype._computeLength = function (path) {
  7447. var l = 0;
  7448. for (var i = 1; i < path.length; i++) {
  7449. l += (path[i].subtract(path[i - 1])).length();
  7450. }
  7451. return l;
  7452. };
  7453. return Curve3;
  7454. }());
  7455. BABYLON.Curve3 = Curve3;
  7456. // Vertex formats
  7457. var PositionNormalVertex = /** @class */ (function () {
  7458. function PositionNormalVertex(position, normal) {
  7459. if (position === void 0) { position = Vector3.Zero(); }
  7460. if (normal === void 0) { normal = Vector3.Up(); }
  7461. this.position = position;
  7462. this.normal = normal;
  7463. }
  7464. PositionNormalVertex.prototype.clone = function () {
  7465. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7466. };
  7467. return PositionNormalVertex;
  7468. }());
  7469. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7470. var PositionNormalTextureVertex = /** @class */ (function () {
  7471. function PositionNormalTextureVertex(position, normal, uv) {
  7472. if (position === void 0) { position = Vector3.Zero(); }
  7473. if (normal === void 0) { normal = Vector3.Up(); }
  7474. if (uv === void 0) { uv = Vector2.Zero(); }
  7475. this.position = position;
  7476. this.normal = normal;
  7477. this.uv = uv;
  7478. }
  7479. PositionNormalTextureVertex.prototype.clone = function () {
  7480. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7481. };
  7482. return PositionNormalTextureVertex;
  7483. }());
  7484. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7485. // Temporary pre-allocated objects for engine internal use
  7486. // usage in any internal function :
  7487. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7488. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7489. var Tmp = /** @class */ (function () {
  7490. function Tmp() {
  7491. }
  7492. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7493. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7494. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7495. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7496. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7497. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7498. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7499. Matrix.Zero(), Matrix.Zero(),
  7500. Matrix.Zero(), Matrix.Zero(),
  7501. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7502. return Tmp;
  7503. }());
  7504. BABYLON.Tmp = Tmp;
  7505. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7506. var MathTmp = /** @class */ (function () {
  7507. function MathTmp() {
  7508. }
  7509. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7510. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7511. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7512. return MathTmp;
  7513. }());
  7514. })(BABYLON || (BABYLON = {}));
  7515. //# sourceMappingURL=babylon.math.js.map
  7516. var BABYLON;
  7517. (function (BABYLON) {
  7518. var Scalar = /** @class */ (function () {
  7519. function Scalar() {
  7520. }
  7521. /**
  7522. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7523. */
  7524. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7525. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7526. var num = a - b;
  7527. return -epsilon <= num && num <= epsilon;
  7528. };
  7529. /**
  7530. * Returns a string : the upper case translation of the number i to hexadecimal.
  7531. */
  7532. Scalar.ToHex = function (i) {
  7533. var str = i.toString(16);
  7534. if (i <= 15) {
  7535. return ("0" + str).toUpperCase();
  7536. }
  7537. return str.toUpperCase();
  7538. };
  7539. /**
  7540. * Returns -1 if value is negative and +1 is value is positive.
  7541. * Returns the value itself if it's equal to zero.
  7542. */
  7543. Scalar.Sign = function (value) {
  7544. value = +value; // convert to a number
  7545. if (value === 0 || isNaN(value))
  7546. return value;
  7547. return value > 0 ? 1 : -1;
  7548. };
  7549. /**
  7550. * Returns the value itself if it's between min and max.
  7551. * Returns min if the value is lower than min.
  7552. * Returns max if the value is greater than max.
  7553. */
  7554. Scalar.Clamp = function (value, min, max) {
  7555. if (min === void 0) { min = 0; }
  7556. if (max === void 0) { max = 1; }
  7557. return Math.min(max, Math.max(min, value));
  7558. };
  7559. /**
  7560. * Returns the log2 of value.
  7561. */
  7562. Scalar.Log2 = function (value) {
  7563. return Math.log(value) * Math.LOG2E;
  7564. };
  7565. /**
  7566. * Loops the value, so that it is never larger than length and never smaller than 0.
  7567. *
  7568. * This is similar to the modulo operator but it works with floating point numbers.
  7569. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7570. * With t = 5 and length = 2.5, the result would be 0.0.
  7571. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7572. */
  7573. Scalar.Repeat = function (value, length) {
  7574. return value - Math.floor(value / length) * length;
  7575. };
  7576. /**
  7577. * Normalize the value between 0.0 and 1.0 using min and max values
  7578. */
  7579. Scalar.Normalize = function (value, min, max) {
  7580. return (value - min) / (max - min);
  7581. };
  7582. /**
  7583. * Denormalize the value from 0.0 and 1.0 using min and max values
  7584. */
  7585. Scalar.Denormalize = function (normalized, min, max) {
  7586. return (normalized * (max - min) + min);
  7587. };
  7588. /**
  7589. * Calculates the shortest difference between two given angles given in degrees.
  7590. */
  7591. Scalar.DeltaAngle = function (current, target) {
  7592. var num = Scalar.Repeat(target - current, 360.0);
  7593. if (num > 180.0) {
  7594. num -= 360.0;
  7595. }
  7596. return num;
  7597. };
  7598. /**
  7599. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7600. *
  7601. * The returned value will move back and forth between 0 and length
  7602. */
  7603. Scalar.PingPong = function (tx, length) {
  7604. var t = Scalar.Repeat(tx, length * 2.0);
  7605. return length - Math.abs(t - length);
  7606. };
  7607. /**
  7608. * Interpolates between min and max with smoothing at the limits.
  7609. *
  7610. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7611. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7612. */
  7613. Scalar.SmoothStep = function (from, to, tx) {
  7614. var t = Scalar.Clamp(tx);
  7615. t = -2.0 * t * t * t + 3.0 * t * t;
  7616. return to * t + from * (1.0 - t);
  7617. };
  7618. /**
  7619. * Moves a value current towards target.
  7620. *
  7621. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7622. * Negative values of maxDelta pushes the value away from target.
  7623. */
  7624. Scalar.MoveTowards = function (current, target, maxDelta) {
  7625. var result = 0;
  7626. if (Math.abs(target - current) <= maxDelta) {
  7627. result = target;
  7628. }
  7629. else {
  7630. result = current + Scalar.Sign(target - current) * maxDelta;
  7631. }
  7632. return result;
  7633. };
  7634. /**
  7635. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7636. *
  7637. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7638. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7639. */
  7640. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7641. var num = Scalar.DeltaAngle(current, target);
  7642. var result = 0;
  7643. if (-maxDelta < num && num < maxDelta) {
  7644. result = target;
  7645. }
  7646. else {
  7647. target = current + num;
  7648. result = Scalar.MoveTowards(current, target, maxDelta);
  7649. }
  7650. return result;
  7651. };
  7652. /**
  7653. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7654. */
  7655. Scalar.Lerp = function (start, end, amount) {
  7656. return start + ((end - start) * amount);
  7657. };
  7658. /**
  7659. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7660. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7661. */
  7662. Scalar.LerpAngle = function (start, end, amount) {
  7663. var num = Scalar.Repeat(end - start, 360.0);
  7664. if (num > 180.0) {
  7665. num -= 360.0;
  7666. }
  7667. return start + num * Scalar.Clamp(amount);
  7668. };
  7669. /**
  7670. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7671. */
  7672. Scalar.InverseLerp = function (a, b, value) {
  7673. var result = 0;
  7674. if (a != b) {
  7675. result = Scalar.Clamp((value - a) / (b - a));
  7676. }
  7677. else {
  7678. result = 0.0;
  7679. }
  7680. return result;
  7681. };
  7682. /**
  7683. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7684. */
  7685. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7686. var squared = amount * amount;
  7687. var cubed = amount * squared;
  7688. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7689. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7690. var part3 = (cubed - (2.0 * squared)) + amount;
  7691. var part4 = cubed - squared;
  7692. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7693. };
  7694. /**
  7695. * Returns a random float number between and min and max values
  7696. */
  7697. Scalar.RandomRange = function (min, max) {
  7698. if (min === max)
  7699. return min;
  7700. return ((Math.random() * (max - min)) + min);
  7701. };
  7702. /**
  7703. * This function returns percentage of a number in a given range.
  7704. *
  7705. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7706. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7707. */
  7708. Scalar.RangeToPercent = function (number, min, max) {
  7709. return ((number - min) / (max - min));
  7710. };
  7711. /**
  7712. * This function returns number that corresponds to the percentage in a given range.
  7713. *
  7714. * PercentToRange(0.34,0,100) will return 34.
  7715. */
  7716. Scalar.PercentToRange = function (percent, min, max) {
  7717. return ((max - min) * percent + min);
  7718. };
  7719. /**
  7720. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7721. * @param angle The angle to normalize in radian.
  7722. * @return The converted angle.
  7723. */
  7724. Scalar.NormalizeRadians = function (angle) {
  7725. // More precise but slower version kept for reference.
  7726. // angle = angle % Tools.TwoPi;
  7727. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7728. //if (angle > Math.PI) {
  7729. // angle -= Tools.TwoPi;
  7730. //}
  7731. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7732. return angle;
  7733. };
  7734. /**
  7735. * Two pi constants convenient for computation.
  7736. */
  7737. Scalar.TwoPi = Math.PI * 2;
  7738. return Scalar;
  7739. }());
  7740. BABYLON.Scalar = Scalar;
  7741. })(BABYLON || (BABYLON = {}));
  7742. //# sourceMappingURL=babylon.math.scalar.js.map
  7743. //# sourceMappingURL=babylon.mixins.js.map
  7744. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7745. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7746. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7747. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7748. //# sourceMappingURL=babylon.webgl2.js.map
  7749. var BABYLON;
  7750. (function (BABYLON) {
  7751. var __decoratorInitialStore = {};
  7752. var __mergedStore = {};
  7753. var _copySource = function (creationFunction, source, instanciate) {
  7754. var destination = creationFunction();
  7755. // Tags
  7756. if (BABYLON.Tags) {
  7757. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7758. }
  7759. var classStore = getMergedStore(destination);
  7760. // Properties
  7761. for (var property in classStore) {
  7762. var propertyDescriptor = classStore[property];
  7763. var sourceProperty = source[property];
  7764. var propertyType = propertyDescriptor.type;
  7765. if (sourceProperty !== undefined && sourceProperty !== null) {
  7766. switch (propertyType) {
  7767. case 0: // Value
  7768. case 6: // Mesh reference
  7769. case 11: // Camera reference
  7770. destination[property] = sourceProperty;
  7771. break;
  7772. case 1: // Texture
  7773. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7774. break;
  7775. case 2: // Color3
  7776. case 3: // FresnelParameters
  7777. case 4: // Vector2
  7778. case 5: // Vector3
  7779. case 7: // Color Curves
  7780. case 10: // Quaternion
  7781. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7782. break;
  7783. }
  7784. }
  7785. }
  7786. return destination;
  7787. };
  7788. function getDirectStore(target) {
  7789. var classKey = target.getClassName();
  7790. if (!__decoratorInitialStore[classKey]) {
  7791. __decoratorInitialStore[classKey] = {};
  7792. }
  7793. return __decoratorInitialStore[classKey];
  7794. }
  7795. /**
  7796. * Return the list of properties flagged as serializable
  7797. * @param target: host object
  7798. */
  7799. function getMergedStore(target) {
  7800. var classKey = target.getClassName();
  7801. if (__mergedStore[classKey]) {
  7802. return __mergedStore[classKey];
  7803. }
  7804. __mergedStore[classKey] = {};
  7805. var store = __mergedStore[classKey];
  7806. var currentTarget = target;
  7807. var currentKey = classKey;
  7808. while (currentKey) {
  7809. var initialStore = __decoratorInitialStore[currentKey];
  7810. for (var property in initialStore) {
  7811. store[property] = initialStore[property];
  7812. }
  7813. var parent_1 = void 0;
  7814. var done = false;
  7815. do {
  7816. parent_1 = Object.getPrototypeOf(currentTarget);
  7817. if (!parent_1.getClassName) {
  7818. done = true;
  7819. break;
  7820. }
  7821. if (parent_1.getClassName() !== currentKey) {
  7822. break;
  7823. }
  7824. currentTarget = parent_1;
  7825. } while (parent_1);
  7826. if (done) {
  7827. break;
  7828. }
  7829. currentKey = parent_1.getClassName();
  7830. currentTarget = parent_1;
  7831. }
  7832. return store;
  7833. }
  7834. function generateSerializableMember(type, sourceName) {
  7835. return function (target, propertyKey) {
  7836. var classStore = getDirectStore(target);
  7837. if (!classStore[propertyKey]) {
  7838. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7839. }
  7840. };
  7841. }
  7842. function generateExpandMember(setCallback, targetKey) {
  7843. if (targetKey === void 0) { targetKey = null; }
  7844. return function (target, propertyKey) {
  7845. var key = targetKey || ("_" + propertyKey);
  7846. Object.defineProperty(target, propertyKey, {
  7847. get: function () {
  7848. return this[key];
  7849. },
  7850. set: function (value) {
  7851. if (this[key] === value) {
  7852. return;
  7853. }
  7854. this[key] = value;
  7855. target[setCallback].apply(this);
  7856. },
  7857. enumerable: true,
  7858. configurable: true
  7859. });
  7860. };
  7861. }
  7862. function expandToProperty(callback, targetKey) {
  7863. if (targetKey === void 0) { targetKey = null; }
  7864. return generateExpandMember(callback, targetKey);
  7865. }
  7866. BABYLON.expandToProperty = expandToProperty;
  7867. function serialize(sourceName) {
  7868. return generateSerializableMember(0, sourceName); // value member
  7869. }
  7870. BABYLON.serialize = serialize;
  7871. function serializeAsTexture(sourceName) {
  7872. return generateSerializableMember(1, sourceName); // texture member
  7873. }
  7874. BABYLON.serializeAsTexture = serializeAsTexture;
  7875. function serializeAsColor3(sourceName) {
  7876. return generateSerializableMember(2, sourceName); // color3 member
  7877. }
  7878. BABYLON.serializeAsColor3 = serializeAsColor3;
  7879. function serializeAsFresnelParameters(sourceName) {
  7880. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7881. }
  7882. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7883. function serializeAsVector2(sourceName) {
  7884. return generateSerializableMember(4, sourceName); // vector2 member
  7885. }
  7886. BABYLON.serializeAsVector2 = serializeAsVector2;
  7887. function serializeAsVector3(sourceName) {
  7888. return generateSerializableMember(5, sourceName); // vector3 member
  7889. }
  7890. BABYLON.serializeAsVector3 = serializeAsVector3;
  7891. function serializeAsMeshReference(sourceName) {
  7892. return generateSerializableMember(6, sourceName); // mesh reference member
  7893. }
  7894. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7895. function serializeAsColorCurves(sourceName) {
  7896. return generateSerializableMember(7, sourceName); // color curves
  7897. }
  7898. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7899. function serializeAsColor4(sourceName) {
  7900. return generateSerializableMember(8, sourceName); // color 4
  7901. }
  7902. BABYLON.serializeAsColor4 = serializeAsColor4;
  7903. function serializeAsImageProcessingConfiguration(sourceName) {
  7904. return generateSerializableMember(9, sourceName); // image processing
  7905. }
  7906. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7907. function serializeAsQuaternion(sourceName) {
  7908. return generateSerializableMember(10, sourceName); // quaternion member
  7909. }
  7910. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7911. /**
  7912. * Decorator used to define property that can be serialized as reference to a camera
  7913. * @param sourceName defines the name of the property to decorate
  7914. */
  7915. function serializeAsCameraReference(sourceName) {
  7916. return generateSerializableMember(11, sourceName); // camera reference member
  7917. }
  7918. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7919. var SerializationHelper = /** @class */ (function () {
  7920. function SerializationHelper() {
  7921. }
  7922. SerializationHelper.Serialize = function (entity, serializationObject) {
  7923. if (!serializationObject) {
  7924. serializationObject = {};
  7925. }
  7926. // Tags
  7927. if (BABYLON.Tags) {
  7928. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7929. }
  7930. var serializedProperties = getMergedStore(entity);
  7931. // Properties
  7932. for (var property in serializedProperties) {
  7933. var propertyDescriptor = serializedProperties[property];
  7934. var targetPropertyName = propertyDescriptor.sourceName || property;
  7935. var propertyType = propertyDescriptor.type;
  7936. var sourceProperty = entity[property];
  7937. if (sourceProperty !== undefined && sourceProperty !== null) {
  7938. switch (propertyType) {
  7939. case 0: // Value
  7940. serializationObject[targetPropertyName] = sourceProperty;
  7941. break;
  7942. case 1: // Texture
  7943. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7944. break;
  7945. case 2: // Color3
  7946. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7947. break;
  7948. case 3: // FresnelParameters
  7949. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7950. break;
  7951. case 4: // Vector2
  7952. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7953. break;
  7954. case 5: // Vector3
  7955. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7956. break;
  7957. case 6: // Mesh reference
  7958. serializationObject[targetPropertyName] = sourceProperty.id;
  7959. break;
  7960. case 7: // Color Curves
  7961. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7962. break;
  7963. case 8: // Color 4
  7964. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7965. break;
  7966. case 9: // Image Processing
  7967. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7968. break;
  7969. case 10: // Quaternion
  7970. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7971. break;
  7972. case 11: // Camera reference
  7973. serializationObject[targetPropertyName] = sourceProperty.id;
  7974. break;
  7975. }
  7976. }
  7977. }
  7978. return serializationObject;
  7979. };
  7980. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7981. if (rootUrl === void 0) { rootUrl = null; }
  7982. var destination = creationFunction();
  7983. if (!rootUrl) {
  7984. rootUrl = "";
  7985. }
  7986. // Tags
  7987. if (BABYLON.Tags) {
  7988. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7989. }
  7990. var classStore = getMergedStore(destination);
  7991. // Properties
  7992. for (var property in classStore) {
  7993. var propertyDescriptor = classStore[property];
  7994. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7995. var propertyType = propertyDescriptor.type;
  7996. if (sourceProperty !== undefined && sourceProperty !== null) {
  7997. var dest = destination;
  7998. switch (propertyType) {
  7999. case 0: // Value
  8000. dest[property] = sourceProperty;
  8001. break;
  8002. case 1: // Texture
  8003. if (scene) {
  8004. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8005. }
  8006. break;
  8007. case 2: // Color3
  8008. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8009. break;
  8010. case 3: // FresnelParameters
  8011. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8012. break;
  8013. case 4: // Vector2
  8014. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8015. break;
  8016. case 5: // Vector3
  8017. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8018. break;
  8019. case 6: // Mesh reference
  8020. if (scene) {
  8021. dest[property] = scene.getLastMeshByID(sourceProperty);
  8022. }
  8023. break;
  8024. case 7: // Color Curves
  8025. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8026. break;
  8027. case 8: // Color 4
  8028. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8029. break;
  8030. case 9: // Image Processing
  8031. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8032. break;
  8033. case 10: // Quaternion
  8034. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8035. break;
  8036. case 11: // Camera reference
  8037. if (scene) {
  8038. dest[property] = scene.getCameraByID(sourceProperty);
  8039. }
  8040. break;
  8041. }
  8042. }
  8043. }
  8044. return destination;
  8045. };
  8046. SerializationHelper.Clone = function (creationFunction, source) {
  8047. return _copySource(creationFunction, source, false);
  8048. };
  8049. SerializationHelper.Instanciate = function (creationFunction, source) {
  8050. return _copySource(creationFunction, source, true);
  8051. };
  8052. return SerializationHelper;
  8053. }());
  8054. BABYLON.SerializationHelper = SerializationHelper;
  8055. })(BABYLON || (BABYLON = {}));
  8056. //# sourceMappingURL=babylon.decorators.js.map
  8057. var BABYLON;
  8058. (function (BABYLON) {
  8059. /**
  8060. * Wrapper class for promise with external resolve and reject.
  8061. */
  8062. var Deferred = /** @class */ (function () {
  8063. /**
  8064. * Constructor for this deferred object.
  8065. */
  8066. function Deferred() {
  8067. var _this = this;
  8068. this.promise = new Promise(function (resolve, reject) {
  8069. _this._resolve = resolve;
  8070. _this._reject = reject;
  8071. });
  8072. }
  8073. Object.defineProperty(Deferred.prototype, "resolve", {
  8074. /**
  8075. * The resolve method of the promise associated with this deferred object.
  8076. */
  8077. get: function () {
  8078. return this._resolve;
  8079. },
  8080. enumerable: true,
  8081. configurable: true
  8082. });
  8083. Object.defineProperty(Deferred.prototype, "reject", {
  8084. /**
  8085. * The reject method of the promise associated with this deferred object.
  8086. */
  8087. get: function () {
  8088. return this._reject;
  8089. },
  8090. enumerable: true,
  8091. configurable: true
  8092. });
  8093. return Deferred;
  8094. }());
  8095. BABYLON.Deferred = Deferred;
  8096. })(BABYLON || (BABYLON = {}));
  8097. //# sourceMappingURL=babylon.deferred.js.map
  8098. var BABYLON;
  8099. (function (BABYLON) {
  8100. /**
  8101. * A class serves as a medium between the observable and its observers
  8102. */
  8103. var EventState = /** @class */ (function () {
  8104. /**
  8105. * Create a new EventState
  8106. * @param mask defines the mask associated with this state
  8107. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8108. * @param target defines the original target of the state
  8109. * @param currentTarget defines the current target of the state
  8110. */
  8111. function EventState(mask, skipNextObservers, target, currentTarget) {
  8112. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8113. this.initalize(mask, skipNextObservers, target, currentTarget);
  8114. }
  8115. /**
  8116. * Initialize the current event state
  8117. * @param mask defines the mask associated with this state
  8118. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8119. * @param target defines the original target of the state
  8120. * @param currentTarget defines the current target of the state
  8121. * @returns the current event state
  8122. */
  8123. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8124. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8125. this.mask = mask;
  8126. this.skipNextObservers = skipNextObservers;
  8127. this.target = target;
  8128. this.currentTarget = currentTarget;
  8129. return this;
  8130. };
  8131. return EventState;
  8132. }());
  8133. BABYLON.EventState = EventState;
  8134. /**
  8135. * Represent an Observer registered to a given Observable object.
  8136. */
  8137. var Observer = /** @class */ (function () {
  8138. /**
  8139. * Creates a new observer
  8140. * @param callback defines the callback to call when the observer is notified
  8141. * @param mask defines the mask of the observer (used to filter notifications)
  8142. * @param scope defines the current scope used to restore the JS context
  8143. */
  8144. function Observer(
  8145. /**
  8146. * Defines the callback to call when the observer is notified
  8147. */
  8148. callback,
  8149. /**
  8150. * Defines the mask of the observer (used to filter notifications)
  8151. */
  8152. mask,
  8153. /**
  8154. * Defines the current scope used to restore the JS context
  8155. */
  8156. scope) {
  8157. if (scope === void 0) { scope = null; }
  8158. this.callback = callback;
  8159. this.mask = mask;
  8160. this.scope = scope;
  8161. /** @hidden */
  8162. this._willBeUnregistered = false;
  8163. /**
  8164. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8165. */
  8166. this.unregisterOnNextCall = false;
  8167. }
  8168. return Observer;
  8169. }());
  8170. BABYLON.Observer = Observer;
  8171. /**
  8172. * Represent a list of observers registered to multiple Observables object.
  8173. */
  8174. var MultiObserver = /** @class */ (function () {
  8175. function MultiObserver() {
  8176. }
  8177. /**
  8178. * Release associated resources
  8179. */
  8180. MultiObserver.prototype.dispose = function () {
  8181. if (this._observers && this._observables) {
  8182. for (var index = 0; index < this._observers.length; index++) {
  8183. this._observables[index].remove(this._observers[index]);
  8184. }
  8185. }
  8186. this._observers = null;
  8187. this._observables = null;
  8188. };
  8189. /**
  8190. * Raise a callback when one of the observable will notify
  8191. * @param observables defines a list of observables to watch
  8192. * @param callback defines the callback to call on notification
  8193. * @param mask defines the mask used to filter notifications
  8194. * @param scope defines the current scope used to restore the JS context
  8195. * @returns the new MultiObserver
  8196. */
  8197. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8198. if (mask === void 0) { mask = -1; }
  8199. if (scope === void 0) { scope = null; }
  8200. var result = new MultiObserver();
  8201. result._observers = new Array();
  8202. result._observables = observables;
  8203. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8204. var observable = observables_1[_i];
  8205. var observer = observable.add(callback, mask, false, scope);
  8206. if (observer) {
  8207. result._observers.push(observer);
  8208. }
  8209. }
  8210. return result;
  8211. };
  8212. return MultiObserver;
  8213. }());
  8214. BABYLON.MultiObserver = MultiObserver;
  8215. /**
  8216. * The Observable class is a simple implementation of the Observable pattern.
  8217. *
  8218. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  8219. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8220. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  8221. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  8222. */
  8223. var Observable = /** @class */ (function () {
  8224. /**
  8225. * Creates a new observable
  8226. * @param onObserverAdded defines a callback to call when a new observer is added
  8227. */
  8228. function Observable(onObserverAdded) {
  8229. this._observers = new Array();
  8230. this._eventState = new EventState(0);
  8231. if (onObserverAdded) {
  8232. this._onObserverAdded = onObserverAdded;
  8233. }
  8234. }
  8235. /**
  8236. * Create a new Observer with the specified callback
  8237. * @param callback the callback that will be executed for that Observer
  8238. * @param mask the mask used to filter observers
  8239. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  8240. * @param scope optional scope for the callback to be called from
  8241. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8242. * @returns the new observer created for the callback
  8243. */
  8244. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8245. if (mask === void 0) { mask = -1; }
  8246. if (insertFirst === void 0) { insertFirst = false; }
  8247. if (scope === void 0) { scope = null; }
  8248. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8249. if (!callback) {
  8250. return null;
  8251. }
  8252. var observer = new Observer(callback, mask, scope);
  8253. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8254. if (insertFirst) {
  8255. this._observers.unshift(observer);
  8256. }
  8257. else {
  8258. this._observers.push(observer);
  8259. }
  8260. if (this._onObserverAdded) {
  8261. this._onObserverAdded(observer);
  8262. }
  8263. return observer;
  8264. };
  8265. /**
  8266. * Create a new Observer with the specified callback and unregisters after the next notification
  8267. * @param callback the callback that will be executed for that Observer
  8268. * @returns the new observer created for the callback
  8269. */
  8270. Observable.prototype.addOnce = function (callback) {
  8271. return this.add(callback, undefined, undefined, undefined, true);
  8272. };
  8273. /**
  8274. * Remove an Observer from the Observable object
  8275. * @param observer the instance of the Observer to remove
  8276. * @returns false if it doesn't belong to this Observable
  8277. */
  8278. Observable.prototype.remove = function (observer) {
  8279. if (!observer) {
  8280. return false;
  8281. }
  8282. var index = this._observers.indexOf(observer);
  8283. if (index !== -1) {
  8284. this._observers.splice(index, 1);
  8285. return true;
  8286. }
  8287. return false;
  8288. };
  8289. /**
  8290. * Remove a callback from the Observable object
  8291. * @param callback the callback to remove
  8292. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8293. * @returns false if it doesn't belong to this Observable
  8294. */
  8295. Observable.prototype.removeCallback = function (callback, scope) {
  8296. for (var index = 0; index < this._observers.length; index++) {
  8297. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8298. this._observers.splice(index, 1);
  8299. return true;
  8300. }
  8301. }
  8302. return false;
  8303. };
  8304. Observable.prototype._deferUnregister = function (observer) {
  8305. var _this = this;
  8306. observer.unregisterOnNextCall = false;
  8307. observer._willBeUnregistered = true;
  8308. BABYLON.Tools.SetImmediate(function () {
  8309. _this.remove(observer);
  8310. });
  8311. };
  8312. /**
  8313. * Notify all Observers by calling their respective callback with the given data
  8314. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8315. * @param eventData defines the data to send to all observers
  8316. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8317. * @param target defines the original target of the state
  8318. * @param currentTarget defines the current target of the state
  8319. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8320. */
  8321. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8322. if (mask === void 0) { mask = -1; }
  8323. if (!this._observers.length) {
  8324. return true;
  8325. }
  8326. var state = this._eventState;
  8327. state.mask = mask;
  8328. state.target = target;
  8329. state.currentTarget = currentTarget;
  8330. state.skipNextObservers = false;
  8331. state.lastReturnValue = eventData;
  8332. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8333. var obs = _a[_i];
  8334. if (obs._willBeUnregistered) {
  8335. continue;
  8336. }
  8337. if (obs.mask & mask) {
  8338. if (obs.scope) {
  8339. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8340. }
  8341. else {
  8342. state.lastReturnValue = obs.callback(eventData, state);
  8343. }
  8344. if (obs.unregisterOnNextCall) {
  8345. this._deferUnregister(obs);
  8346. }
  8347. }
  8348. if (state.skipNextObservers) {
  8349. return false;
  8350. }
  8351. }
  8352. return true;
  8353. };
  8354. /**
  8355. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8356. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8357. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8358. * and it is crucial that all callbacks will be executed.
  8359. * The order of the callbacks is kept, callbacks are not executed parallel.
  8360. *
  8361. * @param eventData The data to be sent to each callback
  8362. * @param mask is used to filter observers defaults to -1
  8363. * @param target defines the callback target (see EventState)
  8364. * @param currentTarget defines he current object in the bubbling phase
  8365. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8366. */
  8367. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8368. var _this = this;
  8369. if (mask === void 0) { mask = -1; }
  8370. // create an empty promise
  8371. var p = Promise.resolve(eventData);
  8372. // no observers? return this promise.
  8373. if (!this._observers.length) {
  8374. return p;
  8375. }
  8376. var state = this._eventState;
  8377. state.mask = mask;
  8378. state.target = target;
  8379. state.currentTarget = currentTarget;
  8380. state.skipNextObservers = false;
  8381. // execute one callback after another (not using Promise.all, the order is important)
  8382. this._observers.forEach(function (obs) {
  8383. if (state.skipNextObservers) {
  8384. return;
  8385. }
  8386. if (obs._willBeUnregistered) {
  8387. return;
  8388. }
  8389. if (obs.mask & mask) {
  8390. if (obs.scope) {
  8391. p = p.then(function (lastReturnedValue) {
  8392. state.lastReturnValue = lastReturnedValue;
  8393. return obs.callback.apply(obs.scope, [eventData, state]);
  8394. });
  8395. }
  8396. else {
  8397. p = p.then(function (lastReturnedValue) {
  8398. state.lastReturnValue = lastReturnedValue;
  8399. return obs.callback(eventData, state);
  8400. });
  8401. }
  8402. if (obs.unregisterOnNextCall) {
  8403. _this._deferUnregister(obs);
  8404. }
  8405. }
  8406. });
  8407. // return the eventData
  8408. return p.then(function () { return eventData; });
  8409. };
  8410. /**
  8411. * Notify a specific observer
  8412. * @param observer defines the observer to notify
  8413. * @param eventData defines the data to be sent to each callback
  8414. * @param mask is used to filter observers defaults to -1
  8415. */
  8416. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8417. if (mask === void 0) { mask = -1; }
  8418. var state = this._eventState;
  8419. state.mask = mask;
  8420. state.skipNextObservers = false;
  8421. observer.callback(eventData, state);
  8422. };
  8423. /**
  8424. * Gets a boolean indicating if the observable has at least one observer
  8425. * @returns true is the Observable has at least one Observer registered
  8426. */
  8427. Observable.prototype.hasObservers = function () {
  8428. return this._observers.length > 0;
  8429. };
  8430. /**
  8431. * Clear the list of observers
  8432. */
  8433. Observable.prototype.clear = function () {
  8434. this._observers = new Array();
  8435. this._onObserverAdded = null;
  8436. };
  8437. /**
  8438. * Clone the current observable
  8439. * @returns a new observable
  8440. */
  8441. Observable.prototype.clone = function () {
  8442. var result = new Observable();
  8443. result._observers = this._observers.slice(0);
  8444. return result;
  8445. };
  8446. /**
  8447. * Does this observable handles observer registered with a given mask
  8448. * @param mask defines the mask to be tested
  8449. * @return whether or not one observer registered with the given mask is handeled
  8450. **/
  8451. Observable.prototype.hasSpecificMask = function (mask) {
  8452. if (mask === void 0) { mask = -1; }
  8453. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8454. var obs = _a[_i];
  8455. if (obs.mask & mask || obs.mask === mask) {
  8456. return true;
  8457. }
  8458. }
  8459. return false;
  8460. };
  8461. return Observable;
  8462. }());
  8463. BABYLON.Observable = Observable;
  8464. })(BABYLON || (BABYLON = {}));
  8465. //# sourceMappingURL=babylon.observable.js.map
  8466. var BABYLON;
  8467. (function (BABYLON) {
  8468. var SmartArray = /** @class */ (function () {
  8469. function SmartArray(capacity) {
  8470. this.length = 0;
  8471. this.data = new Array(capacity);
  8472. this._id = SmartArray._GlobalId++;
  8473. }
  8474. SmartArray.prototype.push = function (value) {
  8475. this.data[this.length++] = value;
  8476. if (this.length > this.data.length) {
  8477. this.data.length *= 2;
  8478. }
  8479. };
  8480. SmartArray.prototype.forEach = function (func) {
  8481. for (var index = 0; index < this.length; index++) {
  8482. func(this.data[index]);
  8483. }
  8484. };
  8485. SmartArray.prototype.sort = function (compareFn) {
  8486. this.data.sort(compareFn);
  8487. };
  8488. SmartArray.prototype.reset = function () {
  8489. this.length = 0;
  8490. };
  8491. SmartArray.prototype.dispose = function () {
  8492. this.reset();
  8493. if (this.data) {
  8494. this.data.length = 0;
  8495. this.data = [];
  8496. }
  8497. };
  8498. SmartArray.prototype.concat = function (array) {
  8499. if (array.length === 0) {
  8500. return;
  8501. }
  8502. if (this.length + array.length > this.data.length) {
  8503. this.data.length = (this.length + array.length) * 2;
  8504. }
  8505. for (var index = 0; index < array.length; index++) {
  8506. this.data[this.length++] = (array.data || array)[index];
  8507. }
  8508. };
  8509. SmartArray.prototype.indexOf = function (value) {
  8510. var position = this.data.indexOf(value);
  8511. if (position >= this.length) {
  8512. return -1;
  8513. }
  8514. return position;
  8515. };
  8516. SmartArray.prototype.contains = function (value) {
  8517. return this.data.indexOf(value) !== -1;
  8518. };
  8519. // Statics
  8520. SmartArray._GlobalId = 0;
  8521. return SmartArray;
  8522. }());
  8523. BABYLON.SmartArray = SmartArray;
  8524. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8525. __extends(SmartArrayNoDuplicate, _super);
  8526. function SmartArrayNoDuplicate() {
  8527. var _this = _super !== null && _super.apply(this, arguments) || this;
  8528. _this._duplicateId = 0;
  8529. return _this;
  8530. }
  8531. SmartArrayNoDuplicate.prototype.push = function (value) {
  8532. _super.prototype.push.call(this, value);
  8533. if (!value.__smartArrayFlags) {
  8534. value.__smartArrayFlags = {};
  8535. }
  8536. value.__smartArrayFlags[this._id] = this._duplicateId;
  8537. };
  8538. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8539. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8540. return false;
  8541. }
  8542. this.push(value);
  8543. return true;
  8544. };
  8545. SmartArrayNoDuplicate.prototype.reset = function () {
  8546. _super.prototype.reset.call(this);
  8547. this._duplicateId++;
  8548. };
  8549. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8550. if (array.length === 0) {
  8551. return;
  8552. }
  8553. if (this.length + array.length > this.data.length) {
  8554. this.data.length = (this.length + array.length) * 2;
  8555. }
  8556. for (var index = 0; index < array.length; index++) {
  8557. var item = (array.data || array)[index];
  8558. this.pushNoDuplicate(item);
  8559. }
  8560. };
  8561. return SmartArrayNoDuplicate;
  8562. }(SmartArray));
  8563. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8564. })(BABYLON || (BABYLON = {}));
  8565. //# sourceMappingURL=babylon.smartArray.js.map
  8566. var BABYLON;
  8567. (function (BABYLON) {
  8568. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8569. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8570. var LoadFileError = /** @class */ (function (_super) {
  8571. __extends(LoadFileError, _super);
  8572. function LoadFileError(message, request) {
  8573. var _this = _super.call(this, message) || this;
  8574. _this.request = request;
  8575. _this.name = "LoadFileError";
  8576. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8577. return _this;
  8578. }
  8579. // Polyfill for Object.setPrototypeOf if necessary.
  8580. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8581. return LoadFileError;
  8582. }(Error));
  8583. BABYLON.LoadFileError = LoadFileError;
  8584. var RetryStrategy = /** @class */ (function () {
  8585. function RetryStrategy() {
  8586. }
  8587. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8588. if (maxRetries === void 0) { maxRetries = 3; }
  8589. if (baseInterval === void 0) { baseInterval = 500; }
  8590. return function (url, request, retryIndex) {
  8591. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8592. return -1;
  8593. }
  8594. return Math.pow(2, retryIndex) * baseInterval;
  8595. };
  8596. };
  8597. return RetryStrategy;
  8598. }());
  8599. BABYLON.RetryStrategy = RetryStrategy;
  8600. // Screenshots
  8601. var screenshotCanvas;
  8602. var cloneValue = function (source, destinationObject) {
  8603. if (!source)
  8604. return null;
  8605. if (source instanceof BABYLON.Mesh) {
  8606. return null;
  8607. }
  8608. if (source instanceof BABYLON.SubMesh) {
  8609. return source.clone(destinationObject);
  8610. }
  8611. else if (source.clone) {
  8612. return source.clone();
  8613. }
  8614. return null;
  8615. };
  8616. var Tools = /** @class */ (function () {
  8617. function Tools() {
  8618. }
  8619. /**
  8620. * Interpolates between a and b via alpha
  8621. * @param a The lower value (returned when alpha = 0)
  8622. * @param b The upper value (returned when alpha = 1)
  8623. * @param alpha The interpolation-factor
  8624. * @return The mixed value
  8625. */
  8626. Tools.Mix = function (a, b, alpha) {
  8627. return a * (1 - alpha) + b * alpha;
  8628. };
  8629. Tools.Instantiate = function (className) {
  8630. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8631. return Tools.RegisteredExternalClasses[className];
  8632. }
  8633. var arr = className.split(".");
  8634. var fn = (window || this);
  8635. for (var i = 0, len = arr.length; i < len; i++) {
  8636. fn = fn[arr[i]];
  8637. }
  8638. if (typeof fn !== "function") {
  8639. return null;
  8640. }
  8641. return fn;
  8642. };
  8643. /**
  8644. * Provides a slice function that will work even on IE
  8645. * @param data defines the array to slice
  8646. * @param start defines the start of the data (optional)
  8647. * @param end defines the end of the data (optional)
  8648. * @returns the new sliced array
  8649. */
  8650. Tools.Slice = function (data, start, end) {
  8651. if (data.slice) {
  8652. return data.slice(start, end);
  8653. }
  8654. return Array.prototype.slice.call(data, start, end);
  8655. };
  8656. Tools.SetImmediate = function (action) {
  8657. if (window.setImmediate) {
  8658. window.setImmediate(action);
  8659. }
  8660. else {
  8661. setTimeout(action, 1);
  8662. }
  8663. };
  8664. Tools.IsExponentOfTwo = function (value) {
  8665. var count = 1;
  8666. do {
  8667. count *= 2;
  8668. } while (count < value);
  8669. return count === value;
  8670. };
  8671. /**
  8672. * Returns the nearest 32-bit single precision float representation of a Number
  8673. * @param value A Number. If the parameter is of a different type, it will get converted
  8674. * to a number or to NaN if it cannot be converted
  8675. * @returns number
  8676. */
  8677. Tools.FloatRound = function (value) {
  8678. if (Math.fround) {
  8679. return Math.fround(value);
  8680. }
  8681. return (Tools._tmpFloatArray[0] = value);
  8682. };
  8683. /**
  8684. * Find the next highest power of two.
  8685. * @param x Number to start search from.
  8686. * @return Next highest power of two.
  8687. */
  8688. Tools.CeilingPOT = function (x) {
  8689. x--;
  8690. x |= x >> 1;
  8691. x |= x >> 2;
  8692. x |= x >> 4;
  8693. x |= x >> 8;
  8694. x |= x >> 16;
  8695. x++;
  8696. return x;
  8697. };
  8698. /**
  8699. * Find the next lowest power of two.
  8700. * @param x Number to start search from.
  8701. * @return Next lowest power of two.
  8702. */
  8703. Tools.FloorPOT = function (x) {
  8704. x = x | (x >> 1);
  8705. x = x | (x >> 2);
  8706. x = x | (x >> 4);
  8707. x = x | (x >> 8);
  8708. x = x | (x >> 16);
  8709. return x - (x >> 1);
  8710. };
  8711. /**
  8712. * Find the nearest power of two.
  8713. * @param x Number to start search from.
  8714. * @return Next nearest power of two.
  8715. */
  8716. Tools.NearestPOT = function (x) {
  8717. var c = Tools.CeilingPOT(x);
  8718. var f = Tools.FloorPOT(x);
  8719. return (c - x) > (x - f) ? f : c;
  8720. };
  8721. Tools.GetExponentOfTwo = function (value, max, mode) {
  8722. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8723. var pot;
  8724. switch (mode) {
  8725. case BABYLON.Engine.SCALEMODE_FLOOR:
  8726. pot = Tools.FloorPOT(value);
  8727. break;
  8728. case BABYLON.Engine.SCALEMODE_NEAREST:
  8729. pot = Tools.NearestPOT(value);
  8730. break;
  8731. case BABYLON.Engine.SCALEMODE_CEILING:
  8732. default:
  8733. pot = Tools.CeilingPOT(value);
  8734. break;
  8735. }
  8736. return Math.min(pot, max);
  8737. };
  8738. Tools.GetFilename = function (path) {
  8739. var index = path.lastIndexOf("/");
  8740. if (index < 0)
  8741. return path;
  8742. return path.substring(index + 1);
  8743. };
  8744. /**
  8745. * Extracts the "folder" part of a path (everything before the filename).
  8746. * @param uri The URI to extract the info from
  8747. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8748. * @returns The "folder" part of the path
  8749. */
  8750. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8751. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8752. var index = uri.lastIndexOf("/");
  8753. if (index < 0) {
  8754. if (returnUnchangedIfNoSlash) {
  8755. return uri;
  8756. }
  8757. return "";
  8758. }
  8759. return uri.substring(0, index + 1);
  8760. };
  8761. Tools.GetDOMTextContent = function (element) {
  8762. var result = "";
  8763. var child = element.firstChild;
  8764. while (child) {
  8765. if (child.nodeType === 3) {
  8766. result += child.textContent;
  8767. }
  8768. child = child.nextSibling;
  8769. }
  8770. return result;
  8771. };
  8772. Tools.ToDegrees = function (angle) {
  8773. return angle * 180 / Math.PI;
  8774. };
  8775. Tools.ToRadians = function (angle) {
  8776. return angle * Math.PI / 180;
  8777. };
  8778. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8779. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8780. var output = "";
  8781. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8782. var i = 0;
  8783. var bytes = new Uint8Array(buffer);
  8784. while (i < bytes.length) {
  8785. chr1 = bytes[i++];
  8786. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8787. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8788. enc1 = chr1 >> 2;
  8789. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8790. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8791. enc4 = chr3 & 63;
  8792. if (isNaN(chr2)) {
  8793. enc3 = enc4 = 64;
  8794. }
  8795. else if (isNaN(chr3)) {
  8796. enc4 = 64;
  8797. }
  8798. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8799. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8800. }
  8801. return "data:image/png;base64," + output;
  8802. };
  8803. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8804. if (bias === void 0) { bias = null; }
  8805. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8806. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8807. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8808. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8809. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8810. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8811. }
  8812. if (bias) {
  8813. minimum.x -= minimum.x * bias.x + bias.y;
  8814. minimum.y -= minimum.y * bias.x + bias.y;
  8815. minimum.z -= minimum.z * bias.x + bias.y;
  8816. maximum.x += maximum.x * bias.x + bias.y;
  8817. maximum.y += maximum.y * bias.x + bias.y;
  8818. maximum.z += maximum.z * bias.x + bias.y;
  8819. }
  8820. return {
  8821. minimum: minimum,
  8822. maximum: maximum
  8823. };
  8824. };
  8825. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8826. if (bias === void 0) { bias = null; }
  8827. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8828. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8829. if (!stride) {
  8830. stride = 3;
  8831. }
  8832. for (var index = start; index < start + count; index++) {
  8833. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8834. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8835. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8836. }
  8837. if (bias) {
  8838. minimum.x -= minimum.x * bias.x + bias.y;
  8839. minimum.y -= minimum.y * bias.x + bias.y;
  8840. minimum.z -= minimum.z * bias.x + bias.y;
  8841. maximum.x += maximum.x * bias.x + bias.y;
  8842. maximum.y += maximum.y * bias.x + bias.y;
  8843. maximum.z += maximum.z * bias.x + bias.y;
  8844. }
  8845. return {
  8846. minimum: minimum,
  8847. maximum: maximum
  8848. };
  8849. };
  8850. Tools.Vector2ArrayFeeder = function (array) {
  8851. return function (index) {
  8852. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8853. var length = isFloatArray ? array.length / 2 : array.length;
  8854. if (index >= length) {
  8855. return null;
  8856. }
  8857. if (isFloatArray) {
  8858. var fa = array;
  8859. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8860. }
  8861. var a = array;
  8862. return a[index];
  8863. };
  8864. };
  8865. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8866. if (bias === void 0) { bias = null; }
  8867. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8868. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8869. var i = 0;
  8870. var cur = feeder(i++);
  8871. while (cur) {
  8872. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8873. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8874. cur = feeder(i++);
  8875. }
  8876. if (bias) {
  8877. minimum.x -= minimum.x * bias.x + bias.y;
  8878. minimum.y -= minimum.y * bias.x + bias.y;
  8879. maximum.x += maximum.x * bias.x + bias.y;
  8880. maximum.y += maximum.y * bias.x + bias.y;
  8881. }
  8882. return {
  8883. minimum: minimum,
  8884. maximum: maximum
  8885. };
  8886. };
  8887. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8888. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8889. return null;
  8890. return Array.isArray(obj) ? obj : [obj];
  8891. };
  8892. // Misc.
  8893. Tools.GetPointerPrefix = function () {
  8894. var eventPrefix = "pointer";
  8895. // Check if pointer events are supported
  8896. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8897. eventPrefix = "mouse";
  8898. }
  8899. return eventPrefix;
  8900. };
  8901. /**
  8902. * @param func - the function to be called
  8903. * @param requester - the object that will request the next frame. Falls back to window.
  8904. */
  8905. Tools.QueueNewFrame = function (func, requester) {
  8906. if (!Tools.IsWindowObjectExist()) {
  8907. return setTimeout(func, 16);
  8908. }
  8909. if (!requester) {
  8910. requester = window;
  8911. }
  8912. if (requester.requestAnimationFrame) {
  8913. return requester.requestAnimationFrame(func);
  8914. }
  8915. else if (requester.msRequestAnimationFrame) {
  8916. return requester.msRequestAnimationFrame(func);
  8917. }
  8918. else if (requester.webkitRequestAnimationFrame) {
  8919. return requester.webkitRequestAnimationFrame(func);
  8920. }
  8921. else if (requester.mozRequestAnimationFrame) {
  8922. return requester.mozRequestAnimationFrame(func);
  8923. }
  8924. else if (requester.oRequestAnimationFrame) {
  8925. return requester.oRequestAnimationFrame(func);
  8926. }
  8927. else {
  8928. return window.setTimeout(func, 16);
  8929. }
  8930. };
  8931. Tools.RequestFullscreen = function (element) {
  8932. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8933. if (!requestFunction)
  8934. return;
  8935. requestFunction.call(element);
  8936. };
  8937. Tools.ExitFullscreen = function () {
  8938. if (document.exitFullscreen) {
  8939. document.exitFullscreen();
  8940. }
  8941. else if (document.mozCancelFullScreen) {
  8942. document.mozCancelFullScreen();
  8943. }
  8944. else if (document.webkitCancelFullScreen) {
  8945. document.webkitCancelFullScreen();
  8946. }
  8947. else if (document.msCancelFullScreen) {
  8948. document.msCancelFullScreen();
  8949. }
  8950. };
  8951. Tools.SetCorsBehavior = function (url, element) {
  8952. if (url && url.indexOf("data:") === 0) {
  8953. return;
  8954. }
  8955. if (Tools.CorsBehavior) {
  8956. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8957. element.crossOrigin = Tools.CorsBehavior;
  8958. }
  8959. else {
  8960. var result = Tools.CorsBehavior(url);
  8961. if (result) {
  8962. element.crossOrigin = result;
  8963. }
  8964. }
  8965. }
  8966. };
  8967. // External files
  8968. Tools.CleanUrl = function (url) {
  8969. url = url.replace(/#/mg, "%23");
  8970. return url;
  8971. };
  8972. /**
  8973. * Loads an image as an HTMLImageElement.
  8974. * @param input url string, ArrayBuffer, or Blob to load
  8975. * @param onLoad callback called when the image successfully loads
  8976. * @param onError callback called when the image fails to load
  8977. * @param database database for caching
  8978. * @returns the HTMLImageElement of the loaded image
  8979. */
  8980. Tools.LoadImage = function (input, onLoad, onError, database) {
  8981. var url;
  8982. var usingObjectURL = false;
  8983. if (input instanceof ArrayBuffer) {
  8984. url = URL.createObjectURL(new Blob([input]));
  8985. usingObjectURL = true;
  8986. }
  8987. else if (input instanceof Blob) {
  8988. url = URL.createObjectURL(input);
  8989. usingObjectURL = true;
  8990. }
  8991. else {
  8992. url = Tools.CleanUrl(input);
  8993. url = Tools.PreprocessUrl(input);
  8994. }
  8995. var img = new Image();
  8996. Tools.SetCorsBehavior(url, img);
  8997. var loadHandler = function () {
  8998. if (usingObjectURL && img.src) {
  8999. URL.revokeObjectURL(img.src);
  9000. }
  9001. img.removeEventListener("load", loadHandler);
  9002. img.removeEventListener("error", errorHandler);
  9003. onLoad(img);
  9004. };
  9005. var errorHandler = function (err) {
  9006. if (usingObjectURL && img.src) {
  9007. URL.revokeObjectURL(img.src);
  9008. }
  9009. img.removeEventListener("load", loadHandler);
  9010. img.removeEventListener("error", errorHandler);
  9011. Tools.Error("Error while trying to load image: " + input);
  9012. if (onError) {
  9013. onError("Error while trying to load image: " + input, err);
  9014. }
  9015. };
  9016. img.addEventListener("load", loadHandler);
  9017. img.addEventListener("error", errorHandler);
  9018. var noIndexedDB = function () {
  9019. img.src = url;
  9020. };
  9021. var loadFromIndexedDB = function () {
  9022. if (database) {
  9023. database.loadImageFromDB(url, img);
  9024. }
  9025. };
  9026. //ANY database to do!
  9027. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9028. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9029. }
  9030. else {
  9031. if (url.indexOf("file:") !== -1) {
  9032. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9033. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9034. try {
  9035. var blobURL;
  9036. try {
  9037. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  9038. }
  9039. catch (ex) {
  9040. // Chrome doesn't support oneTimeOnly parameter
  9041. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9042. }
  9043. img.src = blobURL;
  9044. usingObjectURL = true;
  9045. }
  9046. catch (e) {
  9047. img.src = "";
  9048. }
  9049. return img;
  9050. }
  9051. }
  9052. noIndexedDB();
  9053. }
  9054. return img;
  9055. };
  9056. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9057. url = Tools.CleanUrl(url);
  9058. url = Tools.PreprocessUrl(url);
  9059. // If file and file input are set
  9060. if (url.indexOf("file:") !== -1) {
  9061. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9062. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9063. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9064. }
  9065. }
  9066. var loadUrl = Tools.BaseUrl + url;
  9067. var aborted = false;
  9068. var fileRequest = {
  9069. onCompleteObservable: new BABYLON.Observable(),
  9070. abort: function () { return aborted = true; },
  9071. };
  9072. var requestFile = function () {
  9073. var request = new XMLHttpRequest();
  9074. var retryHandle = null;
  9075. fileRequest.abort = function () {
  9076. aborted = true;
  9077. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9078. request.abort();
  9079. }
  9080. if (retryHandle !== null) {
  9081. clearTimeout(retryHandle);
  9082. retryHandle = null;
  9083. }
  9084. };
  9085. var retryLoop = function (retryIndex) {
  9086. request.open('GET', loadUrl, true);
  9087. if (useArrayBuffer) {
  9088. request.responseType = "arraybuffer";
  9089. }
  9090. if (onProgress) {
  9091. request.addEventListener("progress", onProgress);
  9092. }
  9093. var onLoadEnd = function () {
  9094. request.removeEventListener("loadend", onLoadEnd);
  9095. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9096. fileRequest.onCompleteObservable.clear();
  9097. };
  9098. request.addEventListener("loadend", onLoadEnd);
  9099. var onReadyStateChange = function () {
  9100. if (aborted) {
  9101. return;
  9102. }
  9103. // In case of undefined state in some browsers.
  9104. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9105. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9106. request.removeEventListener("readystatechange", onReadyStateChange);
  9107. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9108. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9109. return;
  9110. }
  9111. var retryStrategy = Tools.DefaultRetryStrategy;
  9112. if (retryStrategy) {
  9113. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9114. if (waitTime !== -1) {
  9115. // Prevent the request from completing for retry.
  9116. request.removeEventListener("loadend", onLoadEnd);
  9117. request = new XMLHttpRequest();
  9118. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9119. return;
  9120. }
  9121. }
  9122. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9123. if (onError) {
  9124. onError(request, e);
  9125. }
  9126. else {
  9127. throw e;
  9128. }
  9129. }
  9130. };
  9131. request.addEventListener("readystatechange", onReadyStateChange);
  9132. request.send();
  9133. };
  9134. retryLoop(0);
  9135. };
  9136. // Caching all files
  9137. if (database && database.enableSceneOffline) {
  9138. var noIndexedDB_1 = function () {
  9139. if (!aborted) {
  9140. requestFile();
  9141. }
  9142. };
  9143. var loadFromIndexedDB = function () {
  9144. // TODO: database needs to support aborting and should return a IFileRequest
  9145. if (aborted) {
  9146. return;
  9147. }
  9148. if (database) {
  9149. database.loadFileFromDB(url, function (data) {
  9150. if (!aborted) {
  9151. onSuccess(data);
  9152. }
  9153. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9154. }, onProgress ? function (event) {
  9155. if (!aborted) {
  9156. onProgress(event);
  9157. }
  9158. } : undefined, noIndexedDB_1, useArrayBuffer);
  9159. }
  9160. };
  9161. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9162. }
  9163. else {
  9164. requestFile();
  9165. }
  9166. return fileRequest;
  9167. };
  9168. /**
  9169. * Load a script (identified by an url). When the url returns, the
  9170. * content of this file is added into a new script element, attached to the DOM (body element)
  9171. */
  9172. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9173. var head = document.getElementsByTagName('head')[0];
  9174. var script = document.createElement('script');
  9175. script.type = 'text/javascript';
  9176. script.src = scriptUrl;
  9177. script.onload = function () {
  9178. if (onSuccess) {
  9179. onSuccess();
  9180. }
  9181. };
  9182. script.onerror = function (e) {
  9183. if (onError) {
  9184. onError("Unable to load script '" + scriptUrl + "'", e);
  9185. }
  9186. };
  9187. head.appendChild(script);
  9188. };
  9189. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9190. var reader = new FileReader();
  9191. var request = {
  9192. onCompleteObservable: new BABYLON.Observable(),
  9193. abort: function () { return reader.abort(); },
  9194. };
  9195. reader.onloadend = function (e) {
  9196. request.onCompleteObservable.notifyObservers(request);
  9197. };
  9198. reader.onload = function (e) {
  9199. //target doesn't have result from ts 1.3
  9200. callback(e.target['result']);
  9201. };
  9202. reader.onprogress = progressCallback;
  9203. reader.readAsDataURL(fileToLoad);
  9204. return request;
  9205. };
  9206. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9207. var reader = new FileReader();
  9208. var request = {
  9209. onCompleteObservable: new BABYLON.Observable(),
  9210. abort: function () { return reader.abort(); },
  9211. };
  9212. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9213. reader.onerror = function (e) {
  9214. Tools.Log("Error while reading file: " + fileToLoad.name);
  9215. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9216. };
  9217. reader.onload = function (e) {
  9218. //target doesn't have result from ts 1.3
  9219. callback(e.target['result']);
  9220. };
  9221. if (progressCallBack) {
  9222. reader.onprogress = progressCallBack;
  9223. }
  9224. if (!useArrayBuffer) {
  9225. // Asynchronous read
  9226. reader.readAsText(fileToLoad);
  9227. }
  9228. else {
  9229. reader.readAsArrayBuffer(fileToLoad);
  9230. }
  9231. return request;
  9232. };
  9233. //returns a downloadable url to a file content.
  9234. Tools.FileAsURL = function (content) {
  9235. var fileBlob = new Blob([content]);
  9236. var url = window.URL || window.webkitURL;
  9237. var link = url.createObjectURL(fileBlob);
  9238. return link;
  9239. };
  9240. // Misc.
  9241. Tools.Format = function (value, decimals) {
  9242. if (decimals === void 0) { decimals = 2; }
  9243. return value.toFixed(decimals);
  9244. };
  9245. Tools.CheckExtends = function (v, min, max) {
  9246. if (v.x < min.x)
  9247. min.x = v.x;
  9248. if (v.y < min.y)
  9249. min.y = v.y;
  9250. if (v.z < min.z)
  9251. min.z = v.z;
  9252. if (v.x > max.x)
  9253. max.x = v.x;
  9254. if (v.y > max.y)
  9255. max.y = v.y;
  9256. if (v.z > max.z)
  9257. max.z = v.z;
  9258. };
  9259. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9260. for (var prop in source) {
  9261. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9262. continue;
  9263. }
  9264. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9265. continue;
  9266. }
  9267. var sourceValue = source[prop];
  9268. var typeOfSourceValue = typeof sourceValue;
  9269. if (typeOfSourceValue === "function") {
  9270. continue;
  9271. }
  9272. try {
  9273. if (typeOfSourceValue === "object") {
  9274. if (sourceValue instanceof Array) {
  9275. destination[prop] = [];
  9276. if (sourceValue.length > 0) {
  9277. if (typeof sourceValue[0] == "object") {
  9278. for (var index = 0; index < sourceValue.length; index++) {
  9279. var clonedValue = cloneValue(sourceValue[index], destination);
  9280. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9281. destination[prop].push(clonedValue);
  9282. }
  9283. }
  9284. }
  9285. else {
  9286. destination[prop] = sourceValue.slice(0);
  9287. }
  9288. }
  9289. }
  9290. else {
  9291. destination[prop] = cloneValue(sourceValue, destination);
  9292. }
  9293. }
  9294. else {
  9295. destination[prop] = sourceValue;
  9296. }
  9297. }
  9298. catch (e) {
  9299. // Just ignore error (it could be because of a read-only property)
  9300. }
  9301. }
  9302. };
  9303. Tools.IsEmpty = function (obj) {
  9304. for (var i in obj) {
  9305. if (obj.hasOwnProperty(i)) {
  9306. return false;
  9307. }
  9308. }
  9309. return true;
  9310. };
  9311. Tools.RegisterTopRootEvents = function (events) {
  9312. for (var index = 0; index < events.length; index++) {
  9313. var event = events[index];
  9314. window.addEventListener(event.name, event.handler, false);
  9315. try {
  9316. if (window.parent) {
  9317. window.parent.addEventListener(event.name, event.handler, false);
  9318. }
  9319. }
  9320. catch (e) {
  9321. // Silently fails...
  9322. }
  9323. }
  9324. };
  9325. Tools.UnregisterTopRootEvents = function (events) {
  9326. for (var index = 0; index < events.length; index++) {
  9327. var event = events[index];
  9328. window.removeEventListener(event.name, event.handler);
  9329. try {
  9330. if (window.parent) {
  9331. window.parent.removeEventListener(event.name, event.handler);
  9332. }
  9333. }
  9334. catch (e) {
  9335. // Silently fails...
  9336. }
  9337. }
  9338. };
  9339. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9340. if (mimeType === void 0) { mimeType = "image/png"; }
  9341. // Read the contents of the framebuffer
  9342. var numberOfChannelsByLine = width * 4;
  9343. var halfHeight = height / 2;
  9344. //Reading datas from WebGL
  9345. var data = engine.readPixels(0, 0, width, height);
  9346. //To flip image on Y axis.
  9347. for (var i = 0; i < halfHeight; i++) {
  9348. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9349. var currentCell = j + i * numberOfChannelsByLine;
  9350. var targetLine = height - i - 1;
  9351. var targetCell = j + targetLine * numberOfChannelsByLine;
  9352. var temp = data[currentCell];
  9353. data[currentCell] = data[targetCell];
  9354. data[targetCell] = temp;
  9355. }
  9356. }
  9357. // Create a 2D canvas to store the result
  9358. if (!screenshotCanvas) {
  9359. screenshotCanvas = document.createElement('canvas');
  9360. }
  9361. screenshotCanvas.width = width;
  9362. screenshotCanvas.height = height;
  9363. var context = screenshotCanvas.getContext('2d');
  9364. if (context) {
  9365. // Copy the pixels to a 2D canvas
  9366. var imageData = context.createImageData(width, height);
  9367. var castData = (imageData.data);
  9368. castData.set(data);
  9369. context.putImageData(imageData, 0, 0);
  9370. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9371. }
  9372. };
  9373. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9374. if (mimeType === void 0) { mimeType = "image/png"; }
  9375. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9376. if (successCallback) {
  9377. successCallback(base64Image);
  9378. }
  9379. else {
  9380. // We need HTMLCanvasElement.toBlob for HD screenshots
  9381. if (!screenshotCanvas.toBlob) {
  9382. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9383. screenshotCanvas.toBlob = function (callback, type, quality) {
  9384. var _this = this;
  9385. setTimeout(function () {
  9386. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9387. for (var i = 0; i < len; i++) {
  9388. arr[i] = binStr.charCodeAt(i);
  9389. }
  9390. callback(new Blob([arr], { type: type || 'image/png' }));
  9391. });
  9392. };
  9393. }
  9394. screenshotCanvas.toBlob(function (blob) {
  9395. var url = URL.createObjectURL(blob);
  9396. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9397. if (("download" in document.createElement("a"))) {
  9398. var a = window.document.createElement("a");
  9399. a.href = url;
  9400. if (fileName) {
  9401. a.setAttribute("download", fileName);
  9402. }
  9403. else {
  9404. var date = new Date();
  9405. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9406. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9407. }
  9408. window.document.body.appendChild(a);
  9409. a.addEventListener("click", function () {
  9410. if (a.parentElement) {
  9411. a.parentElement.removeChild(a);
  9412. }
  9413. });
  9414. a.click();
  9415. }
  9416. else {
  9417. var newWindow = window.open("");
  9418. if (!newWindow)
  9419. return;
  9420. var img = newWindow.document.createElement("img");
  9421. img.onload = function () {
  9422. // no longer need to read the blob so it's revoked
  9423. URL.revokeObjectURL(url);
  9424. };
  9425. img.src = url;
  9426. newWindow.document.body.appendChild(img);
  9427. }
  9428. });
  9429. }
  9430. };
  9431. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9432. if (mimeType === void 0) { mimeType = "image/png"; }
  9433. var width;
  9434. var height;
  9435. // If a precision value is specified
  9436. if (size.precision) {
  9437. width = Math.round(engine.getRenderWidth() * size.precision);
  9438. height = Math.round(width / engine.getAspectRatio(camera));
  9439. }
  9440. else if (size.width && size.height) {
  9441. width = size.width;
  9442. height = size.height;
  9443. }
  9444. //If passing only width, computing height to keep display canvas ratio.
  9445. else if (size.width && !size.height) {
  9446. width = size.width;
  9447. height = Math.round(width / engine.getAspectRatio(camera));
  9448. }
  9449. //If passing only height, computing width to keep display canvas ratio.
  9450. else if (size.height && !size.width) {
  9451. height = size.height;
  9452. width = Math.round(height * engine.getAspectRatio(camera));
  9453. }
  9454. //Assuming here that "size" parameter is a number
  9455. else if (!isNaN(size)) {
  9456. height = size;
  9457. width = size;
  9458. }
  9459. else {
  9460. Tools.Error("Invalid 'size' parameter !");
  9461. return;
  9462. }
  9463. if (!screenshotCanvas) {
  9464. screenshotCanvas = document.createElement('canvas');
  9465. }
  9466. screenshotCanvas.width = width;
  9467. screenshotCanvas.height = height;
  9468. var renderContext = screenshotCanvas.getContext("2d");
  9469. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9470. var newWidth = width;
  9471. var newHeight = newWidth / ratio;
  9472. if (newHeight > height) {
  9473. newHeight = height;
  9474. newWidth = newHeight * ratio;
  9475. }
  9476. var offsetX = Math.max(0, width - newWidth) / 2;
  9477. var offsetY = Math.max(0, height - newHeight) / 2;
  9478. var renderingCanvas = engine.getRenderingCanvas();
  9479. if (renderContext && renderingCanvas) {
  9480. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9481. }
  9482. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9483. };
  9484. /**
  9485. * Generates an image screenshot from the specified camera.
  9486. *
  9487. * @param engine The engine to use for rendering
  9488. * @param camera The camera to use for rendering
  9489. * @param size This parameter can be set to a single number or to an object with the
  9490. * following (optional) properties: precision, width, height. If a single number is passed,
  9491. * it will be used for both width and height. If an object is passed, the screenshot size
  9492. * will be derived from the parameters. The precision property is a multiplier allowing
  9493. * rendering at a higher or lower resolution.
  9494. * @param successCallback The callback receives a single parameter which contains the
  9495. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9496. * src parameter of an <img> to display it.
  9497. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9498. * Check your browser for supported MIME types.
  9499. * @param samples Texture samples (default: 1)
  9500. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9501. * @param fileName A name for for the downloaded file.
  9502. * @constructor
  9503. */
  9504. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9505. if (mimeType === void 0) { mimeType = "image/png"; }
  9506. if (samples === void 0) { samples = 1; }
  9507. if (antialiasing === void 0) { antialiasing = false; }
  9508. var width;
  9509. var height;
  9510. //If a precision value is specified
  9511. if (size.precision) {
  9512. width = Math.round(engine.getRenderWidth() * size.precision);
  9513. height = Math.round(width / engine.getAspectRatio(camera));
  9514. size = { width: width, height: height };
  9515. }
  9516. else if (size.width && size.height) {
  9517. width = size.width;
  9518. height = size.height;
  9519. }
  9520. //If passing only width, computing height to keep display canvas ratio.
  9521. else if (size.width && !size.height) {
  9522. width = size.width;
  9523. height = Math.round(width / engine.getAspectRatio(camera));
  9524. size = { width: width, height: height };
  9525. }
  9526. //If passing only height, computing width to keep display canvas ratio.
  9527. else if (size.height && !size.width) {
  9528. height = size.height;
  9529. width = Math.round(height * engine.getAspectRatio(camera));
  9530. size = { width: width, height: height };
  9531. }
  9532. //Assuming here that "size" parameter is a number
  9533. else if (!isNaN(size)) {
  9534. height = size;
  9535. width = size;
  9536. }
  9537. else {
  9538. Tools.Error("Invalid 'size' parameter !");
  9539. return;
  9540. }
  9541. var scene = camera.getScene();
  9542. var previousCamera = null;
  9543. if (scene.activeCamera !== camera) {
  9544. previousCamera = scene.activeCamera;
  9545. scene.activeCamera = camera;
  9546. }
  9547. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9548. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9549. texture.renderList = null;
  9550. texture.samples = samples;
  9551. if (antialiasing) {
  9552. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9553. }
  9554. texture.onAfterRenderObservable.add(function () {
  9555. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9556. });
  9557. scene.incrementRenderId();
  9558. scene.resetCachedMaterial();
  9559. texture.render(true);
  9560. texture.dispose();
  9561. if (previousCamera) {
  9562. scene.activeCamera = previousCamera;
  9563. }
  9564. camera.getProjectionMatrix(true); // Force cache refresh;
  9565. };
  9566. // XHR response validator for local file scenario
  9567. Tools.ValidateXHRData = function (xhr, dataType) {
  9568. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9569. if (dataType === void 0) { dataType = 7; }
  9570. try {
  9571. if (dataType & 1) {
  9572. if (xhr.responseText && xhr.responseText.length > 0) {
  9573. return true;
  9574. }
  9575. else if (dataType === 1) {
  9576. return false;
  9577. }
  9578. }
  9579. if (dataType & 2) {
  9580. // Check header width and height since there is no "TGA" magic number
  9581. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9582. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9583. return true;
  9584. }
  9585. else if (dataType === 2) {
  9586. return false;
  9587. }
  9588. }
  9589. if (dataType & 4) {
  9590. // Check for the "DDS" magic number
  9591. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9592. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9593. return true;
  9594. }
  9595. else {
  9596. return false;
  9597. }
  9598. }
  9599. }
  9600. catch (e) {
  9601. // Global protection
  9602. }
  9603. return false;
  9604. };
  9605. /**
  9606. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9607. * Be aware Math.random() could cause collisions, but:
  9608. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  9609. */
  9610. Tools.RandomId = function () {
  9611. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9612. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9613. return v.toString(16);
  9614. });
  9615. };
  9616. /**
  9617. * Test if the given uri is a base64 string.
  9618. * @param uri The uri to test
  9619. * @return True if the uri is a base64 string or false otherwise.
  9620. */
  9621. Tools.IsBase64 = function (uri) {
  9622. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9623. };
  9624. /**
  9625. * Decode the given base64 uri.
  9626. * @param uri The uri to decode
  9627. * @return The decoded base64 data.
  9628. */
  9629. Tools.DecodeBase64 = function (uri) {
  9630. var decodedString = atob(uri.split(",")[1]);
  9631. var bufferLength = decodedString.length;
  9632. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9633. for (var i = 0; i < bufferLength; i++) {
  9634. bufferView[i] = decodedString.charCodeAt(i);
  9635. }
  9636. return bufferView.buffer;
  9637. };
  9638. Object.defineProperty(Tools, "NoneLogLevel", {
  9639. get: function () {
  9640. return Tools._NoneLogLevel;
  9641. },
  9642. enumerable: true,
  9643. configurable: true
  9644. });
  9645. Object.defineProperty(Tools, "MessageLogLevel", {
  9646. get: function () {
  9647. return Tools._MessageLogLevel;
  9648. },
  9649. enumerable: true,
  9650. configurable: true
  9651. });
  9652. Object.defineProperty(Tools, "WarningLogLevel", {
  9653. get: function () {
  9654. return Tools._WarningLogLevel;
  9655. },
  9656. enumerable: true,
  9657. configurable: true
  9658. });
  9659. Object.defineProperty(Tools, "ErrorLogLevel", {
  9660. get: function () {
  9661. return Tools._ErrorLogLevel;
  9662. },
  9663. enumerable: true,
  9664. configurable: true
  9665. });
  9666. Object.defineProperty(Tools, "AllLogLevel", {
  9667. get: function () {
  9668. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9669. },
  9670. enumerable: true,
  9671. configurable: true
  9672. });
  9673. Tools._AddLogEntry = function (entry) {
  9674. Tools._LogCache = entry + Tools._LogCache;
  9675. if (Tools.OnNewCacheEntry) {
  9676. Tools.OnNewCacheEntry(entry);
  9677. }
  9678. };
  9679. Tools._FormatMessage = function (message) {
  9680. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9681. var date = new Date();
  9682. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9683. };
  9684. Tools._LogDisabled = function (message) {
  9685. // nothing to do
  9686. };
  9687. Tools._LogEnabled = function (message) {
  9688. var formattedMessage = Tools._FormatMessage(message);
  9689. console.log("BJS - " + formattedMessage);
  9690. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9691. Tools._AddLogEntry(entry);
  9692. };
  9693. Tools._WarnDisabled = function (message) {
  9694. // nothing to do
  9695. };
  9696. Tools._WarnEnabled = function (message) {
  9697. var formattedMessage = Tools._FormatMessage(message);
  9698. console.warn("BJS - " + formattedMessage);
  9699. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9700. Tools._AddLogEntry(entry);
  9701. };
  9702. Tools._ErrorDisabled = function (message) {
  9703. // nothing to do
  9704. };
  9705. Tools._ErrorEnabled = function (message) {
  9706. Tools.errorsCount++;
  9707. var formattedMessage = Tools._FormatMessage(message);
  9708. console.error("BJS - " + formattedMessage);
  9709. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9710. Tools._AddLogEntry(entry);
  9711. };
  9712. Object.defineProperty(Tools, "LogCache", {
  9713. get: function () {
  9714. return Tools._LogCache;
  9715. },
  9716. enumerable: true,
  9717. configurable: true
  9718. });
  9719. Tools.ClearLogCache = function () {
  9720. Tools._LogCache = "";
  9721. Tools.errorsCount = 0;
  9722. };
  9723. Object.defineProperty(Tools, "LogLevels", {
  9724. set: function (level) {
  9725. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9726. Tools.Log = Tools._LogEnabled;
  9727. }
  9728. else {
  9729. Tools.Log = Tools._LogDisabled;
  9730. }
  9731. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9732. Tools.Warn = Tools._WarnEnabled;
  9733. }
  9734. else {
  9735. Tools.Warn = Tools._WarnDisabled;
  9736. }
  9737. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9738. Tools.Error = Tools._ErrorEnabled;
  9739. }
  9740. else {
  9741. Tools.Error = Tools._ErrorDisabled;
  9742. }
  9743. },
  9744. enumerable: true,
  9745. configurable: true
  9746. });
  9747. Tools.IsWindowObjectExist = function () {
  9748. return (typeof window) !== "undefined";
  9749. };
  9750. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9751. get: function () {
  9752. return Tools._PerformanceNoneLogLevel;
  9753. },
  9754. enumerable: true,
  9755. configurable: true
  9756. });
  9757. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9758. get: function () {
  9759. return Tools._PerformanceUserMarkLogLevel;
  9760. },
  9761. enumerable: true,
  9762. configurable: true
  9763. });
  9764. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9765. get: function () {
  9766. return Tools._PerformanceConsoleLogLevel;
  9767. },
  9768. enumerable: true,
  9769. configurable: true
  9770. });
  9771. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9772. set: function (level) {
  9773. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9774. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9775. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9776. return;
  9777. }
  9778. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9779. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9780. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9781. return;
  9782. }
  9783. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9784. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9785. },
  9786. enumerable: true,
  9787. configurable: true
  9788. });
  9789. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9790. };
  9791. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9792. };
  9793. Tools._StartUserMark = function (counterName, condition) {
  9794. if (condition === void 0) { condition = true; }
  9795. if (!Tools._performance) {
  9796. if (!Tools.IsWindowObjectExist()) {
  9797. return;
  9798. }
  9799. Tools._performance = window.performance;
  9800. }
  9801. if (!condition || !Tools._performance.mark) {
  9802. return;
  9803. }
  9804. Tools._performance.mark(counterName + "-Begin");
  9805. };
  9806. Tools._EndUserMark = function (counterName, condition) {
  9807. if (condition === void 0) { condition = true; }
  9808. if (!condition || !Tools._performance.mark) {
  9809. return;
  9810. }
  9811. Tools._performance.mark(counterName + "-End");
  9812. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9813. };
  9814. Tools._StartPerformanceConsole = function (counterName, condition) {
  9815. if (condition === void 0) { condition = true; }
  9816. if (!condition) {
  9817. return;
  9818. }
  9819. Tools._StartUserMark(counterName, condition);
  9820. if (console.time) {
  9821. console.time(counterName);
  9822. }
  9823. };
  9824. Tools._EndPerformanceConsole = function (counterName, condition) {
  9825. if (condition === void 0) { condition = true; }
  9826. if (!condition) {
  9827. return;
  9828. }
  9829. Tools._EndUserMark(counterName, condition);
  9830. if (console.time) {
  9831. console.timeEnd(counterName);
  9832. }
  9833. };
  9834. Object.defineProperty(Tools, "Now", {
  9835. get: function () {
  9836. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9837. return window.performance.now();
  9838. }
  9839. return Date.now();
  9840. },
  9841. enumerable: true,
  9842. configurable: true
  9843. });
  9844. /**
  9845. * This method will return the name of the class used to create the instance of the given object.
  9846. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9847. * @param object the object to get the class name from
  9848. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9849. */
  9850. Tools.GetClassName = function (object, isType) {
  9851. if (isType === void 0) { isType = false; }
  9852. var name = null;
  9853. if (!isType && object.getClassName) {
  9854. name = object.getClassName();
  9855. }
  9856. else {
  9857. if (object instanceof Object) {
  9858. var classObj = isType ? object : Object.getPrototypeOf(object);
  9859. name = classObj.constructor["__bjsclassName__"];
  9860. }
  9861. if (!name) {
  9862. name = typeof object;
  9863. }
  9864. }
  9865. return name;
  9866. };
  9867. Tools.First = function (array, predicate) {
  9868. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9869. var el = array_1[_i];
  9870. if (predicate(el)) {
  9871. return el;
  9872. }
  9873. }
  9874. return null;
  9875. };
  9876. /**
  9877. * This method will return the name of the full name of the class, including its owning module (if any).
  9878. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  9879. * @param object the object to get the class name from
  9880. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  9881. */
  9882. Tools.getFullClassName = function (object, isType) {
  9883. if (isType === void 0) { isType = false; }
  9884. var className = null;
  9885. var moduleName = null;
  9886. if (!isType && object.getClassName) {
  9887. className = object.getClassName();
  9888. }
  9889. else {
  9890. if (object instanceof Object) {
  9891. var classObj = isType ? object : Object.getPrototypeOf(object);
  9892. className = classObj.constructor["__bjsclassName__"];
  9893. moduleName = classObj.constructor["__bjsmoduleName__"];
  9894. }
  9895. if (!className) {
  9896. className = typeof object;
  9897. }
  9898. }
  9899. if (!className) {
  9900. return null;
  9901. }
  9902. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9903. };
  9904. /**
  9905. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  9906. * @param array
  9907. */
  9908. Tools.arrayOrStringFeeder = function (array) {
  9909. return function (index) {
  9910. if (index >= array.length) {
  9911. return null;
  9912. }
  9913. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9914. if (val && val.getHashCode) {
  9915. val = val.getHashCode();
  9916. }
  9917. if (typeof val === "string") {
  9918. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9919. }
  9920. return val;
  9921. };
  9922. };
  9923. /**
  9924. * Compute the hashCode of a stream of number
  9925. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9926. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9927. * @return the hash code computed
  9928. */
  9929. Tools.hashCodeFromStream = function (feeder) {
  9930. // Based from here: http://stackoverflow.com/a/7616484/802124
  9931. var hash = 0;
  9932. var index = 0;
  9933. var chr = feeder(index++);
  9934. while (chr != null) {
  9935. hash = ((hash << 5) - hash) + chr;
  9936. hash |= 0; // Convert to 32bit integer
  9937. chr = feeder(index++);
  9938. }
  9939. return hash;
  9940. };
  9941. /**
  9942. * Returns a promise that resolves after the given amount of time.
  9943. * @param delay Number of milliseconds to delay
  9944. * @returns Promise that resolves after the given amount of time
  9945. */
  9946. Tools.DelayAsync = function (delay) {
  9947. return new Promise(function (resolve) {
  9948. setTimeout(function () {
  9949. resolve();
  9950. }, delay);
  9951. });
  9952. };
  9953. Tools.BaseUrl = "";
  9954. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9955. /**
  9956. * Default behaviour for cors in the application.
  9957. * It can be a string if the expected behavior is identical in the entire app.
  9958. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9959. */
  9960. Tools.CorsBehavior = "anonymous";
  9961. Tools.UseFallbackTexture = true;
  9962. /**
  9963. * Use this object to register external classes like custom textures or material
  9964. * to allow the laoders to instantiate them
  9965. */
  9966. Tools.RegisteredExternalClasses = {};
  9967. // Used in case of a texture loading problem
  9968. Tools.fallbackTexture = "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";
  9969. Tools._tmpFloatArray = new Float32Array(1);
  9970. Tools.PreprocessUrl = function (url) {
  9971. return url;
  9972. };
  9973. // Logs
  9974. Tools._NoneLogLevel = 0;
  9975. Tools._MessageLogLevel = 1;
  9976. Tools._WarningLogLevel = 2;
  9977. Tools._ErrorLogLevel = 4;
  9978. Tools._LogCache = "";
  9979. Tools.errorsCount = 0;
  9980. Tools.Log = Tools._LogEnabled;
  9981. Tools.Warn = Tools._WarnEnabled;
  9982. Tools.Error = Tools._ErrorEnabled;
  9983. // Performances
  9984. Tools._PerformanceNoneLogLevel = 0;
  9985. Tools._PerformanceUserMarkLogLevel = 1;
  9986. Tools._PerformanceConsoleLogLevel = 2;
  9987. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9988. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9989. return Tools;
  9990. }());
  9991. BABYLON.Tools = Tools;
  9992. /**
  9993. * This class is used to track a performance counter which is number based.
  9994. * The user has access to many properties which give statistics of different nature
  9995. *
  9996. * The implementer can track two kinds of Performance Counter: time and count
  9997. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  9998. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  9999. */
  10000. var PerfCounter = /** @class */ (function () {
  10001. function PerfCounter() {
  10002. this._startMonitoringTime = 0;
  10003. this._min = 0;
  10004. this._max = 0;
  10005. this._average = 0;
  10006. this._lastSecAverage = 0;
  10007. this._current = 0;
  10008. this._totalValueCount = 0;
  10009. this._totalAccumulated = 0;
  10010. this._lastSecAccumulated = 0;
  10011. this._lastSecTime = 0;
  10012. this._lastSecValueCount = 0;
  10013. }
  10014. Object.defineProperty(PerfCounter.prototype, "min", {
  10015. /**
  10016. * Returns the smallest value ever
  10017. */
  10018. get: function () {
  10019. return this._min;
  10020. },
  10021. enumerable: true,
  10022. configurable: true
  10023. });
  10024. Object.defineProperty(PerfCounter.prototype, "max", {
  10025. /**
  10026. * Returns the biggest value ever
  10027. */
  10028. get: function () {
  10029. return this._max;
  10030. },
  10031. enumerable: true,
  10032. configurable: true
  10033. });
  10034. Object.defineProperty(PerfCounter.prototype, "average", {
  10035. /**
  10036. * Returns the average value since the performance counter is running
  10037. */
  10038. get: function () {
  10039. return this._average;
  10040. },
  10041. enumerable: true,
  10042. configurable: true
  10043. });
  10044. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10045. /**
  10046. * Returns the average value of the last second the counter was monitored
  10047. */
  10048. get: function () {
  10049. return this._lastSecAverage;
  10050. },
  10051. enumerable: true,
  10052. configurable: true
  10053. });
  10054. Object.defineProperty(PerfCounter.prototype, "current", {
  10055. /**
  10056. * Returns the current value
  10057. */
  10058. get: function () {
  10059. return this._current;
  10060. },
  10061. enumerable: true,
  10062. configurable: true
  10063. });
  10064. Object.defineProperty(PerfCounter.prototype, "total", {
  10065. get: function () {
  10066. return this._totalAccumulated;
  10067. },
  10068. enumerable: true,
  10069. configurable: true
  10070. });
  10071. Object.defineProperty(PerfCounter.prototype, "count", {
  10072. get: function () {
  10073. return this._totalValueCount;
  10074. },
  10075. enumerable: true,
  10076. configurable: true
  10077. });
  10078. /**
  10079. * Call this method to start monitoring a new frame.
  10080. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  10081. */
  10082. PerfCounter.prototype.fetchNewFrame = function () {
  10083. this._totalValueCount++;
  10084. this._current = 0;
  10085. this._lastSecValueCount++;
  10086. };
  10087. /**
  10088. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10089. * @param newCount the count value to add to the monitored count
  10090. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  10091. */
  10092. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10093. if (!PerfCounter.Enabled) {
  10094. return;
  10095. }
  10096. this._current += newCount;
  10097. if (fetchResult) {
  10098. this._fetchResult();
  10099. }
  10100. };
  10101. /**
  10102. * Start monitoring this performance counter
  10103. */
  10104. PerfCounter.prototype.beginMonitoring = function () {
  10105. if (!PerfCounter.Enabled) {
  10106. return;
  10107. }
  10108. this._startMonitoringTime = Tools.Now;
  10109. };
  10110. /**
  10111. * Compute the time lapsed since the previous beginMonitoring() call.
  10112. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  10113. */
  10114. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10115. if (newFrame === void 0) { newFrame = true; }
  10116. if (!PerfCounter.Enabled) {
  10117. return;
  10118. }
  10119. if (newFrame) {
  10120. this.fetchNewFrame();
  10121. }
  10122. var currentTime = Tools.Now;
  10123. this._current = currentTime - this._startMonitoringTime;
  10124. if (newFrame) {
  10125. this._fetchResult();
  10126. }
  10127. };
  10128. PerfCounter.prototype._fetchResult = function () {
  10129. this._totalAccumulated += this._current;
  10130. this._lastSecAccumulated += this._current;
  10131. // Min/Max update
  10132. this._min = Math.min(this._min, this._current);
  10133. this._max = Math.max(this._max, this._current);
  10134. this._average = this._totalAccumulated / this._totalValueCount;
  10135. // Reset last sec?
  10136. var now = Tools.Now;
  10137. if ((now - this._lastSecTime) > 1000) {
  10138. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10139. this._lastSecTime = now;
  10140. this._lastSecAccumulated = 0;
  10141. this._lastSecValueCount = 0;
  10142. }
  10143. };
  10144. PerfCounter.Enabled = true;
  10145. return PerfCounter;
  10146. }());
  10147. BABYLON.PerfCounter = PerfCounter;
  10148. /**
  10149. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10150. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10151. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10152. * @param name The name of the class, case should be preserved
  10153. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10154. */
  10155. function className(name, module) {
  10156. return function (target) {
  10157. target["__bjsclassName__"] = name;
  10158. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10159. };
  10160. }
  10161. BABYLON.className = className;
  10162. /**
  10163. * An implementation of a loop for asynchronous functions.
  10164. */
  10165. var AsyncLoop = /** @class */ (function () {
  10166. /**
  10167. * Constroctor.
  10168. * @param iterations the number of iterations.
  10169. * @param _fn the function to run each iteration
  10170. * @param _successCallback the callback that will be called upon succesful execution
  10171. * @param offset starting offset.
  10172. */
  10173. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10174. if (offset === void 0) { offset = 0; }
  10175. this.iterations = iterations;
  10176. this._fn = _fn;
  10177. this._successCallback = _successCallback;
  10178. this.index = offset - 1;
  10179. this._done = false;
  10180. }
  10181. /**
  10182. * Execute the next iteration. Must be called after the last iteration was finished.
  10183. */
  10184. AsyncLoop.prototype.executeNext = function () {
  10185. if (!this._done) {
  10186. if (this.index + 1 < this.iterations) {
  10187. ++this.index;
  10188. this._fn(this);
  10189. }
  10190. else {
  10191. this.breakLoop();
  10192. }
  10193. }
  10194. };
  10195. /**
  10196. * Break the loop and run the success callback.
  10197. */
  10198. AsyncLoop.prototype.breakLoop = function () {
  10199. this._done = true;
  10200. this._successCallback();
  10201. };
  10202. /**
  10203. * Helper function
  10204. */
  10205. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10206. if (offset === void 0) { offset = 0; }
  10207. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10208. loop.executeNext();
  10209. return loop;
  10210. };
  10211. /**
  10212. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10213. * @param iterations total number of iterations
  10214. * @param syncedIterations number of synchronous iterations in each async iteration.
  10215. * @param fn the function to call each iteration.
  10216. * @param callback a success call back that will be called when iterating stops.
  10217. * @param breakFunction a break condition (optional)
  10218. * @param timeout timeout settings for the setTimeout function. default - 0.
  10219. * @constructor
  10220. */
  10221. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10222. if (timeout === void 0) { timeout = 0; }
  10223. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10224. if (breakFunction && breakFunction())
  10225. loop.breakLoop();
  10226. else {
  10227. setTimeout(function () {
  10228. for (var i = 0; i < syncedIterations; ++i) {
  10229. var iteration = (loop.index * syncedIterations) + i;
  10230. if (iteration >= iterations)
  10231. break;
  10232. fn(iteration);
  10233. if (breakFunction && breakFunction()) {
  10234. loop.breakLoop();
  10235. break;
  10236. }
  10237. }
  10238. loop.executeNext();
  10239. }, timeout);
  10240. }
  10241. }, callback);
  10242. };
  10243. return AsyncLoop;
  10244. }());
  10245. BABYLON.AsyncLoop = AsyncLoop;
  10246. })(BABYLON || (BABYLON = {}));
  10247. //# sourceMappingURL=babylon.tools.js.map
  10248. var BABYLON;
  10249. (function (BABYLON) {
  10250. var PromiseStates;
  10251. (function (PromiseStates) {
  10252. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10253. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10254. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10255. })(PromiseStates || (PromiseStates = {}));
  10256. var FulFillmentAgregator = /** @class */ (function () {
  10257. function FulFillmentAgregator() {
  10258. this.count = 0;
  10259. this.target = 0;
  10260. this.results = [];
  10261. }
  10262. return FulFillmentAgregator;
  10263. }());
  10264. var InternalPromise = /** @class */ (function () {
  10265. function InternalPromise(resolver) {
  10266. var _this = this;
  10267. this._state = PromiseStates.Pending;
  10268. this._children = new Array();
  10269. this._rejectWasConsumed = false;
  10270. if (!resolver) {
  10271. return;
  10272. }
  10273. try {
  10274. resolver(function (value) {
  10275. _this._resolve(value);
  10276. }, function (reason) {
  10277. _this._reject(reason);
  10278. });
  10279. }
  10280. catch (e) {
  10281. this._reject(e);
  10282. }
  10283. }
  10284. Object.defineProperty(InternalPromise.prototype, "_result", {
  10285. get: function () {
  10286. return this._resultValue;
  10287. },
  10288. set: function (value) {
  10289. this._resultValue = value;
  10290. if (this._parent && this._parent._result === undefined) {
  10291. this._parent._result = value;
  10292. }
  10293. },
  10294. enumerable: true,
  10295. configurable: true
  10296. });
  10297. InternalPromise.prototype.catch = function (onRejected) {
  10298. return this.then(undefined, onRejected);
  10299. };
  10300. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10301. var _this = this;
  10302. var newPromise = new InternalPromise();
  10303. newPromise._onFulfilled = onFulfilled;
  10304. newPromise._onRejected = onRejected;
  10305. // Composition
  10306. this._children.push(newPromise);
  10307. newPromise._parent = this;
  10308. if (this._state !== PromiseStates.Pending) {
  10309. BABYLON.Tools.SetImmediate(function () {
  10310. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10311. var returnedValue = newPromise._resolve(_this._result);
  10312. if (returnedValue !== undefined && returnedValue !== null) {
  10313. if (returnedValue._state !== undefined) {
  10314. var returnedPromise = returnedValue;
  10315. newPromise._children.push(returnedPromise);
  10316. returnedPromise._parent = newPromise;
  10317. newPromise = returnedPromise;
  10318. }
  10319. else {
  10320. newPromise._result = returnedValue;
  10321. }
  10322. }
  10323. }
  10324. else {
  10325. newPromise._reject(_this._reason);
  10326. }
  10327. });
  10328. }
  10329. return newPromise;
  10330. };
  10331. InternalPromise.prototype._moveChildren = function (children) {
  10332. var _this = this;
  10333. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10334. this._children.forEach(function (child) {
  10335. child._parent = _this;
  10336. });
  10337. if (this._state === PromiseStates.Fulfilled) {
  10338. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10339. var child = _b[_i];
  10340. child._resolve(this._result);
  10341. }
  10342. }
  10343. else if (this._state === PromiseStates.Rejected) {
  10344. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10345. var child = _d[_c];
  10346. child._reject(this._reason);
  10347. }
  10348. }
  10349. var _a;
  10350. };
  10351. InternalPromise.prototype._resolve = function (value) {
  10352. try {
  10353. this._state = PromiseStates.Fulfilled;
  10354. var returnedValue = null;
  10355. if (this._onFulfilled) {
  10356. returnedValue = this._onFulfilled(value);
  10357. }
  10358. if (returnedValue !== undefined && returnedValue !== null) {
  10359. if (returnedValue._state !== undefined) {
  10360. // Transmit children
  10361. var returnedPromise = returnedValue;
  10362. returnedPromise._parent = this;
  10363. returnedPromise._moveChildren(this._children);
  10364. value = returnedPromise._result;
  10365. }
  10366. else {
  10367. value = returnedValue;
  10368. }
  10369. }
  10370. this._result = value;
  10371. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10372. var child = _a[_i];
  10373. child._resolve(value);
  10374. }
  10375. this._children.length = 0;
  10376. delete this._onFulfilled;
  10377. delete this._onRejected;
  10378. }
  10379. catch (e) {
  10380. this._reject(e, true);
  10381. }
  10382. };
  10383. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10384. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10385. this._state = PromiseStates.Rejected;
  10386. this._reason = reason;
  10387. if (this._onRejected && !onLocalThrow) {
  10388. try {
  10389. this._onRejected(reason);
  10390. this._rejectWasConsumed = true;
  10391. }
  10392. catch (e) {
  10393. reason = e;
  10394. }
  10395. }
  10396. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10397. var child = _a[_i];
  10398. if (this._rejectWasConsumed) {
  10399. child._resolve(null);
  10400. }
  10401. else {
  10402. child._reject(reason);
  10403. }
  10404. }
  10405. this._children.length = 0;
  10406. delete this._onFulfilled;
  10407. delete this._onRejected;
  10408. };
  10409. InternalPromise.resolve = function (value) {
  10410. var newPromise = new InternalPromise();
  10411. newPromise._resolve(value);
  10412. return newPromise;
  10413. };
  10414. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10415. promise.then(function (value) {
  10416. agregator.results[index] = value;
  10417. agregator.count++;
  10418. if (agregator.count === agregator.target) {
  10419. agregator.rootPromise._resolve(agregator.results);
  10420. }
  10421. return null;
  10422. }, function (reason) {
  10423. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10424. agregator.rootPromise._reject(reason);
  10425. }
  10426. });
  10427. };
  10428. InternalPromise.all = function (promises) {
  10429. var newPromise = new InternalPromise();
  10430. var agregator = new FulFillmentAgregator();
  10431. agregator.target = promises.length;
  10432. agregator.rootPromise = newPromise;
  10433. if (promises.length) {
  10434. for (var index = 0; index < promises.length; index++) {
  10435. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10436. }
  10437. }
  10438. else {
  10439. newPromise._resolve([]);
  10440. }
  10441. return newPromise;
  10442. };
  10443. InternalPromise.race = function (promises) {
  10444. var newPromise = new InternalPromise();
  10445. if (promises.length) {
  10446. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10447. var promise = promises_1[_i];
  10448. promise.then(function (value) {
  10449. if (newPromise) {
  10450. newPromise._resolve(value);
  10451. newPromise = null;
  10452. }
  10453. return null;
  10454. }, function (reason) {
  10455. if (newPromise) {
  10456. newPromise._reject(reason);
  10457. newPromise = null;
  10458. }
  10459. });
  10460. }
  10461. }
  10462. return newPromise;
  10463. };
  10464. return InternalPromise;
  10465. }());
  10466. /**
  10467. * Helper class that provides a small promise polyfill
  10468. */
  10469. var PromisePolyfill = /** @class */ (function () {
  10470. function PromisePolyfill() {
  10471. }
  10472. /**
  10473. * Static function used to check if the polyfill is required
  10474. * If this is the case then the function will inject the polyfill to window.Promise
  10475. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10476. */
  10477. PromisePolyfill.Apply = function (force) {
  10478. if (force === void 0) { force = false; }
  10479. if (force || typeof Promise === 'undefined') {
  10480. var root = window;
  10481. root.Promise = InternalPromise;
  10482. }
  10483. };
  10484. return PromisePolyfill;
  10485. }());
  10486. BABYLON.PromisePolyfill = PromisePolyfill;
  10487. })(BABYLON || (BABYLON = {}));
  10488. //# sourceMappingURL=babylon.promise.js.map
  10489. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10490. var BABYLON;
  10491. (function (BABYLON) {
  10492. /**
  10493. * Helper class to push actions to a pool of workers.
  10494. */
  10495. var WorkerPool = /** @class */ (function () {
  10496. /**
  10497. * Constructor
  10498. * @param workers Array of workers to use for actions
  10499. */
  10500. function WorkerPool(workers) {
  10501. this._pendingActions = new Array();
  10502. this._workerInfos = workers.map(function (worker) { return ({
  10503. worker: worker,
  10504. active: false
  10505. }); });
  10506. }
  10507. /**
  10508. * Terminates all workers and clears any pending actions.
  10509. */
  10510. WorkerPool.prototype.dispose = function () {
  10511. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10512. var workerInfo = _a[_i];
  10513. workerInfo.worker.terminate();
  10514. }
  10515. delete this._workerInfos;
  10516. delete this._pendingActions;
  10517. };
  10518. /**
  10519. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10520. * pended until a worker has completed its action.
  10521. * @param action The action to perform. Call onComplete when the action is complete.
  10522. */
  10523. WorkerPool.prototype.push = function (action) {
  10524. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10525. var workerInfo = _a[_i];
  10526. if (!workerInfo.active) {
  10527. this._execute(workerInfo, action);
  10528. return;
  10529. }
  10530. }
  10531. this._pendingActions.push(action);
  10532. };
  10533. WorkerPool.prototype._execute = function (workerInfo, action) {
  10534. var _this = this;
  10535. workerInfo.active = true;
  10536. action(workerInfo.worker, function () {
  10537. workerInfo.active = false;
  10538. var nextAction = _this._pendingActions.shift();
  10539. if (nextAction) {
  10540. _this._execute(workerInfo, nextAction);
  10541. }
  10542. });
  10543. };
  10544. return WorkerPool;
  10545. }());
  10546. BABYLON.WorkerPool = WorkerPool;
  10547. })(BABYLON || (BABYLON = {}));
  10548. //# sourceMappingURL=babylon.workerPool.js.map
  10549. var BABYLON;
  10550. (function (BABYLON) {
  10551. /**
  10552. * @hidden
  10553. **/
  10554. var _AlphaState = /** @class */ (function () {
  10555. /**
  10556. * Initializes the state.
  10557. */
  10558. function _AlphaState() {
  10559. this._isAlphaBlendDirty = false;
  10560. this._isBlendFunctionParametersDirty = false;
  10561. this._isBlendEquationParametersDirty = false;
  10562. this._isBlendConstantsDirty = false;
  10563. this._alphaBlend = false;
  10564. this._blendFunctionParameters = new Array(4);
  10565. this._blendEquationParameters = new Array(2);
  10566. this._blendConstants = new Array(4);
  10567. this.reset();
  10568. }
  10569. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10570. get: function () {
  10571. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10572. },
  10573. enumerable: true,
  10574. configurable: true
  10575. });
  10576. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10577. get: function () {
  10578. return this._alphaBlend;
  10579. },
  10580. set: function (value) {
  10581. if (this._alphaBlend === value) {
  10582. return;
  10583. }
  10584. this._alphaBlend = value;
  10585. this._isAlphaBlendDirty = true;
  10586. },
  10587. enumerable: true,
  10588. configurable: true
  10589. });
  10590. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10591. if (this._blendConstants[0] === r &&
  10592. this._blendConstants[1] === g &&
  10593. this._blendConstants[2] === b &&
  10594. this._blendConstants[3] === a) {
  10595. return;
  10596. }
  10597. this._blendConstants[0] = r;
  10598. this._blendConstants[1] = g;
  10599. this._blendConstants[2] = b;
  10600. this._blendConstants[3] = a;
  10601. this._isBlendConstantsDirty = true;
  10602. };
  10603. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10604. if (this._blendFunctionParameters[0] === value0 &&
  10605. this._blendFunctionParameters[1] === value1 &&
  10606. this._blendFunctionParameters[2] === value2 &&
  10607. this._blendFunctionParameters[3] === value3) {
  10608. return;
  10609. }
  10610. this._blendFunctionParameters[0] = value0;
  10611. this._blendFunctionParameters[1] = value1;
  10612. this._blendFunctionParameters[2] = value2;
  10613. this._blendFunctionParameters[3] = value3;
  10614. this._isBlendFunctionParametersDirty = true;
  10615. };
  10616. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10617. if (this._blendEquationParameters[0] === rgb &&
  10618. this._blendEquationParameters[1] === alpha) {
  10619. return;
  10620. }
  10621. this._blendEquationParameters[0] = rgb;
  10622. this._blendEquationParameters[1] = alpha;
  10623. this._isBlendEquationParametersDirty = true;
  10624. };
  10625. _AlphaState.prototype.reset = function () {
  10626. this._alphaBlend = false;
  10627. this._blendFunctionParameters[0] = null;
  10628. this._blendFunctionParameters[1] = null;
  10629. this._blendFunctionParameters[2] = null;
  10630. this._blendFunctionParameters[3] = null;
  10631. this._blendEquationParameters[0] = null;
  10632. this._blendEquationParameters[1] = null;
  10633. this._blendConstants[0] = null;
  10634. this._blendConstants[1] = null;
  10635. this._blendConstants[2] = null;
  10636. this._blendConstants[3] = null;
  10637. this._isAlphaBlendDirty = true;
  10638. this._isBlendFunctionParametersDirty = false;
  10639. this._isBlendEquationParametersDirty = false;
  10640. this._isBlendConstantsDirty = false;
  10641. };
  10642. _AlphaState.prototype.apply = function (gl) {
  10643. if (!this.isDirty) {
  10644. return;
  10645. }
  10646. // Alpha blend
  10647. if (this._isAlphaBlendDirty) {
  10648. if (this._alphaBlend) {
  10649. gl.enable(gl.BLEND);
  10650. }
  10651. else {
  10652. gl.disable(gl.BLEND);
  10653. }
  10654. this._isAlphaBlendDirty = false;
  10655. }
  10656. // Alpha function
  10657. if (this._isBlendFunctionParametersDirty) {
  10658. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10659. this._isBlendFunctionParametersDirty = false;
  10660. }
  10661. // Alpha equation
  10662. if (this._isBlendEquationParametersDirty) {
  10663. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10664. this._isBlendEquationParametersDirty = false;
  10665. }
  10666. // Constants
  10667. if (this._isBlendConstantsDirty) {
  10668. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10669. this._isBlendConstantsDirty = false;
  10670. }
  10671. };
  10672. return _AlphaState;
  10673. }());
  10674. BABYLON._AlphaState = _AlphaState;
  10675. })(BABYLON || (BABYLON = {}));
  10676. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10677. var BABYLON;
  10678. (function (BABYLON) {
  10679. /**
  10680. * @hidden
  10681. **/
  10682. var _DepthCullingState = /** @class */ (function () {
  10683. /**
  10684. * Initializes the state.
  10685. */
  10686. function _DepthCullingState() {
  10687. this._isDepthTestDirty = false;
  10688. this._isDepthMaskDirty = false;
  10689. this._isDepthFuncDirty = false;
  10690. this._isCullFaceDirty = false;
  10691. this._isCullDirty = false;
  10692. this._isZOffsetDirty = false;
  10693. this._isFrontFaceDirty = false;
  10694. this.reset();
  10695. }
  10696. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10697. get: function () {
  10698. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10699. },
  10700. enumerable: true,
  10701. configurable: true
  10702. });
  10703. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10704. get: function () {
  10705. return this._zOffset;
  10706. },
  10707. set: function (value) {
  10708. if (this._zOffset === value) {
  10709. return;
  10710. }
  10711. this._zOffset = value;
  10712. this._isZOffsetDirty = true;
  10713. },
  10714. enumerable: true,
  10715. configurable: true
  10716. });
  10717. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10718. get: function () {
  10719. return this._cullFace;
  10720. },
  10721. set: function (value) {
  10722. if (this._cullFace === value) {
  10723. return;
  10724. }
  10725. this._cullFace = value;
  10726. this._isCullFaceDirty = true;
  10727. },
  10728. enumerable: true,
  10729. configurable: true
  10730. });
  10731. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10732. get: function () {
  10733. return this._cull;
  10734. },
  10735. set: function (value) {
  10736. if (this._cull === value) {
  10737. return;
  10738. }
  10739. this._cull = value;
  10740. this._isCullDirty = true;
  10741. },
  10742. enumerable: true,
  10743. configurable: true
  10744. });
  10745. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10746. get: function () {
  10747. return this._depthFunc;
  10748. },
  10749. set: function (value) {
  10750. if (this._depthFunc === value) {
  10751. return;
  10752. }
  10753. this._depthFunc = value;
  10754. this._isDepthFuncDirty = true;
  10755. },
  10756. enumerable: true,
  10757. configurable: true
  10758. });
  10759. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10760. get: function () {
  10761. return this._depthMask;
  10762. },
  10763. set: function (value) {
  10764. if (this._depthMask === value) {
  10765. return;
  10766. }
  10767. this._depthMask = value;
  10768. this._isDepthMaskDirty = true;
  10769. },
  10770. enumerable: true,
  10771. configurable: true
  10772. });
  10773. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10774. get: function () {
  10775. return this._depthTest;
  10776. },
  10777. set: function (value) {
  10778. if (this._depthTest === value) {
  10779. return;
  10780. }
  10781. this._depthTest = value;
  10782. this._isDepthTestDirty = true;
  10783. },
  10784. enumerable: true,
  10785. configurable: true
  10786. });
  10787. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10788. get: function () {
  10789. return this._frontFace;
  10790. },
  10791. set: function (value) {
  10792. if (this._frontFace === value) {
  10793. return;
  10794. }
  10795. this._frontFace = value;
  10796. this._isFrontFaceDirty = true;
  10797. },
  10798. enumerable: true,
  10799. configurable: true
  10800. });
  10801. _DepthCullingState.prototype.reset = function () {
  10802. this._depthMask = true;
  10803. this._depthTest = true;
  10804. this._depthFunc = null;
  10805. this._cullFace = null;
  10806. this._cull = null;
  10807. this._zOffset = 0;
  10808. this._frontFace = null;
  10809. this._isDepthTestDirty = true;
  10810. this._isDepthMaskDirty = true;
  10811. this._isDepthFuncDirty = false;
  10812. this._isCullFaceDirty = false;
  10813. this._isCullDirty = false;
  10814. this._isZOffsetDirty = false;
  10815. this._isFrontFaceDirty = false;
  10816. };
  10817. _DepthCullingState.prototype.apply = function (gl) {
  10818. if (!this.isDirty) {
  10819. return;
  10820. }
  10821. // Cull
  10822. if (this._isCullDirty) {
  10823. if (this.cull) {
  10824. gl.enable(gl.CULL_FACE);
  10825. }
  10826. else {
  10827. gl.disable(gl.CULL_FACE);
  10828. }
  10829. this._isCullDirty = false;
  10830. }
  10831. // Cull face
  10832. if (this._isCullFaceDirty) {
  10833. gl.cullFace(this.cullFace);
  10834. this._isCullFaceDirty = false;
  10835. }
  10836. // Depth mask
  10837. if (this._isDepthMaskDirty) {
  10838. gl.depthMask(this.depthMask);
  10839. this._isDepthMaskDirty = false;
  10840. }
  10841. // Depth test
  10842. if (this._isDepthTestDirty) {
  10843. if (this.depthTest) {
  10844. gl.enable(gl.DEPTH_TEST);
  10845. }
  10846. else {
  10847. gl.disable(gl.DEPTH_TEST);
  10848. }
  10849. this._isDepthTestDirty = false;
  10850. }
  10851. // Depth func
  10852. if (this._isDepthFuncDirty) {
  10853. gl.depthFunc(this.depthFunc);
  10854. this._isDepthFuncDirty = false;
  10855. }
  10856. // zOffset
  10857. if (this._isZOffsetDirty) {
  10858. if (this.zOffset) {
  10859. gl.enable(gl.POLYGON_OFFSET_FILL);
  10860. gl.polygonOffset(this.zOffset, 0);
  10861. }
  10862. else {
  10863. gl.disable(gl.POLYGON_OFFSET_FILL);
  10864. }
  10865. this._isZOffsetDirty = false;
  10866. }
  10867. // Front face
  10868. if (this._isFrontFaceDirty) {
  10869. gl.frontFace(this.frontFace);
  10870. this._isFrontFaceDirty = false;
  10871. }
  10872. };
  10873. return _DepthCullingState;
  10874. }());
  10875. BABYLON._DepthCullingState = _DepthCullingState;
  10876. })(BABYLON || (BABYLON = {}));
  10877. //# sourceMappingURL=babylon.depthCullingState.js.map
  10878. var BABYLON;
  10879. (function (BABYLON) {
  10880. /**
  10881. * @hidden
  10882. **/
  10883. var _StencilState = /** @class */ (function () {
  10884. function _StencilState() {
  10885. this._isStencilTestDirty = false;
  10886. this._isStencilMaskDirty = false;
  10887. this._isStencilFuncDirty = false;
  10888. this._isStencilOpDirty = false;
  10889. this.reset();
  10890. }
  10891. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10892. get: function () {
  10893. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10894. },
  10895. enumerable: true,
  10896. configurable: true
  10897. });
  10898. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10899. get: function () {
  10900. return this._stencilFunc;
  10901. },
  10902. set: function (value) {
  10903. if (this._stencilFunc === value) {
  10904. return;
  10905. }
  10906. this._stencilFunc = value;
  10907. this._isStencilFuncDirty = true;
  10908. },
  10909. enumerable: true,
  10910. configurable: true
  10911. });
  10912. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10913. get: function () {
  10914. return this._stencilFuncRef;
  10915. },
  10916. set: function (value) {
  10917. if (this._stencilFuncRef === value) {
  10918. return;
  10919. }
  10920. this._stencilFuncRef = value;
  10921. this._isStencilFuncDirty = true;
  10922. },
  10923. enumerable: true,
  10924. configurable: true
  10925. });
  10926. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10927. get: function () {
  10928. return this._stencilFuncMask;
  10929. },
  10930. set: function (value) {
  10931. if (this._stencilFuncMask === value) {
  10932. return;
  10933. }
  10934. this._stencilFuncMask = value;
  10935. this._isStencilFuncDirty = true;
  10936. },
  10937. enumerable: true,
  10938. configurable: true
  10939. });
  10940. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10941. get: function () {
  10942. return this._stencilOpStencilFail;
  10943. },
  10944. set: function (value) {
  10945. if (this._stencilOpStencilFail === value) {
  10946. return;
  10947. }
  10948. this._stencilOpStencilFail = value;
  10949. this._isStencilOpDirty = true;
  10950. },
  10951. enumerable: true,
  10952. configurable: true
  10953. });
  10954. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10955. get: function () {
  10956. return this._stencilOpDepthFail;
  10957. },
  10958. set: function (value) {
  10959. if (this._stencilOpDepthFail === value) {
  10960. return;
  10961. }
  10962. this._stencilOpDepthFail = value;
  10963. this._isStencilOpDirty = true;
  10964. },
  10965. enumerable: true,
  10966. configurable: true
  10967. });
  10968. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10969. get: function () {
  10970. return this._stencilOpStencilDepthPass;
  10971. },
  10972. set: function (value) {
  10973. if (this._stencilOpStencilDepthPass === value) {
  10974. return;
  10975. }
  10976. this._stencilOpStencilDepthPass = value;
  10977. this._isStencilOpDirty = true;
  10978. },
  10979. enumerable: true,
  10980. configurable: true
  10981. });
  10982. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10983. get: function () {
  10984. return this._stencilMask;
  10985. },
  10986. set: function (value) {
  10987. if (this._stencilMask === value) {
  10988. return;
  10989. }
  10990. this._stencilMask = value;
  10991. this._isStencilMaskDirty = true;
  10992. },
  10993. enumerable: true,
  10994. configurable: true
  10995. });
  10996. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10997. get: function () {
  10998. return this._stencilTest;
  10999. },
  11000. set: function (value) {
  11001. if (this._stencilTest === value) {
  11002. return;
  11003. }
  11004. this._stencilTest = value;
  11005. this._isStencilTestDirty = true;
  11006. },
  11007. enumerable: true,
  11008. configurable: true
  11009. });
  11010. _StencilState.prototype.reset = function () {
  11011. this._stencilTest = false;
  11012. this._stencilMask = 0xFF;
  11013. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11014. this._stencilFuncRef = 1;
  11015. this._stencilFuncMask = 0xFF;
  11016. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11017. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11018. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11019. this._isStencilTestDirty = true;
  11020. this._isStencilMaskDirty = true;
  11021. this._isStencilFuncDirty = true;
  11022. this._isStencilOpDirty = true;
  11023. };
  11024. _StencilState.prototype.apply = function (gl) {
  11025. if (!this.isDirty) {
  11026. return;
  11027. }
  11028. // Stencil test
  11029. if (this._isStencilTestDirty) {
  11030. if (this.stencilTest) {
  11031. gl.enable(gl.STENCIL_TEST);
  11032. }
  11033. else {
  11034. gl.disable(gl.STENCIL_TEST);
  11035. }
  11036. this._isStencilTestDirty = false;
  11037. }
  11038. // Stencil mask
  11039. if (this._isStencilMaskDirty) {
  11040. gl.stencilMask(this.stencilMask);
  11041. this._isStencilMaskDirty = false;
  11042. }
  11043. // Stencil func
  11044. if (this._isStencilFuncDirty) {
  11045. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11046. this._isStencilFuncDirty = false;
  11047. }
  11048. // Stencil op
  11049. if (this._isStencilOpDirty) {
  11050. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11051. this._isStencilOpDirty = false;
  11052. }
  11053. };
  11054. return _StencilState;
  11055. }());
  11056. BABYLON._StencilState = _StencilState;
  11057. })(BABYLON || (BABYLON = {}));
  11058. //# sourceMappingURL=babylon.stencilState.js.map
  11059. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11060. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11061. s = arguments[i];
  11062. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11063. t[p] = s[p];
  11064. }
  11065. return t;
  11066. };
  11067. var BABYLON;
  11068. (function (BABYLON) {
  11069. var compileShader = function (gl, source, type, defines, shaderVersion) {
  11070. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  11071. };
  11072. var compileRawShader = function (gl, source, type) {
  11073. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  11074. gl.shaderSource(shader, source);
  11075. gl.compileShader(shader);
  11076. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  11077. var log = gl.getShaderInfoLog(shader);
  11078. if (log) {
  11079. throw new Error(log);
  11080. }
  11081. }
  11082. if (!shader) {
  11083. throw new Error("Something went wrong while compile the shader.");
  11084. }
  11085. return shader;
  11086. };
  11087. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11088. var magFilter = gl.NEAREST;
  11089. var minFilter = gl.NEAREST;
  11090. switch (samplingMode) {
  11091. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11092. magFilter = gl.LINEAR;
  11093. if (generateMipMaps) {
  11094. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11095. }
  11096. else {
  11097. minFilter = gl.LINEAR;
  11098. }
  11099. break;
  11100. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11101. magFilter = gl.LINEAR;
  11102. if (generateMipMaps) {
  11103. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11104. }
  11105. else {
  11106. minFilter = gl.LINEAR;
  11107. }
  11108. break;
  11109. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11110. magFilter = gl.NEAREST;
  11111. if (generateMipMaps) {
  11112. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11113. }
  11114. else {
  11115. minFilter = gl.NEAREST;
  11116. }
  11117. break;
  11118. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11119. magFilter = gl.NEAREST;
  11120. if (generateMipMaps) {
  11121. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11122. }
  11123. else {
  11124. minFilter = gl.NEAREST;
  11125. }
  11126. break;
  11127. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11128. magFilter = gl.NEAREST;
  11129. if (generateMipMaps) {
  11130. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11131. }
  11132. else {
  11133. minFilter = gl.LINEAR;
  11134. }
  11135. break;
  11136. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11137. magFilter = gl.NEAREST;
  11138. if (generateMipMaps) {
  11139. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11140. }
  11141. else {
  11142. minFilter = gl.LINEAR;
  11143. }
  11144. break;
  11145. case BABYLON.Texture.NEAREST_LINEAR:
  11146. magFilter = gl.NEAREST;
  11147. minFilter = gl.LINEAR;
  11148. break;
  11149. case BABYLON.Texture.NEAREST_NEAREST:
  11150. magFilter = gl.NEAREST;
  11151. minFilter = gl.NEAREST;
  11152. break;
  11153. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11154. magFilter = gl.LINEAR;
  11155. if (generateMipMaps) {
  11156. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11157. }
  11158. else {
  11159. minFilter = gl.NEAREST;
  11160. }
  11161. break;
  11162. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11163. magFilter = gl.LINEAR;
  11164. if (generateMipMaps) {
  11165. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11166. }
  11167. else {
  11168. minFilter = gl.NEAREST;
  11169. }
  11170. break;
  11171. case BABYLON.Texture.LINEAR_LINEAR:
  11172. magFilter = gl.LINEAR;
  11173. minFilter = gl.LINEAR;
  11174. break;
  11175. case BABYLON.Texture.LINEAR_NEAREST:
  11176. magFilter = gl.LINEAR;
  11177. minFilter = gl.NEAREST;
  11178. break;
  11179. }
  11180. return {
  11181. min: minFilter,
  11182. mag: magFilter
  11183. };
  11184. };
  11185. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11186. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11187. var img;
  11188. var onload = function () {
  11189. loadedImages[index] = img;
  11190. loadedImages._internalCount++;
  11191. if (scene) {
  11192. scene._removePendingData(img);
  11193. }
  11194. if (loadedImages._internalCount === 6) {
  11195. onfinish(loadedImages);
  11196. }
  11197. };
  11198. var onerror = function (message, exception) {
  11199. if (scene) {
  11200. scene._removePendingData(img);
  11201. }
  11202. if (onErrorCallBack) {
  11203. onErrorCallBack(message, exception);
  11204. }
  11205. };
  11206. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11207. if (scene) {
  11208. scene._addPendingData(img);
  11209. }
  11210. };
  11211. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11212. if (onError === void 0) { onError = null; }
  11213. var loadedImages = [];
  11214. loadedImages._internalCount = 0;
  11215. for (var index = 0; index < 6; index++) {
  11216. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11217. }
  11218. };
  11219. var BufferPointer = /** @class */ (function () {
  11220. function BufferPointer() {
  11221. }
  11222. return BufferPointer;
  11223. }());
  11224. /**
  11225. * Interface for attribute information associated with buffer instanciation
  11226. */
  11227. var InstancingAttributeInfo = /** @class */ (function () {
  11228. function InstancingAttributeInfo() {
  11229. }
  11230. return InstancingAttributeInfo;
  11231. }());
  11232. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11233. /**
  11234. * Define options used to create a render target texture
  11235. */
  11236. var RenderTargetCreationOptions = /** @class */ (function () {
  11237. function RenderTargetCreationOptions() {
  11238. }
  11239. return RenderTargetCreationOptions;
  11240. }());
  11241. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11242. /**
  11243. * Define options used to create a depth texture
  11244. */
  11245. var DepthTextureCreationOptions = /** @class */ (function () {
  11246. function DepthTextureCreationOptions() {
  11247. }
  11248. return DepthTextureCreationOptions;
  11249. }());
  11250. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11251. /**
  11252. * Class used to describe the capabilities of the engine relatively to the current browser
  11253. */
  11254. var EngineCapabilities = /** @class */ (function () {
  11255. function EngineCapabilities() {
  11256. }
  11257. return EngineCapabilities;
  11258. }());
  11259. BABYLON.EngineCapabilities = EngineCapabilities;
  11260. /**
  11261. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11262. */
  11263. var Engine = /** @class */ (function () {
  11264. /**
  11265. * Creates a new engine
  11266. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11267. * @param antialias defines enable antialiasing (default: false)
  11268. * @param options defines further options to be sent to the getContext() function
  11269. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11270. */
  11271. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11272. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11273. var _this = this;
  11274. // Public members
  11275. /**
  11276. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11277. */
  11278. this.forcePOTTextures = false;
  11279. /**
  11280. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11281. */
  11282. this.isFullscreen = false;
  11283. /**
  11284. * Gets a boolean indicating if the pointer is currently locked
  11285. */
  11286. this.isPointerLock = false;
  11287. /**
  11288. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11289. */
  11290. this.cullBackFaces = true;
  11291. /**
  11292. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11293. */
  11294. this.renderEvenInBackground = true;
  11295. /**
  11296. * Gets or sets a boolean indicating that cache can be kept between frames
  11297. */
  11298. this.preventCacheWipeBetweenFrames = false;
  11299. /**
  11300. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11301. **/
  11302. this.enableOfflineSupport = false;
  11303. /**
  11304. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
  11305. **/
  11306. this.disableManifestCheck = false;
  11307. /**
  11308. * Gets the list of created scenes
  11309. */
  11310. this.scenes = new Array();
  11311. /**
  11312. * Gets the list of created postprocesses
  11313. */
  11314. this.postProcesses = new Array();
  11315. // Observables
  11316. /**
  11317. * Observable event triggered each time the rendering canvas is resized
  11318. */
  11319. this.onResizeObservable = new BABYLON.Observable();
  11320. /**
  11321. * Observable event triggered each time the canvas loses focus
  11322. */
  11323. this.onCanvasBlurObservable = new BABYLON.Observable();
  11324. /**
  11325. * Observable event triggered each time the canvas gains focus
  11326. */
  11327. this.onCanvasFocusObservable = new BABYLON.Observable();
  11328. /**
  11329. * Observable event triggered each time the canvas receives pointerout event
  11330. */
  11331. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11332. /**
  11333. * Observable event triggered before each texture is initialized
  11334. */
  11335. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11336. //WebVR
  11337. this._vrDisplay = undefined;
  11338. this._vrSupported = false;
  11339. this._vrExclusivePointerMode = false;
  11340. // Uniform buffers list
  11341. /**
  11342. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11343. */
  11344. this.disableUniformBuffers = false;
  11345. /** @hidden */
  11346. this._uniformBuffers = new Array();
  11347. // Observables
  11348. /**
  11349. * Observable raised when the engine begins a new frame
  11350. */
  11351. this.onBeginFrameObservable = new BABYLON.Observable();
  11352. /**
  11353. * Observable raised when the engine ends the current frame
  11354. */
  11355. this.onEndFrameObservable = new BABYLON.Observable();
  11356. /**
  11357. * Observable raised when the engine is about to compile a shader
  11358. */
  11359. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11360. /**
  11361. * Observable raised when the engine has jsut compiled a shader
  11362. */
  11363. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11364. this._windowIsBackground = false;
  11365. this._webGLVersion = 1.0;
  11366. /** @hidden */
  11367. this._badOS = false;
  11368. /** @hidden */
  11369. this._badDesktopOS = false;
  11370. /**
  11371. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11372. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11373. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11374. */
  11375. this.disableTextureBindingOptimization = false;
  11376. /**
  11377. * Observable signaled when VR display mode changes
  11378. */
  11379. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11380. /**
  11381. * Observable signaled when VR request present is complete
  11382. */
  11383. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11384. /**
  11385. * Observable signaled when VR request present starts
  11386. */
  11387. this.onVRRequestPresentStart = new BABYLON.Observable();
  11388. this._colorWrite = true;
  11389. /** @hidden */
  11390. this._drawCalls = new BABYLON.PerfCounter();
  11391. /** @hidden */
  11392. this._textureCollisions = new BABYLON.PerfCounter();
  11393. this._renderingQueueLaunched = false;
  11394. this._activeRenderLoops = new Array();
  11395. // Deterministic lockstepMaxSteps
  11396. this._deterministicLockstep = false;
  11397. this._lockstepMaxSteps = 4;
  11398. // Lost context
  11399. /**
  11400. * Observable signaled when a context lost event is raised
  11401. */
  11402. this.onContextLostObservable = new BABYLON.Observable();
  11403. /**
  11404. * Observable signaled when a context restored event is raised
  11405. */
  11406. this.onContextRestoredObservable = new BABYLON.Observable();
  11407. this._contextWasLost = false;
  11408. this._doNotHandleContextLost = false;
  11409. // FPS
  11410. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11411. this._fps = 60;
  11412. this._deltaTime = 0;
  11413. /**
  11414. * Turn this value on if you want to pause FPS computation when in background
  11415. */
  11416. this.disablePerformanceMonitorInBackground = false;
  11417. // States
  11418. /** @hidden */
  11419. this._depthCullingState = new BABYLON._DepthCullingState();
  11420. /** @hidden */
  11421. this._stencilState = new BABYLON._StencilState();
  11422. /** @hidden */
  11423. this._alphaState = new BABYLON._AlphaState();
  11424. /** @hidden */
  11425. this._alphaMode = Engine.ALPHA_DISABLE;
  11426. // Cache
  11427. this._internalTexturesCache = new Array();
  11428. /** @hidden */
  11429. this._activeChannel = 0;
  11430. this._currentTextureChannel = -1;
  11431. /** @hidden */
  11432. this._boundTexturesCache = {};
  11433. this._compiledEffects = {};
  11434. this._vertexAttribArraysEnabled = [];
  11435. this._uintIndicesCurrentlySet = false;
  11436. this._currentBoundBuffer = new Array();
  11437. this._currentBufferPointers = new Array();
  11438. this._currentInstanceLocations = new Array();
  11439. this._currentInstanceBuffers = new Array();
  11440. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11441. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11442. this._vaoRecordInProgress = false;
  11443. this._mustWipeVertexAttributes = false;
  11444. this._nextFreeTextureSlots = new Array();
  11445. this._maxSimultaneousTextures = 0;
  11446. this._activeRequests = new Array();
  11447. // Hardware supported Compressed Textures
  11448. this._texturesSupported = new Array();
  11449. this._onVRFullScreenTriggered = function () {
  11450. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11451. //get the old size before we change
  11452. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11453. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11454. //get the width and height, change the render size
  11455. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11456. _this.setHardwareScalingLevel(1);
  11457. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11458. }
  11459. else {
  11460. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11461. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11462. }
  11463. };
  11464. this._boundUniforms = {};
  11465. // Register promises
  11466. BABYLON.PromisePolyfill.Apply();
  11467. var canvas = null;
  11468. Engine.Instances.push(this);
  11469. if (!canvasOrContext) {
  11470. return;
  11471. }
  11472. options = options || {};
  11473. if (canvasOrContext.getContext) {
  11474. canvas = canvasOrContext;
  11475. this._renderingCanvas = canvas;
  11476. if (antialias != null) {
  11477. options.antialias = antialias;
  11478. }
  11479. if (options.deterministicLockstep === undefined) {
  11480. options.deterministicLockstep = false;
  11481. }
  11482. if (options.lockstepMaxSteps === undefined) {
  11483. options.lockstepMaxSteps = 4;
  11484. }
  11485. if (options.preserveDrawingBuffer === undefined) {
  11486. options.preserveDrawingBuffer = false;
  11487. }
  11488. if (options.audioEngine === undefined) {
  11489. options.audioEngine = true;
  11490. }
  11491. if (options.stencil === undefined) {
  11492. options.stencil = true;
  11493. }
  11494. this._deterministicLockstep = options.deterministicLockstep;
  11495. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11496. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11497. // Exceptions
  11498. if (navigator && navigator.userAgent) {
  11499. var ua = navigator.userAgent;
  11500. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11501. var exception = _a[_i];
  11502. var key = exception.key;
  11503. var targets = exception.targets;
  11504. if (ua.indexOf(key) > -1) {
  11505. if (exception.capture && exception.captureConstraint) {
  11506. var capture = exception.capture;
  11507. var constraint = exception.captureConstraint;
  11508. var regex = new RegExp(capture);
  11509. var matches = regex.exec(ua);
  11510. if (matches && matches.length > 0) {
  11511. var capturedValue = parseInt(matches[matches.length - 1]);
  11512. if (capturedValue >= constraint) {
  11513. continue;
  11514. }
  11515. }
  11516. }
  11517. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11518. var target = targets_1[_b];
  11519. switch (target) {
  11520. case "uniformBuffer":
  11521. this.disableUniformBuffers = true;
  11522. break;
  11523. case "textureBindingOptimization":
  11524. this.disableTextureBindingOptimization = true;
  11525. break;
  11526. }
  11527. }
  11528. }
  11529. }
  11530. }
  11531. // GL
  11532. if (!options.disableWebGL2Support) {
  11533. try {
  11534. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11535. if (this._gl) {
  11536. this._webGLVersion = 2.0;
  11537. }
  11538. }
  11539. catch (e) {
  11540. // Do nothing
  11541. }
  11542. }
  11543. if (!this._gl) {
  11544. if (!canvas) {
  11545. throw new Error("The provided canvas is null or undefined.");
  11546. }
  11547. try {
  11548. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11549. }
  11550. catch (e) {
  11551. throw new Error("WebGL not supported");
  11552. }
  11553. }
  11554. if (!this._gl) {
  11555. throw new Error("WebGL not supported");
  11556. }
  11557. this._onCanvasFocus = function () {
  11558. _this.onCanvasFocusObservable.notifyObservers(_this);
  11559. };
  11560. this._onCanvasBlur = function () {
  11561. _this.onCanvasBlurObservable.notifyObservers(_this);
  11562. };
  11563. canvas.addEventListener("focus", this._onCanvasFocus);
  11564. canvas.addEventListener("blur", this._onCanvasBlur);
  11565. this._onBlur = function () {
  11566. if (_this.disablePerformanceMonitorInBackground) {
  11567. _this._performanceMonitor.disable();
  11568. }
  11569. _this._windowIsBackground = true;
  11570. };
  11571. this._onFocus = function () {
  11572. if (_this.disablePerformanceMonitorInBackground) {
  11573. _this._performanceMonitor.enable();
  11574. }
  11575. _this._windowIsBackground = false;
  11576. };
  11577. this._onCanvasPointerOut = function (ev) {
  11578. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11579. };
  11580. window.addEventListener("blur", this._onBlur);
  11581. window.addEventListener("focus", this._onFocus);
  11582. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11583. // Context lost
  11584. if (!this._doNotHandleContextLost) {
  11585. this._onContextLost = function (evt) {
  11586. evt.preventDefault();
  11587. _this._contextWasLost = true;
  11588. BABYLON.Tools.Warn("WebGL context lost.");
  11589. _this.onContextLostObservable.notifyObservers(_this);
  11590. };
  11591. this._onContextRestored = function (evt) {
  11592. // Adding a timeout to avoid race condition at browser level
  11593. setTimeout(function () {
  11594. // Rebuild gl context
  11595. _this._initGLContext();
  11596. // Rebuild effects
  11597. _this._rebuildEffects();
  11598. // Rebuild textures
  11599. _this._rebuildInternalTextures();
  11600. // Rebuild buffers
  11601. _this._rebuildBuffers();
  11602. // Cache
  11603. _this.wipeCaches(true);
  11604. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11605. _this.onContextRestoredObservable.notifyObservers(_this);
  11606. _this._contextWasLost = false;
  11607. }, 0);
  11608. };
  11609. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11610. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11611. }
  11612. }
  11613. else {
  11614. this._gl = canvasOrContext;
  11615. this._renderingCanvas = this._gl.canvas;
  11616. if (this._gl.renderbufferStorageMultisample) {
  11617. this._webGLVersion = 2.0;
  11618. }
  11619. options.stencil = this._gl.getContextAttributes().stencil;
  11620. }
  11621. // Viewport
  11622. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11623. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11624. this.resize();
  11625. this._isStencilEnable = options.stencil ? true : false;
  11626. this._initGLContext();
  11627. if (canvas) {
  11628. // Fullscreen
  11629. this._onFullscreenChange = function () {
  11630. if (document.fullscreen !== undefined) {
  11631. _this.isFullscreen = document.fullscreen;
  11632. }
  11633. else if (document.mozFullScreen !== undefined) {
  11634. _this.isFullscreen = document.mozFullScreen;
  11635. }
  11636. else if (document.webkitIsFullScreen !== undefined) {
  11637. _this.isFullscreen = document.webkitIsFullScreen;
  11638. }
  11639. else if (document.msIsFullScreen !== undefined) {
  11640. _this.isFullscreen = document.msIsFullScreen;
  11641. }
  11642. // Pointer lock
  11643. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11644. canvas.requestPointerLock = canvas.requestPointerLock ||
  11645. canvas.msRequestPointerLock ||
  11646. canvas.mozRequestPointerLock ||
  11647. canvas.webkitRequestPointerLock;
  11648. if (canvas.requestPointerLock) {
  11649. canvas.requestPointerLock();
  11650. }
  11651. }
  11652. };
  11653. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11654. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11655. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11656. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11657. // Pointer lock
  11658. this._onPointerLockChange = function () {
  11659. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11660. document.webkitPointerLockElement === canvas ||
  11661. document.msPointerLockElement === canvas ||
  11662. document.pointerLockElement === canvas);
  11663. };
  11664. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11665. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11666. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11667. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11668. this._onVRDisplayPointerRestricted = function () {
  11669. if (canvas) {
  11670. canvas.requestPointerLock();
  11671. }
  11672. };
  11673. this._onVRDisplayPointerUnrestricted = function () {
  11674. document.exitPointerLock();
  11675. };
  11676. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11677. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11678. }
  11679. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11680. Engine.audioEngine = new BABYLON.AudioEngine();
  11681. }
  11682. // Prepare buffer pointers
  11683. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11684. this._currentBufferPointers[i] = new BufferPointer();
  11685. }
  11686. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11687. // Load WebVR Devices
  11688. if (options.autoEnableWebVR) {
  11689. this.initWebVR();
  11690. }
  11691. // Detect if we are running on a faulty buggy OS.
  11692. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11693. // Detect if we are running on a faulty buggy desktop OS.
  11694. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11695. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11696. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11697. }
  11698. Object.defineProperty(Engine, "LastCreatedEngine", {
  11699. /**
  11700. * Gets the latest created engine
  11701. */
  11702. get: function () {
  11703. if (Engine.Instances.length === 0) {
  11704. return null;
  11705. }
  11706. return Engine.Instances[Engine.Instances.length - 1];
  11707. },
  11708. enumerable: true,
  11709. configurable: true
  11710. });
  11711. Object.defineProperty(Engine, "LastCreatedScene", {
  11712. /**
  11713. * Gets the latest created scene
  11714. */
  11715. get: function () {
  11716. var lastCreatedEngine = Engine.LastCreatedEngine;
  11717. if (!lastCreatedEngine) {
  11718. return null;
  11719. }
  11720. if (lastCreatedEngine.scenes.length === 0) {
  11721. return null;
  11722. }
  11723. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11724. },
  11725. enumerable: true,
  11726. configurable: true
  11727. });
  11728. /**
  11729. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11730. * @param flag defines which part of the materials must be marked as dirty
  11731. * @param predicate defines a predicate used to filter which materials should be affected
  11732. */
  11733. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11734. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11735. var engine = Engine.Instances[engineIndex];
  11736. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11737. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11738. }
  11739. }
  11740. };
  11741. Object.defineProperty(Engine, "NEVER", {
  11742. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11743. get: function () {
  11744. return Engine._NEVER;
  11745. },
  11746. enumerable: true,
  11747. configurable: true
  11748. });
  11749. Object.defineProperty(Engine, "ALWAYS", {
  11750. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */
  11751. get: function () {
  11752. return Engine._ALWAYS;
  11753. },
  11754. enumerable: true,
  11755. configurable: true
  11756. });
  11757. Object.defineProperty(Engine, "LESS", {
  11758. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11759. get: function () {
  11760. return Engine._LESS;
  11761. },
  11762. enumerable: true,
  11763. configurable: true
  11764. });
  11765. Object.defineProperty(Engine, "EQUAL", {
  11766. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11767. get: function () {
  11768. return Engine._EQUAL;
  11769. },
  11770. enumerable: true,
  11771. configurable: true
  11772. });
  11773. Object.defineProperty(Engine, "LEQUAL", {
  11774. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value */
  11775. get: function () {
  11776. return Engine._LEQUAL;
  11777. },
  11778. enumerable: true,
  11779. configurable: true
  11780. });
  11781. Object.defineProperty(Engine, "GREATER", {
  11782. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11783. get: function () {
  11784. return Engine._GREATER;
  11785. },
  11786. enumerable: true,
  11787. configurable: true
  11788. });
  11789. Object.defineProperty(Engine, "GEQUAL", {
  11790. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value */
  11791. get: function () {
  11792. return Engine._GEQUAL;
  11793. },
  11794. enumerable: true,
  11795. configurable: true
  11796. });
  11797. Object.defineProperty(Engine, "NOTEQUAL", {
  11798. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value */
  11799. get: function () {
  11800. return Engine._NOTEQUAL;
  11801. },
  11802. enumerable: true,
  11803. configurable: true
  11804. });
  11805. Object.defineProperty(Engine, "KEEP", {
  11806. /** Passed to stencilOperation to specify that stencil value must be kept */
  11807. get: function () {
  11808. return Engine._KEEP;
  11809. },
  11810. enumerable: true,
  11811. configurable: true
  11812. });
  11813. Object.defineProperty(Engine, "REPLACE", {
  11814. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11815. get: function () {
  11816. return Engine._REPLACE;
  11817. },
  11818. enumerable: true,
  11819. configurable: true
  11820. });
  11821. Object.defineProperty(Engine, "INCR", {
  11822. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11823. get: function () {
  11824. return Engine._INCR;
  11825. },
  11826. enumerable: true,
  11827. configurable: true
  11828. });
  11829. Object.defineProperty(Engine, "DECR", {
  11830. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11831. get: function () {
  11832. return Engine._DECR;
  11833. },
  11834. enumerable: true,
  11835. configurable: true
  11836. });
  11837. Object.defineProperty(Engine, "INVERT", {
  11838. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11839. get: function () {
  11840. return Engine._INVERT;
  11841. },
  11842. enumerable: true,
  11843. configurable: true
  11844. });
  11845. Object.defineProperty(Engine, "INCR_WRAP", {
  11846. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11847. get: function () {
  11848. return Engine._INCR_WRAP;
  11849. },
  11850. enumerable: true,
  11851. configurable: true
  11852. });
  11853. Object.defineProperty(Engine, "DECR_WRAP", {
  11854. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11855. get: function () {
  11856. return Engine._DECR_WRAP;
  11857. },
  11858. enumerable: true,
  11859. configurable: true
  11860. });
  11861. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11862. // Alpha
  11863. /** Defines that alpha blending is disabled */
  11864. get: function () {
  11865. return Engine._ALPHA_DISABLE;
  11866. },
  11867. enumerable: true,
  11868. configurable: true
  11869. });
  11870. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11871. /** Defines that alpha blending to SRC + DEST */
  11872. get: function () {
  11873. return Engine._ALPHA_ONEONE;
  11874. },
  11875. enumerable: true,
  11876. configurable: true
  11877. });
  11878. Object.defineProperty(Engine, "ALPHA_ADD", {
  11879. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11880. get: function () {
  11881. return Engine._ALPHA_ADD;
  11882. },
  11883. enumerable: true,
  11884. configurable: true
  11885. });
  11886. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11887. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11888. get: function () {
  11889. return Engine._ALPHA_COMBINE;
  11890. },
  11891. enumerable: true,
  11892. configurable: true
  11893. });
  11894. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11895. /** Defines that alpha blending to DEST - SRC * DEST */
  11896. get: function () {
  11897. return Engine._ALPHA_SUBTRACT;
  11898. },
  11899. enumerable: true,
  11900. configurable: true
  11901. });
  11902. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11903. /** Defines that alpha blending to SRC * DEST */
  11904. get: function () {
  11905. return Engine._ALPHA_MULTIPLY;
  11906. },
  11907. enumerable: true,
  11908. configurable: true
  11909. });
  11910. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11911. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11912. get: function () {
  11913. return Engine._ALPHA_MAXIMIZED;
  11914. },
  11915. enumerable: true,
  11916. configurable: true
  11917. });
  11918. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11919. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11920. get: function () {
  11921. return Engine._ALPHA_PREMULTIPLIED;
  11922. },
  11923. enumerable: true,
  11924. configurable: true
  11925. });
  11926. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11927. /**
  11928. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11929. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11930. */
  11931. get: function () {
  11932. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11933. },
  11934. enumerable: true,
  11935. configurable: true
  11936. });
  11937. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11938. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11939. get: function () {
  11940. return Engine._ALPHA_INTERPOLATE;
  11941. },
  11942. enumerable: true,
  11943. configurable: true
  11944. });
  11945. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11946. /**
  11947. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11948. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11949. */
  11950. get: function () {
  11951. return Engine._ALPHA_SCREENMODE;
  11952. },
  11953. enumerable: true,
  11954. configurable: true
  11955. });
  11956. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11957. // Delays
  11958. /** Defines that the ressource is not delayed*/
  11959. get: function () {
  11960. return Engine._DELAYLOADSTATE_NONE;
  11961. },
  11962. enumerable: true,
  11963. configurable: true
  11964. });
  11965. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11966. /** Defines that the ressource was successfully delay loaded */
  11967. get: function () {
  11968. return Engine._DELAYLOADSTATE_LOADED;
  11969. },
  11970. enumerable: true,
  11971. configurable: true
  11972. });
  11973. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11974. /** Defines that the ressource is currently delay loading */
  11975. get: function () {
  11976. return Engine._DELAYLOADSTATE_LOADING;
  11977. },
  11978. enumerable: true,
  11979. configurable: true
  11980. });
  11981. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11982. /** Defines that the ressource is delayed and has not started loading */
  11983. get: function () {
  11984. return Engine._DELAYLOADSTATE_NOTLOADED;
  11985. },
  11986. enumerable: true,
  11987. configurable: true
  11988. });
  11989. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11990. /** ALPHA */
  11991. get: function () {
  11992. return Engine._TEXTUREFORMAT_ALPHA;
  11993. },
  11994. enumerable: true,
  11995. configurable: true
  11996. });
  11997. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11998. /** LUMINANCE */
  11999. get: function () {
  12000. return Engine._TEXTUREFORMAT_LUMINANCE;
  12001. },
  12002. enumerable: true,
  12003. configurable: true
  12004. });
  12005. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  12006. /**
  12007. * R32F
  12008. */
  12009. get: function () {
  12010. return Engine._TEXTUREFORMAT_R32F;
  12011. },
  12012. enumerable: true,
  12013. configurable: true
  12014. });
  12015. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  12016. /**
  12017. * RG32F
  12018. */
  12019. get: function () {
  12020. return Engine._TEXTUREFORMAT_RG32F;
  12021. },
  12022. enumerable: true,
  12023. configurable: true
  12024. });
  12025. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  12026. /**
  12027. * RGB32F
  12028. */
  12029. get: function () {
  12030. return Engine._TEXTUREFORMAT_RGB32F;
  12031. },
  12032. enumerable: true,
  12033. configurable: true
  12034. });
  12035. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  12036. /**
  12037. * RGBA32F
  12038. */
  12039. get: function () {
  12040. return Engine._TEXTUREFORMAT_RGBA32F;
  12041. },
  12042. enumerable: true,
  12043. configurable: true
  12044. });
  12045. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  12046. /** LUMINANCE_ALPHA */
  12047. get: function () {
  12048. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  12049. },
  12050. enumerable: true,
  12051. configurable: true
  12052. });
  12053. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  12054. /** RGB */
  12055. get: function () {
  12056. return Engine._TEXTUREFORMAT_RGB;
  12057. },
  12058. enumerable: true,
  12059. configurable: true
  12060. });
  12061. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  12062. /** RGBA */
  12063. get: function () {
  12064. return Engine._TEXTUREFORMAT_RGBA;
  12065. },
  12066. enumerable: true,
  12067. configurable: true
  12068. });
  12069. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  12070. /** UNSIGNED_INT */
  12071. get: function () {
  12072. return Engine._TEXTURETYPE_UNSIGNED_INT;
  12073. },
  12074. enumerable: true,
  12075. configurable: true
  12076. });
  12077. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  12078. /** FLOAT */
  12079. get: function () {
  12080. return Engine._TEXTURETYPE_FLOAT;
  12081. },
  12082. enumerable: true,
  12083. configurable: true
  12084. });
  12085. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12086. /** HALF_FLOAT */
  12087. get: function () {
  12088. return Engine._TEXTURETYPE_HALF_FLOAT;
  12089. },
  12090. enumerable: true,
  12091. configurable: true
  12092. });
  12093. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12094. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12095. get: function () {
  12096. return Engine._SCALEMODE_FLOOR;
  12097. },
  12098. enumerable: true,
  12099. configurable: true
  12100. });
  12101. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12102. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12103. get: function () {
  12104. return Engine._SCALEMODE_NEAREST;
  12105. },
  12106. enumerable: true,
  12107. configurable: true
  12108. });
  12109. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12110. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12111. get: function () {
  12112. return Engine._SCALEMODE_CEILING;
  12113. },
  12114. enumerable: true,
  12115. configurable: true
  12116. });
  12117. Object.defineProperty(Engine, "Version", {
  12118. /**
  12119. * Returns the current version of the framework
  12120. */
  12121. get: function () {
  12122. return "3.3.0-alpha.2";
  12123. },
  12124. enumerable: true,
  12125. configurable: true
  12126. });
  12127. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12128. /**
  12129. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12130. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12131. */
  12132. get: function () {
  12133. return this._vrExclusivePointerMode;
  12134. },
  12135. enumerable: true,
  12136. configurable: true
  12137. });
  12138. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12139. /**
  12140. * Gets a boolean indicating that the engine supports uniform buffers
  12141. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12142. */
  12143. get: function () {
  12144. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12145. },
  12146. enumerable: true,
  12147. configurable: true
  12148. });
  12149. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12150. /**
  12151. * Gets a boolean indicating that only power of 2 textures are supported
  12152. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12153. */
  12154. get: function () {
  12155. return this._webGLVersion < 2 || this.forcePOTTextures;
  12156. },
  12157. enumerable: true,
  12158. configurable: true
  12159. });
  12160. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12161. /**
  12162. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12163. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12164. */
  12165. get: function () {
  12166. return this._doNotHandleContextLost;
  12167. },
  12168. set: function (value) {
  12169. this._doNotHandleContextLost = value;
  12170. },
  12171. enumerable: true,
  12172. configurable: true
  12173. });
  12174. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12175. /**
  12176. * Gets the performance monitor attached to this engine
  12177. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12178. */
  12179. get: function () {
  12180. return this._performanceMonitor;
  12181. },
  12182. enumerable: true,
  12183. configurable: true
  12184. });
  12185. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12186. /**
  12187. * Gets the list of texture formats supported
  12188. */
  12189. get: function () {
  12190. return this._texturesSupported;
  12191. },
  12192. enumerable: true,
  12193. configurable: true
  12194. });
  12195. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12196. /**
  12197. * Gets the list of texture formats in use
  12198. */
  12199. get: function () {
  12200. return this._textureFormatInUse;
  12201. },
  12202. enumerable: true,
  12203. configurable: true
  12204. });
  12205. Object.defineProperty(Engine.prototype, "currentViewport", {
  12206. /**
  12207. * Gets the current viewport
  12208. */
  12209. get: function () {
  12210. return this._cachedViewport;
  12211. },
  12212. enumerable: true,
  12213. configurable: true
  12214. });
  12215. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12216. /**
  12217. * Gets the default empty texture
  12218. */
  12219. get: function () {
  12220. if (!this._emptyTexture) {
  12221. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12222. }
  12223. return this._emptyTexture;
  12224. },
  12225. enumerable: true,
  12226. configurable: true
  12227. });
  12228. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12229. /**
  12230. * Gets the default empty 3D texture
  12231. */
  12232. get: function () {
  12233. if (!this._emptyTexture3D) {
  12234. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12235. }
  12236. return this._emptyTexture3D;
  12237. },
  12238. enumerable: true,
  12239. configurable: true
  12240. });
  12241. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12242. /**
  12243. * Gets the default empty cube texture
  12244. */
  12245. get: function () {
  12246. if (!this._emptyCubeTexture) {
  12247. var faceData = new Uint8Array(4);
  12248. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12249. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12250. }
  12251. return this._emptyCubeTexture;
  12252. },
  12253. enumerable: true,
  12254. configurable: true
  12255. });
  12256. Engine.prototype._rebuildInternalTextures = function () {
  12257. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12258. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12259. var internalTexture = currentState_1[_i];
  12260. internalTexture._rebuild();
  12261. }
  12262. };
  12263. Engine.prototype._rebuildEffects = function () {
  12264. for (var key in this._compiledEffects) {
  12265. var effect = this._compiledEffects[key];
  12266. effect._prepareEffect();
  12267. }
  12268. BABYLON.Effect.ResetCache();
  12269. };
  12270. Engine.prototype._rebuildBuffers = function () {
  12271. // Index / Vertex
  12272. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12273. var scene = _a[_i];
  12274. scene.resetCachedMaterial();
  12275. scene._rebuildGeometries();
  12276. scene._rebuildTextures();
  12277. }
  12278. // Uniforms
  12279. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12280. var uniformBuffer = _c[_b];
  12281. uniformBuffer._rebuild();
  12282. }
  12283. };
  12284. Engine.prototype._initGLContext = function () {
  12285. // Caps
  12286. this._caps = new EngineCapabilities();
  12287. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12288. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12289. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12290. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12291. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12292. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12293. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12294. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12295. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12296. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12297. // Infos
  12298. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12299. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12300. if (rendererInfo != null) {
  12301. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12302. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12303. }
  12304. if (!this._glVendor) {
  12305. this._glVendor = "Unknown vendor";
  12306. }
  12307. if (!this._glRenderer) {
  12308. this._glRenderer = "Unknown renderer";
  12309. }
  12310. // Constants
  12311. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12312. if (this._gl.RGBA16F !== 0x881A) {
  12313. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12314. }
  12315. if (this._gl.RGBA32F !== 0x8814) {
  12316. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12317. }
  12318. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12319. this._gl.DEPTH24_STENCIL8 = 35056;
  12320. }
  12321. // Extensions
  12322. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12323. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12324. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12325. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12326. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12327. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12328. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12329. 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');
  12330. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12331. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12332. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12333. this._caps.highPrecisionShaderSupported = true;
  12334. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12335. if (this._caps.timerQuery) {
  12336. if (this._webGLVersion === 1) {
  12337. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12338. }
  12339. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12340. }
  12341. // Checks if some of the format renders first to allow the use of webgl inspector.
  12342. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12343. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12344. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12345. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12346. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12347. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12348. if (this._webGLVersion > 1) {
  12349. this._gl.HALF_FLOAT_OES = 0x140B;
  12350. }
  12351. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12352. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12353. // Draw buffers
  12354. if (this._webGLVersion > 1) {
  12355. this._caps.drawBuffersExtension = true;
  12356. }
  12357. else {
  12358. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12359. if (drawBuffersExtension !== null) {
  12360. this._caps.drawBuffersExtension = true;
  12361. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12362. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12363. for (var i = 0; i < 16; i++) {
  12364. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12365. }
  12366. }
  12367. else {
  12368. this._caps.drawBuffersExtension = false;
  12369. }
  12370. }
  12371. // Depth Texture
  12372. if (this._webGLVersion > 1) {
  12373. this._caps.depthTextureExtension = true;
  12374. }
  12375. else {
  12376. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12377. if (depthTextureExtension != null) {
  12378. this._caps.depthTextureExtension = true;
  12379. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12380. }
  12381. }
  12382. // Vertex array object
  12383. if (this._webGLVersion > 1) {
  12384. this._caps.vertexArrayObject = true;
  12385. }
  12386. else {
  12387. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12388. if (vertexArrayObjectExtension != null) {
  12389. this._caps.vertexArrayObject = true;
  12390. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12391. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12392. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12393. }
  12394. else {
  12395. this._caps.vertexArrayObject = false;
  12396. }
  12397. }
  12398. // Instances count
  12399. if (this._webGLVersion > 1) {
  12400. this._caps.instancedArrays = true;
  12401. }
  12402. else {
  12403. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12404. if (instanceExtension != null) {
  12405. this._caps.instancedArrays = true;
  12406. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12407. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12408. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12409. }
  12410. else {
  12411. this._caps.instancedArrays = false;
  12412. }
  12413. }
  12414. // Intelligently add supported compressed formats in order to check for.
  12415. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12416. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12417. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12418. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12419. if (this._caps.astc)
  12420. this.texturesSupported.push('-astc.ktx');
  12421. if (this._caps.s3tc)
  12422. this.texturesSupported.push('-dxt.ktx');
  12423. if (this._caps.pvrtc)
  12424. this.texturesSupported.push('-pvrtc.ktx');
  12425. if (this._caps.etc2)
  12426. this.texturesSupported.push('-etc2.ktx');
  12427. if (this._caps.etc1)
  12428. this.texturesSupported.push('-etc1.ktx');
  12429. if (this._gl.getShaderPrecisionFormat) {
  12430. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12431. if (highp) {
  12432. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12433. }
  12434. }
  12435. // Depth buffer
  12436. this.setDepthBuffer(true);
  12437. this.setDepthFunctionToLessOrEqual();
  12438. this.setDepthWrite(true);
  12439. // Texture maps
  12440. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12441. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12442. this._nextFreeTextureSlots.push(slot);
  12443. }
  12444. };
  12445. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12446. /**
  12447. * Gets version of the current webGL context
  12448. */
  12449. get: function () {
  12450. return this._webGLVersion;
  12451. },
  12452. enumerable: true,
  12453. configurable: true
  12454. });
  12455. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12456. /**
  12457. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12458. */
  12459. get: function () {
  12460. return this._isStencilEnable;
  12461. },
  12462. enumerable: true,
  12463. configurable: true
  12464. });
  12465. Engine.prototype._prepareWorkingCanvas = function () {
  12466. if (this._workingCanvas) {
  12467. return;
  12468. }
  12469. this._workingCanvas = document.createElement("canvas");
  12470. var context = this._workingCanvas.getContext("2d");
  12471. if (context) {
  12472. this._workingContext = context;
  12473. }
  12474. };
  12475. /**
  12476. * Reset the texture cache to empty state
  12477. */
  12478. Engine.prototype.resetTextureCache = function () {
  12479. for (var key in this._boundTexturesCache) {
  12480. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12481. continue;
  12482. }
  12483. var boundTexture = this._boundTexturesCache[key];
  12484. if (boundTexture) {
  12485. this._removeDesignatedSlot(boundTexture);
  12486. }
  12487. this._boundTexturesCache[key] = null;
  12488. }
  12489. if (!this.disableTextureBindingOptimization) {
  12490. this._nextFreeTextureSlots = [];
  12491. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12492. this._nextFreeTextureSlots.push(slot);
  12493. }
  12494. }
  12495. this._currentTextureChannel = -1;
  12496. };
  12497. /**
  12498. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12499. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12500. * @returns true if engine is in deterministic lock step mode
  12501. */
  12502. Engine.prototype.isDeterministicLockStep = function () {
  12503. return this._deterministicLockstep;
  12504. };
  12505. /**
  12506. * Gets the max steps when engine is running in deterministic lock step
  12507. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12508. * @returns the max steps
  12509. */
  12510. Engine.prototype.getLockstepMaxSteps = function () {
  12511. return this._lockstepMaxSteps;
  12512. };
  12513. /**
  12514. * Gets an object containing information about the current webGL context
  12515. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12516. */
  12517. Engine.prototype.getGlInfo = function () {
  12518. return {
  12519. vendor: this._glVendor,
  12520. renderer: this._glRenderer,
  12521. version: this._glVersion
  12522. };
  12523. };
  12524. /**
  12525. * Gets current aspect ratio
  12526. * @param camera defines the camera to use to get the aspect ratio
  12527. * @param useScreen defines if screen size must be used (or the current render target if any)
  12528. * @returns a number defining the aspect ratio
  12529. */
  12530. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12531. if (useScreen === void 0) { useScreen = false; }
  12532. var viewport = camera.viewport;
  12533. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12534. };
  12535. /**
  12536. * Gets current screen aspect ratio
  12537. * @returns a number defining the aspect ratio
  12538. */
  12539. Engine.prototype.getScreenAspectRatio = function () {
  12540. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12541. };
  12542. /**
  12543. * Gets the current render width
  12544. * @param useScreen defines if screen size must be used (or the current render target if any)
  12545. * @returns a number defining the current render width
  12546. */
  12547. Engine.prototype.getRenderWidth = function (useScreen) {
  12548. if (useScreen === void 0) { useScreen = false; }
  12549. if (!useScreen && this._currentRenderTarget) {
  12550. return this._currentRenderTarget.width;
  12551. }
  12552. return this._gl.drawingBufferWidth;
  12553. };
  12554. /**
  12555. * Gets the current render height
  12556. * @param useScreen defines if screen size must be used (or the current render target if any)
  12557. * @returns a number defining the current render height
  12558. */
  12559. Engine.prototype.getRenderHeight = function (useScreen) {
  12560. if (useScreen === void 0) { useScreen = false; }
  12561. if (!useScreen && this._currentRenderTarget) {
  12562. return this._currentRenderTarget.height;
  12563. }
  12564. return this._gl.drawingBufferHeight;
  12565. };
  12566. /**
  12567. * Gets the HTML canvas attached with the current webGL context
  12568. * @returns a HTML canvas
  12569. */
  12570. Engine.prototype.getRenderingCanvas = function () {
  12571. return this._renderingCanvas;
  12572. };
  12573. /**
  12574. * Gets the client rect of the HTML canvas attached with the current webGL context
  12575. * @returns a client rectanglee
  12576. */
  12577. Engine.prototype.getRenderingCanvasClientRect = function () {
  12578. if (!this._renderingCanvas) {
  12579. return null;
  12580. }
  12581. return this._renderingCanvas.getBoundingClientRect();
  12582. };
  12583. /**
  12584. * Defines the hardware scaling level.
  12585. * By default the hardware scaling level is computed from the window device ratio.
  12586. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12587. * @param level defines the level to use
  12588. */
  12589. Engine.prototype.setHardwareScalingLevel = function (level) {
  12590. this._hardwareScalingLevel = level;
  12591. this.resize();
  12592. };
  12593. /**
  12594. * Gets the current hardware scaling level.
  12595. * By default the hardware scaling level is computed from the window device ratio.
  12596. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12597. * @returns a number indicating the current hardware scaling level
  12598. */
  12599. Engine.prototype.getHardwareScalingLevel = function () {
  12600. return this._hardwareScalingLevel;
  12601. };
  12602. /**
  12603. * Gets the list of loaded textures
  12604. * @returns an array containing all loaded textures
  12605. */
  12606. Engine.prototype.getLoadedTexturesCache = function () {
  12607. return this._internalTexturesCache;
  12608. };
  12609. /**
  12610. * Gets the object containing all engine capabilities
  12611. * @returns the EngineCapabilities object
  12612. */
  12613. Engine.prototype.getCaps = function () {
  12614. return this._caps;
  12615. };
  12616. Object.defineProperty(Engine.prototype, "drawCalls", {
  12617. /** @hidden */
  12618. get: function () {
  12619. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12620. return 0;
  12621. },
  12622. enumerable: true,
  12623. configurable: true
  12624. });
  12625. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12626. /** @hidden */
  12627. get: function () {
  12628. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12629. return null;
  12630. },
  12631. enumerable: true,
  12632. configurable: true
  12633. });
  12634. /**
  12635. * Gets the current depth function
  12636. * @returns a number defining the depth function
  12637. */
  12638. Engine.prototype.getDepthFunction = function () {
  12639. return this._depthCullingState.depthFunc;
  12640. };
  12641. /**
  12642. * Sets the current depth function
  12643. * @param depthFunc defines the function to use
  12644. */
  12645. Engine.prototype.setDepthFunction = function (depthFunc) {
  12646. this._depthCullingState.depthFunc = depthFunc;
  12647. };
  12648. /**
  12649. * Sets the current depth function to GREATER
  12650. */
  12651. Engine.prototype.setDepthFunctionToGreater = function () {
  12652. this._depthCullingState.depthFunc = this._gl.GREATER;
  12653. };
  12654. /**
  12655. * Sets the current depth function to GEQUAL
  12656. */
  12657. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12658. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12659. };
  12660. /**
  12661. * Sets the current depth function to LESS
  12662. */
  12663. Engine.prototype.setDepthFunctionToLess = function () {
  12664. this._depthCullingState.depthFunc = this._gl.LESS;
  12665. };
  12666. /**
  12667. * Sets the current depth function to LEQUAL
  12668. */
  12669. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12670. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12671. };
  12672. /**
  12673. * Gets a boolean indicating if stencil buffer is enabled
  12674. * @returns the current stencil buffer state
  12675. */
  12676. Engine.prototype.getStencilBuffer = function () {
  12677. return this._stencilState.stencilTest;
  12678. };
  12679. /**
  12680. * Enable or disable the stencil buffer
  12681. * @param enable defines if the stencil buffer must be enabled or disabled
  12682. */
  12683. Engine.prototype.setStencilBuffer = function (enable) {
  12684. this._stencilState.stencilTest = enable;
  12685. };
  12686. /**
  12687. * Gets the current stencil mask
  12688. * @returns a number defining the new stencil mask to use
  12689. */
  12690. Engine.prototype.getStencilMask = function () {
  12691. return this._stencilState.stencilMask;
  12692. };
  12693. /**
  12694. * Sets the current stencil mask
  12695. * @param mask defines the new stencil mask to use
  12696. */
  12697. Engine.prototype.setStencilMask = function (mask) {
  12698. this._stencilState.stencilMask = mask;
  12699. };
  12700. /**
  12701. * Gets the current stencil function
  12702. * @returns a number defining the stencil function to use
  12703. */
  12704. Engine.prototype.getStencilFunction = function () {
  12705. return this._stencilState.stencilFunc;
  12706. };
  12707. /**
  12708. * Gets the current stencil reference value
  12709. * @returns a number defining the stencil reference value to use
  12710. */
  12711. Engine.prototype.getStencilFunctionReference = function () {
  12712. return this._stencilState.stencilFuncRef;
  12713. };
  12714. /**
  12715. * Gets the current stencil mask
  12716. * @returns a number defining the stencil mask to use
  12717. */
  12718. Engine.prototype.getStencilFunctionMask = function () {
  12719. return this._stencilState.stencilFuncMask;
  12720. };
  12721. /**
  12722. * Sets the current stencil function
  12723. * @param stencilFunc defines the new stencil function to use
  12724. */
  12725. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12726. this._stencilState.stencilFunc = stencilFunc;
  12727. };
  12728. /**
  12729. * Sets the current stencil reference
  12730. * @param reference defines the new stencil reference to use
  12731. */
  12732. Engine.prototype.setStencilFunctionReference = function (reference) {
  12733. this._stencilState.stencilFuncRef = reference;
  12734. };
  12735. /**
  12736. * Sets the current stencil mask
  12737. * @param mask defines the new stencil mask to use
  12738. */
  12739. Engine.prototype.setStencilFunctionMask = function (mask) {
  12740. this._stencilState.stencilFuncMask = mask;
  12741. };
  12742. /**
  12743. * Gets the current stencil operation when stencil fails
  12744. * @returns a number defining stencil operation to use when stencil fails
  12745. */
  12746. Engine.prototype.getStencilOperationFail = function () {
  12747. return this._stencilState.stencilOpStencilFail;
  12748. };
  12749. /**
  12750. * Gets the current stencil operation when depth fails
  12751. * @returns a number defining stencil operation to use when depth fails
  12752. */
  12753. Engine.prototype.getStencilOperationDepthFail = function () {
  12754. return this._stencilState.stencilOpDepthFail;
  12755. };
  12756. /**
  12757. * Gets the current stencil operation when stencil passes
  12758. * @returns a number defining stencil operation to use when stencil passes
  12759. */
  12760. Engine.prototype.getStencilOperationPass = function () {
  12761. return this._stencilState.stencilOpStencilDepthPass;
  12762. };
  12763. /**
  12764. * Sets the stencil operation to use when stencil fails
  12765. * @param operation defines the stencil operation to use when stencil fails
  12766. */
  12767. Engine.prototype.setStencilOperationFail = function (operation) {
  12768. this._stencilState.stencilOpStencilFail = operation;
  12769. };
  12770. /**
  12771. * Sets the stencil operation to use when depth fails
  12772. * @param operation defines the stencil operation to use when depth fails
  12773. */
  12774. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12775. this._stencilState.stencilOpDepthFail = operation;
  12776. };
  12777. /**
  12778. * Sets the stencil operation to use when stencil passes
  12779. * @param operation defines the stencil operation to use when stencil passes
  12780. */
  12781. Engine.prototype.setStencilOperationPass = function (operation) {
  12782. this._stencilState.stencilOpStencilDepthPass = operation;
  12783. };
  12784. /**
  12785. * Sets a boolean indicating if the dithering state is enabled or disabled
  12786. * @param value defines the dithering state
  12787. */
  12788. Engine.prototype.setDitheringState = function (value) {
  12789. if (value) {
  12790. this._gl.enable(this._gl.DITHER);
  12791. }
  12792. else {
  12793. this._gl.disable(this._gl.DITHER);
  12794. }
  12795. };
  12796. /**
  12797. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12798. * @param value defines the rasterizer state
  12799. */
  12800. Engine.prototype.setRasterizerState = function (value) {
  12801. if (value) {
  12802. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12803. }
  12804. else {
  12805. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12806. }
  12807. };
  12808. /**
  12809. * stop executing a render loop function and remove it from the execution array
  12810. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12811. */
  12812. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12813. if (!renderFunction) {
  12814. this._activeRenderLoops = [];
  12815. return;
  12816. }
  12817. var index = this._activeRenderLoops.indexOf(renderFunction);
  12818. if (index >= 0) {
  12819. this._activeRenderLoops.splice(index, 1);
  12820. }
  12821. };
  12822. /** @hidden */
  12823. Engine.prototype._renderLoop = function () {
  12824. if (!this._contextWasLost) {
  12825. var shouldRender = true;
  12826. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12827. shouldRender = false;
  12828. }
  12829. if (shouldRender) {
  12830. // Start new frame
  12831. this.beginFrame();
  12832. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12833. var renderFunction = this._activeRenderLoops[index];
  12834. renderFunction();
  12835. }
  12836. // Present
  12837. this.endFrame();
  12838. }
  12839. }
  12840. if (this._activeRenderLoops.length > 0) {
  12841. // Register new frame
  12842. var requester = null;
  12843. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12844. requester = this._vrDisplay;
  12845. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12846. }
  12847. else {
  12848. this._renderingQueueLaunched = false;
  12849. }
  12850. };
  12851. /**
  12852. * Register and execute a render loop. The engine can have more than one render function
  12853. * @param renderFunction defines the function to continuously execute
  12854. */
  12855. Engine.prototype.runRenderLoop = function (renderFunction) {
  12856. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12857. return;
  12858. }
  12859. this._activeRenderLoops.push(renderFunction);
  12860. if (!this._renderingQueueLaunched) {
  12861. this._renderingQueueLaunched = true;
  12862. this._bindedRenderFunction = this._renderLoop.bind(this);
  12863. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12864. }
  12865. };
  12866. /**
  12867. * Toggle full screen mode
  12868. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12869. * @param options defines an option object to be sent to the requestFullscreen function
  12870. */
  12871. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12872. if (this.isFullscreen) {
  12873. BABYLON.Tools.ExitFullscreen();
  12874. }
  12875. else {
  12876. this._pointerLockRequested = requestPointerLock;
  12877. if (this._renderingCanvas) {
  12878. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12879. }
  12880. }
  12881. };
  12882. /**
  12883. * Clear the current render buffer or the current render target (if any is set up)
  12884. * @param color defines the color to use
  12885. * @param backBuffer defines if the back buffer must be cleared
  12886. * @param depth defines if the depth buffer must be cleared
  12887. * @param stencil defines if the stencil buffer must be cleared
  12888. */
  12889. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12890. if (stencil === void 0) { stencil = false; }
  12891. this.applyStates();
  12892. var mode = 0;
  12893. if (backBuffer && color) {
  12894. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12895. mode |= this._gl.COLOR_BUFFER_BIT;
  12896. }
  12897. if (depth) {
  12898. this._gl.clearDepth(1.0);
  12899. mode |= this._gl.DEPTH_BUFFER_BIT;
  12900. }
  12901. if (stencil) {
  12902. this._gl.clearStencil(0);
  12903. mode |= this._gl.STENCIL_BUFFER_BIT;
  12904. }
  12905. this._gl.clear(mode);
  12906. };
  12907. /**
  12908. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12909. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12910. * @param y defines the y-coordinate of the corner of the clear rectangle
  12911. * @param width defines the width of the clear rectangle
  12912. * @param height defines the height of the clear rectangle
  12913. * @param clearColor defines the clear color
  12914. */
  12915. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12916. var gl = this._gl;
  12917. // Save state
  12918. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12919. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12920. // Change state
  12921. gl.enable(gl.SCISSOR_TEST);
  12922. gl.scissor(x, y, width, height);
  12923. // Clear
  12924. this.clear(clearColor, true, true, true);
  12925. // Restore state
  12926. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12927. if (curScissor === true) {
  12928. gl.enable(gl.SCISSOR_TEST);
  12929. }
  12930. else {
  12931. gl.disable(gl.SCISSOR_TEST);
  12932. }
  12933. };
  12934. /**
  12935. * Set the WebGL's viewport
  12936. * @param viewport defines the viewport element to be used
  12937. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12938. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12939. */
  12940. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12941. var width = requiredWidth || this.getRenderWidth();
  12942. var height = requiredHeight || this.getRenderHeight();
  12943. var x = viewport.x || 0;
  12944. var y = viewport.y || 0;
  12945. this._cachedViewport = viewport;
  12946. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12947. };
  12948. /**
  12949. * Directly set the WebGL Viewport
  12950. * @param x defines the x coordinate of the viewport (in screen space)
  12951. * @param y defines the y coordinate of the viewport (in screen space)
  12952. * @param width defines the width of the viewport (in screen space)
  12953. * @param height defines the height of the viewport (in screen space)
  12954. * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state
  12955. */
  12956. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12957. var currentViewport = this._cachedViewport;
  12958. this._cachedViewport = null;
  12959. this._gl.viewport(x, y, width, height);
  12960. return currentViewport;
  12961. };
  12962. /**
  12963. * Begin a new frame
  12964. */
  12965. Engine.prototype.beginFrame = function () {
  12966. this.onBeginFrameObservable.notifyObservers(this);
  12967. this._measureFps();
  12968. };
  12969. /**
  12970. * Enf the current frame
  12971. */
  12972. Engine.prototype.endFrame = function () {
  12973. // Force a flush in case we are using a bad OS.
  12974. if (this._badOS) {
  12975. this.flushFramebuffer();
  12976. }
  12977. // Submit frame to the vr device, if enabled
  12978. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12979. // TODO: We should only submit the frame if we read frameData successfully.
  12980. this._vrDisplay.submitFrame();
  12981. }
  12982. this.onEndFrameObservable.notifyObservers(this);
  12983. };
  12984. /**
  12985. * Resize the view according to the canvas' size
  12986. */
  12987. Engine.prototype.resize = function () {
  12988. // We're not resizing the size of the canvas while in VR mode & presenting
  12989. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12990. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12991. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12992. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12993. }
  12994. };
  12995. /**
  12996. * Force a specific size of the canvas
  12997. * @param width defines the new canvas' width
  12998. * @param height defines the new canvas' height
  12999. */
  13000. Engine.prototype.setSize = function (width, height) {
  13001. if (!this._renderingCanvas) {
  13002. return;
  13003. }
  13004. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13005. return;
  13006. }
  13007. this._renderingCanvas.width = width;
  13008. this._renderingCanvas.height = height;
  13009. for (var index = 0; index < this.scenes.length; index++) {
  13010. var scene = this.scenes[index];
  13011. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13012. var cam = scene.cameras[camIndex];
  13013. cam._currentRenderId = 0;
  13014. }
  13015. }
  13016. if (this.onResizeObservable.hasObservers) {
  13017. this.onResizeObservable.notifyObservers(this);
  13018. }
  13019. };
  13020. // WebVR functions
  13021. /**
  13022. * Gets a boolean indicating if a webVR device was detected
  13023. * @returns true if a webVR device was detected
  13024. */
  13025. Engine.prototype.isVRDevicePresent = function () {
  13026. return !!this._vrDisplay;
  13027. };
  13028. /**
  13029. * Gets the current webVR device
  13030. * @returns the current webVR device (or null)
  13031. */
  13032. Engine.prototype.getVRDevice = function () {
  13033. return this._vrDisplay;
  13034. };
  13035. /**
  13036. * Initializes a webVR display and starts listening to display change events
  13037. * The onVRDisplayChangedObservable will be notified upon these changes
  13038. * @returns The onVRDisplayChangedObservable
  13039. */
  13040. Engine.prototype.initWebVR = function () {
  13041. this.initWebVRAsync();
  13042. return this.onVRDisplayChangedObservable;
  13043. };
  13044. /**
  13045. * Initializes a webVR display and starts listening to display change events
  13046. * The onVRDisplayChangedObservable will be notified upon these changes
  13047. * @returns A promise containing a VRDisplay and if vr is supported
  13048. */
  13049. Engine.prototype.initWebVRAsync = function () {
  13050. var _this = this;
  13051. var notifyObservers = function () {
  13052. var eventArgs = {
  13053. vrDisplay: _this._vrDisplay,
  13054. vrSupported: _this._vrSupported
  13055. };
  13056. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13057. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13058. };
  13059. if (!this._onVrDisplayConnect) {
  13060. this._onVrDisplayConnect = function (event) {
  13061. _this._vrDisplay = event.display;
  13062. notifyObservers();
  13063. };
  13064. this._onVrDisplayDisconnect = function () {
  13065. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13066. _this._vrDisplay = undefined;
  13067. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13068. notifyObservers();
  13069. };
  13070. this._onVrDisplayPresentChange = function () {
  13071. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13072. };
  13073. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13074. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13075. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13076. }
  13077. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13078. this._webVRInitPromise.then(notifyObservers);
  13079. return this._webVRInitPromise;
  13080. };
  13081. /**
  13082. * Call this function to switch to webVR mode
  13083. * Will do nothing if webVR is not supported or if there is no webVR device
  13084. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13085. */
  13086. Engine.prototype.enableVR = function () {
  13087. var _this = this;
  13088. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13089. var onResolved = function () {
  13090. _this.onVRRequestPresentComplete.notifyObservers(true);
  13091. _this._onVRFullScreenTriggered();
  13092. };
  13093. var onRejected = function () {
  13094. _this.onVRRequestPresentComplete.notifyObservers(false);
  13095. };
  13096. this.onVRRequestPresentStart.notifyObservers(this);
  13097. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13098. }
  13099. };
  13100. /**
  13101. * Call this function to leave webVR mode
  13102. * Will do nothing if webVR is not supported or if there is no webVR device
  13103. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13104. */
  13105. Engine.prototype.disableVR = function () {
  13106. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13107. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13108. }
  13109. };
  13110. Engine.prototype._getVRDisplaysAsync = function () {
  13111. var _this = this;
  13112. return new Promise(function (res, rej) {
  13113. if (navigator.getVRDisplays) {
  13114. navigator.getVRDisplays().then(function (devices) {
  13115. _this._vrSupported = true;
  13116. // note that devices may actually be an empty array. This is fine;
  13117. // we expect this._vrDisplay to be undefined in this case.
  13118. _this._vrDisplay = devices[0];
  13119. res({
  13120. vrDisplay: _this._vrDisplay,
  13121. vrSupported: _this._vrSupported
  13122. });
  13123. });
  13124. }
  13125. else {
  13126. _this._vrDisplay = undefined;
  13127. _this._vrSupported = false;
  13128. res({
  13129. vrDisplay: _this._vrDisplay,
  13130. vrSupported: _this._vrSupported
  13131. });
  13132. }
  13133. });
  13134. };
  13135. /**
  13136. * Binds the frame buffer to the specified texture.
  13137. * @param texture The texture to render to or null for the default canvas
  13138. * @param faceIndex The face of the texture to render to in case of cube texture
  13139. * @param requiredWidth The width of the target to render to
  13140. * @param requiredHeight The height of the target to render to
  13141. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13142. * @param depthStencilTexture The depth stencil texture to use to render
  13143. */
  13144. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  13145. if (this._currentRenderTarget) {
  13146. this.unBindFramebuffer(this._currentRenderTarget);
  13147. }
  13148. this._currentRenderTarget = texture;
  13149. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13150. var gl = this._gl;
  13151. if (texture.isCube) {
  13152. if (faceIndex === undefined) {
  13153. faceIndex = 0;
  13154. }
  13155. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13156. if (depthStencilTexture) {
  13157. if (depthStencilTexture._generateStencilBuffer) {
  13158. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13159. }
  13160. else {
  13161. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13162. }
  13163. }
  13164. }
  13165. if (this._cachedViewport && !forceFullscreenViewport) {
  13166. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13167. }
  13168. else {
  13169. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  13170. }
  13171. this.wipeCaches();
  13172. };
  13173. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13174. if (this._currentFramebuffer !== framebuffer) {
  13175. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13176. this._currentFramebuffer = framebuffer;
  13177. }
  13178. };
  13179. /**
  13180. * Unbind the current render target texture from the webGL context
  13181. * @param texture defines the render target texture to unbind
  13182. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13183. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13184. */
  13185. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13186. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13187. this._currentRenderTarget = null;
  13188. // If MSAA, we need to bitblt back to main texture
  13189. var gl = this._gl;
  13190. if (texture._MSAAFramebuffer) {
  13191. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13192. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13193. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13194. }
  13195. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13196. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13197. gl.generateMipmap(gl.TEXTURE_2D);
  13198. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13199. }
  13200. if (onBeforeUnbind) {
  13201. if (texture._MSAAFramebuffer) {
  13202. // Bind the correct framebuffer
  13203. this.bindUnboundFramebuffer(texture._framebuffer);
  13204. }
  13205. onBeforeUnbind();
  13206. }
  13207. this.bindUnboundFramebuffer(null);
  13208. };
  13209. /**
  13210. * Unbind a list of render target textures from the webGL context
  13211. * This is used only when drawBuffer extension or webGL2 are active
  13212. * @param textures defines the render target textures to unbind
  13213. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13214. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13215. */
  13216. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13217. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13218. this._currentRenderTarget = null;
  13219. // If MSAA, we need to bitblt back to main texture
  13220. var gl = this._gl;
  13221. if (textures[0]._MSAAFramebuffer) {
  13222. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13223. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13224. var attachments = textures[0]._attachments;
  13225. if (!attachments) {
  13226. attachments = new Array(textures.length);
  13227. textures[0]._attachments = attachments;
  13228. }
  13229. for (var i = 0; i < textures.length; i++) {
  13230. var texture = textures[i];
  13231. for (var j = 0; j < attachments.length; j++) {
  13232. attachments[j] = gl.NONE;
  13233. }
  13234. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13235. gl.readBuffer(attachments[i]);
  13236. gl.drawBuffers(attachments);
  13237. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13238. }
  13239. for (var i = 0; i < attachments.length; i++) {
  13240. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13241. }
  13242. gl.drawBuffers(attachments);
  13243. }
  13244. for (var i = 0; i < textures.length; i++) {
  13245. var texture = textures[i];
  13246. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13247. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13248. gl.generateMipmap(gl.TEXTURE_2D);
  13249. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13250. }
  13251. }
  13252. if (onBeforeUnbind) {
  13253. if (textures[0]._MSAAFramebuffer) {
  13254. // Bind the correct framebuffer
  13255. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13256. }
  13257. onBeforeUnbind();
  13258. }
  13259. this.bindUnboundFramebuffer(null);
  13260. };
  13261. /**
  13262. * Force the mipmap generation for the given render target texture
  13263. * @param texture defines the render target texture to use
  13264. */
  13265. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13266. if (texture.generateMipMaps) {
  13267. var gl = this._gl;
  13268. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13269. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13270. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13271. }
  13272. };
  13273. /**
  13274. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13275. */
  13276. Engine.prototype.flushFramebuffer = function () {
  13277. this._gl.flush();
  13278. };
  13279. /**
  13280. * Unbind the current render target and bind the default framebuffer
  13281. */
  13282. Engine.prototype.restoreDefaultFramebuffer = function () {
  13283. if (this._currentRenderTarget) {
  13284. this.unBindFramebuffer(this._currentRenderTarget);
  13285. }
  13286. else {
  13287. this.bindUnboundFramebuffer(null);
  13288. }
  13289. if (this._cachedViewport) {
  13290. this.setViewport(this._cachedViewport);
  13291. }
  13292. this.wipeCaches();
  13293. };
  13294. // UBOs
  13295. /**
  13296. * Create an uniform buffer
  13297. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13298. * @param elements defines the content of the uniform buffer
  13299. * @returns the webGL uniform buffer
  13300. */
  13301. Engine.prototype.createUniformBuffer = function (elements) {
  13302. var ubo = this._gl.createBuffer();
  13303. if (!ubo) {
  13304. throw new Error("Unable to create uniform buffer");
  13305. }
  13306. this.bindUniformBuffer(ubo);
  13307. if (elements instanceof Float32Array) {
  13308. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13309. }
  13310. else {
  13311. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13312. }
  13313. this.bindUniformBuffer(null);
  13314. ubo.references = 1;
  13315. return ubo;
  13316. };
  13317. /**
  13318. * Create a dynamic uniform buffer
  13319. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13320. * @param elements defines the content of the uniform buffer
  13321. * @returns the webGL uniform buffer
  13322. */
  13323. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13324. var ubo = this._gl.createBuffer();
  13325. if (!ubo) {
  13326. throw new Error("Unable to create dynamic uniform buffer");
  13327. }
  13328. this.bindUniformBuffer(ubo);
  13329. if (elements instanceof Float32Array) {
  13330. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13331. }
  13332. else {
  13333. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13334. }
  13335. this.bindUniformBuffer(null);
  13336. ubo.references = 1;
  13337. return ubo;
  13338. };
  13339. /**
  13340. * Update an existing uniform buffer
  13341. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13342. * @param uniformBuffer defines the target uniform buffer
  13343. * @param elements defines the content to update
  13344. * @param offset defines the offset in the uniform buffer where update should start
  13345. * @param count defines the size of the data to update
  13346. */
  13347. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13348. this.bindUniformBuffer(uniformBuffer);
  13349. if (offset === undefined) {
  13350. offset = 0;
  13351. }
  13352. if (count === undefined) {
  13353. if (elements instanceof Float32Array) {
  13354. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13355. }
  13356. else {
  13357. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13358. }
  13359. }
  13360. else {
  13361. if (elements instanceof Float32Array) {
  13362. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13363. }
  13364. else {
  13365. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13366. }
  13367. }
  13368. this.bindUniformBuffer(null);
  13369. };
  13370. // VBOs
  13371. Engine.prototype._resetVertexBufferBinding = function () {
  13372. this.bindArrayBuffer(null);
  13373. this._cachedVertexBuffers = null;
  13374. };
  13375. /**
  13376. * Creates a vertex buffer
  13377. * @param data the data for the vertex buffer
  13378. * @returns the new WebGL static buffer
  13379. */
  13380. Engine.prototype.createVertexBuffer = function (data) {
  13381. var vbo = this._gl.createBuffer();
  13382. if (!vbo) {
  13383. throw new Error("Unable to create vertex buffer");
  13384. }
  13385. this.bindArrayBuffer(vbo);
  13386. if (data instanceof Array) {
  13387. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13388. }
  13389. else {
  13390. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13391. }
  13392. this._resetVertexBufferBinding();
  13393. vbo.references = 1;
  13394. return vbo;
  13395. };
  13396. /**
  13397. * Creates a dynamic vertex buffer
  13398. * @param data the data for the dynamic vertex buffer
  13399. * @returns the new WebGL dynamic buffer
  13400. */
  13401. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13402. var vbo = this._gl.createBuffer();
  13403. if (!vbo) {
  13404. throw new Error("Unable to create dynamic vertex buffer");
  13405. }
  13406. this.bindArrayBuffer(vbo);
  13407. if (data instanceof Array) {
  13408. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13409. }
  13410. else {
  13411. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13412. }
  13413. this._resetVertexBufferBinding();
  13414. vbo.references = 1;
  13415. return vbo;
  13416. };
  13417. /**
  13418. * Update a dynamic index buffer
  13419. * @param indexBuffer defines the target index buffer
  13420. * @param indices defines the data to update
  13421. * @param offset defines the offset in the target index buffer where update should start
  13422. */
  13423. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13424. if (offset === void 0) { offset = 0; }
  13425. // Force cache update
  13426. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13427. this.bindIndexBuffer(indexBuffer);
  13428. var arrayBuffer;
  13429. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13430. arrayBuffer = indices;
  13431. }
  13432. else {
  13433. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13434. }
  13435. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13436. this._resetIndexBufferBinding();
  13437. };
  13438. /**
  13439. * Updates a dynamic vertex buffer.
  13440. * @param vertexBuffer the vertex buffer to update
  13441. * @param data the data used to update the vertex buffer
  13442. * @param byteOffset the byte offset of the data
  13443. * @param byteLength the byte length of the data
  13444. */
  13445. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13446. this.bindArrayBuffer(vertexBuffer);
  13447. if (byteOffset === undefined) {
  13448. byteOffset = 0;
  13449. }
  13450. if (byteLength === undefined) {
  13451. if (data instanceof Array) {
  13452. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13453. }
  13454. else {
  13455. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13456. }
  13457. }
  13458. else {
  13459. if (data instanceof Array) {
  13460. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13461. }
  13462. else {
  13463. if (data instanceof ArrayBuffer) {
  13464. data = new Uint8Array(data, byteOffset, byteLength);
  13465. }
  13466. else {
  13467. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13468. }
  13469. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13470. }
  13471. }
  13472. this._resetVertexBufferBinding();
  13473. };
  13474. Engine.prototype._resetIndexBufferBinding = function () {
  13475. this.bindIndexBuffer(null);
  13476. this._cachedIndexBuffer = null;
  13477. };
  13478. /**
  13479. * Creates a new index buffer
  13480. * @param indices defines the content of the index buffer
  13481. * @param updatable defines if the index buffer must be updatable
  13482. * @returns a new webGL buffer
  13483. */
  13484. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13485. var vbo = this._gl.createBuffer();
  13486. if (!vbo) {
  13487. throw new Error("Unable to create index buffer");
  13488. }
  13489. this.bindIndexBuffer(vbo);
  13490. // Check for 32 bits indices
  13491. var arrayBuffer;
  13492. var need32Bits = false;
  13493. if (indices instanceof Uint16Array) {
  13494. arrayBuffer = indices;
  13495. }
  13496. else {
  13497. //check 32 bit support
  13498. if (this._caps.uintIndices) {
  13499. if (indices instanceof Uint32Array) {
  13500. arrayBuffer = indices;
  13501. need32Bits = true;
  13502. }
  13503. else {
  13504. //number[] or Int32Array, check if 32 bit is necessary
  13505. for (var index = 0; index < indices.length; index++) {
  13506. if (indices[index] > 65535) {
  13507. need32Bits = true;
  13508. break;
  13509. }
  13510. }
  13511. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13512. }
  13513. }
  13514. else {
  13515. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13516. arrayBuffer = new Uint16Array(indices);
  13517. }
  13518. }
  13519. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13520. this._resetIndexBufferBinding();
  13521. vbo.references = 1;
  13522. vbo.is32Bits = need32Bits;
  13523. return vbo;
  13524. };
  13525. /**
  13526. * Bind a webGL buffer to the webGL context
  13527. * @param buffer defines the buffer to bind
  13528. */
  13529. Engine.prototype.bindArrayBuffer = function (buffer) {
  13530. if (!this._vaoRecordInProgress) {
  13531. this._unbindVertexArrayObject();
  13532. }
  13533. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13534. };
  13535. /**
  13536. * Bind an uniform buffer to the current webGL context
  13537. * @param buffer defines the buffer to bind
  13538. */
  13539. Engine.prototype.bindUniformBuffer = function (buffer) {
  13540. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13541. };
  13542. /**
  13543. * Bind a buffer to the current webGL context at a given location
  13544. * @param buffer defines the buffer to bind
  13545. * @param location defines the index where to bind the buffer
  13546. */
  13547. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13548. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13549. };
  13550. /**
  13551. * Bind a specific block at a given index in a specific shader program
  13552. * @param shaderProgram defines the shader program
  13553. * @param blockName defines the block name
  13554. * @param index defines the index where to bind the block
  13555. */
  13556. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13557. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13558. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13559. };
  13560. ;
  13561. Engine.prototype.bindIndexBuffer = function (buffer) {
  13562. if (!this._vaoRecordInProgress) {
  13563. this._unbindVertexArrayObject();
  13564. }
  13565. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13566. };
  13567. Engine.prototype.bindBuffer = function (buffer, target) {
  13568. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13569. this._gl.bindBuffer(target, buffer);
  13570. this._currentBoundBuffer[target] = buffer;
  13571. }
  13572. };
  13573. /**
  13574. * update the bound buffer with the given data
  13575. * @param data defines the data to update
  13576. */
  13577. Engine.prototype.updateArrayBuffer = function (data) {
  13578. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13579. };
  13580. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13581. var pointer = this._currentBufferPointers[indx];
  13582. var changed = false;
  13583. if (!pointer.active) {
  13584. changed = true;
  13585. pointer.active = true;
  13586. pointer.index = indx;
  13587. pointer.size = size;
  13588. pointer.type = type;
  13589. pointer.normalized = normalized;
  13590. pointer.stride = stride;
  13591. pointer.offset = offset;
  13592. pointer.buffer = buffer;
  13593. }
  13594. else {
  13595. if (pointer.buffer !== buffer) {
  13596. pointer.buffer = buffer;
  13597. changed = true;
  13598. }
  13599. if (pointer.size !== size) {
  13600. pointer.size = size;
  13601. changed = true;
  13602. }
  13603. if (pointer.type !== type) {
  13604. pointer.type = type;
  13605. changed = true;
  13606. }
  13607. if (pointer.normalized !== normalized) {
  13608. pointer.normalized = normalized;
  13609. changed = true;
  13610. }
  13611. if (pointer.stride !== stride) {
  13612. pointer.stride = stride;
  13613. changed = true;
  13614. }
  13615. if (pointer.offset !== offset) {
  13616. pointer.offset = offset;
  13617. changed = true;
  13618. }
  13619. }
  13620. if (changed || this._vaoRecordInProgress) {
  13621. this.bindArrayBuffer(buffer);
  13622. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13623. }
  13624. };
  13625. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13626. if (indexBuffer == null) {
  13627. return;
  13628. }
  13629. if (this._cachedIndexBuffer !== indexBuffer) {
  13630. this._cachedIndexBuffer = indexBuffer;
  13631. this.bindIndexBuffer(indexBuffer);
  13632. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13633. }
  13634. };
  13635. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13636. var attributes = effect.getAttributesNames();
  13637. if (!this._vaoRecordInProgress) {
  13638. this._unbindVertexArrayObject();
  13639. }
  13640. this.unbindAllAttributes();
  13641. for (var index = 0; index < attributes.length; index++) {
  13642. var order = effect.getAttributeLocation(index);
  13643. if (order >= 0) {
  13644. var vertexBuffer = vertexBuffers[attributes[index]];
  13645. if (!vertexBuffer) {
  13646. continue;
  13647. }
  13648. this._gl.enableVertexAttribArray(order);
  13649. if (!this._vaoRecordInProgress) {
  13650. this._vertexAttribArraysEnabled[order] = true;
  13651. }
  13652. var buffer = vertexBuffer.getBuffer();
  13653. if (buffer) {
  13654. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13655. if (vertexBuffer.getIsInstanced()) {
  13656. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13657. if (!this._vaoRecordInProgress) {
  13658. this._currentInstanceLocations.push(order);
  13659. this._currentInstanceBuffers.push(buffer);
  13660. }
  13661. }
  13662. }
  13663. }
  13664. }
  13665. };
  13666. /**
  13667. * Records a vertex array object
  13668. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13669. * @param vertexBuffers defines the list of vertex buffers to store
  13670. * @param indexBuffer defines the index buffer to store
  13671. * @param effect defines the effect to store
  13672. * @returns the new vertex array object
  13673. */
  13674. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13675. var vao = this._gl.createVertexArray();
  13676. this._vaoRecordInProgress = true;
  13677. this._gl.bindVertexArray(vao);
  13678. this._mustWipeVertexAttributes = true;
  13679. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13680. this.bindIndexBuffer(indexBuffer);
  13681. this._vaoRecordInProgress = false;
  13682. this._gl.bindVertexArray(null);
  13683. return vao;
  13684. };
  13685. /**
  13686. * Bind a specific vertex array object
  13687. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13688. * @param vertexArrayObject defines the vertex array object to bind
  13689. * @param indexBuffer defines the index buffer to bind
  13690. */
  13691. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13692. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13693. this._cachedVertexArrayObject = vertexArrayObject;
  13694. this._gl.bindVertexArray(vertexArrayObject);
  13695. this._cachedVertexBuffers = null;
  13696. this._cachedIndexBuffer = null;
  13697. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13698. this._mustWipeVertexAttributes = true;
  13699. }
  13700. };
  13701. /**
  13702. * Bind webGl buffers directly to the webGL context
  13703. * @param vertexBuffer defines the vertex buffer to bind
  13704. * @param indexBuffer defines the index buffer to bind
  13705. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13706. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13707. * @param effect defines the effect associated with the vertex buffer
  13708. */
  13709. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13710. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13711. this._cachedVertexBuffers = vertexBuffer;
  13712. this._cachedEffectForVertexBuffers = effect;
  13713. var attributesCount = effect.getAttributesCount();
  13714. this._unbindVertexArrayObject();
  13715. this.unbindAllAttributes();
  13716. var offset = 0;
  13717. for (var index = 0; index < attributesCount; index++) {
  13718. if (index < vertexDeclaration.length) {
  13719. var order = effect.getAttributeLocation(index);
  13720. if (order >= 0) {
  13721. this._gl.enableVertexAttribArray(order);
  13722. this._vertexAttribArraysEnabled[order] = true;
  13723. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13724. }
  13725. offset += vertexDeclaration[index] * 4;
  13726. }
  13727. }
  13728. }
  13729. this._bindIndexBufferWithCache(indexBuffer);
  13730. };
  13731. Engine.prototype._unbindVertexArrayObject = function () {
  13732. if (!this._cachedVertexArrayObject) {
  13733. return;
  13734. }
  13735. this._cachedVertexArrayObject = null;
  13736. this._gl.bindVertexArray(null);
  13737. };
  13738. /**
  13739. * Bind a list of vertex buffers to the webGL context
  13740. * @param vertexBuffers defines the list of vertex buffers to bind
  13741. * @param indexBuffer defines the index buffer to bind
  13742. * @param effect defines the effect associated with the vertex buffers
  13743. */
  13744. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13745. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13746. this._cachedVertexBuffers = vertexBuffers;
  13747. this._cachedEffectForVertexBuffers = effect;
  13748. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13749. }
  13750. this._bindIndexBufferWithCache(indexBuffer);
  13751. };
  13752. /**
  13753. * Unbind all instance attributes
  13754. */
  13755. Engine.prototype.unbindInstanceAttributes = function () {
  13756. var boundBuffer;
  13757. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13758. var instancesBuffer = this._currentInstanceBuffers[i];
  13759. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13760. boundBuffer = instancesBuffer;
  13761. this.bindArrayBuffer(instancesBuffer);
  13762. }
  13763. var offsetLocation = this._currentInstanceLocations[i];
  13764. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13765. }
  13766. this._currentInstanceBuffers.length = 0;
  13767. this._currentInstanceLocations.length = 0;
  13768. };
  13769. /**
  13770. * Release and free the memory of a vertex array object
  13771. * @param vao defines the vertex array object to delete
  13772. */
  13773. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13774. this._gl.deleteVertexArray(vao);
  13775. };
  13776. /** @hidden */
  13777. Engine.prototype._releaseBuffer = function (buffer) {
  13778. buffer.references--;
  13779. if (buffer.references === 0) {
  13780. this._gl.deleteBuffer(buffer);
  13781. return true;
  13782. }
  13783. return false;
  13784. };
  13785. /**
  13786. * Creates a webGL buffer to use with instanciation
  13787. * @param capacity defines the size of the buffer
  13788. * @returns the webGL buffer
  13789. */
  13790. Engine.prototype.createInstancesBuffer = function (capacity) {
  13791. var buffer = this._gl.createBuffer();
  13792. if (!buffer) {
  13793. throw new Error("Unable to create instance buffer");
  13794. }
  13795. buffer.capacity = capacity;
  13796. this.bindArrayBuffer(buffer);
  13797. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13798. return buffer;
  13799. };
  13800. /**
  13801. * Delete a webGL buffer used with instanciation
  13802. * @param buffer defines the webGL buffer to delete
  13803. */
  13804. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13805. this._gl.deleteBuffer(buffer);
  13806. };
  13807. /**
  13808. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13809. * @param instancesBuffer defines the webGL buffer to update and bind
  13810. * @param data defines the data to store in the buffer
  13811. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13812. */
  13813. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13814. this.bindArrayBuffer(instancesBuffer);
  13815. if (data) {
  13816. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13817. }
  13818. if (offsetLocations[0].index !== undefined) {
  13819. var stride = 0;
  13820. for (var i = 0; i < offsetLocations.length; i++) {
  13821. var ai = offsetLocations[i];
  13822. stride += ai.attributeSize * 4;
  13823. }
  13824. for (var i = 0; i < offsetLocations.length; i++) {
  13825. var ai = offsetLocations[i];
  13826. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13827. this._gl.enableVertexAttribArray(ai.index);
  13828. this._vertexAttribArraysEnabled[ai.index] = true;
  13829. }
  13830. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13831. this._gl.vertexAttribDivisor(ai.index, 1);
  13832. this._currentInstanceLocations.push(ai.index);
  13833. this._currentInstanceBuffers.push(instancesBuffer);
  13834. }
  13835. }
  13836. else {
  13837. for (var index = 0; index < 4; index++) {
  13838. var offsetLocation = offsetLocations[index];
  13839. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13840. this._gl.enableVertexAttribArray(offsetLocation);
  13841. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13842. }
  13843. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13844. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13845. this._currentInstanceLocations.push(offsetLocation);
  13846. this._currentInstanceBuffers.push(instancesBuffer);
  13847. }
  13848. }
  13849. };
  13850. /**
  13851. * Apply all cached states (depth, culling, stencil and alpha)
  13852. */
  13853. Engine.prototype.applyStates = function () {
  13854. this._depthCullingState.apply(this._gl);
  13855. this._stencilState.apply(this._gl);
  13856. this._alphaState.apply(this._gl);
  13857. };
  13858. /**
  13859. * Send a draw order
  13860. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13861. * @param indexStart defines the starting index
  13862. * @param indexCount defines the number of index to draw
  13863. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13864. */
  13865. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13866. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13867. };
  13868. /**
  13869. * Draw a list of points
  13870. * @param verticesStart defines the index of first vertex to draw
  13871. * @param verticesCount defines the count of vertices to draw
  13872. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13873. */
  13874. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13875. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13876. };
  13877. /**
  13878. * Draw a list of unindexed primitives
  13879. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13880. * @param verticesStart defines the index of first vertex to draw
  13881. * @param verticesCount defines the count of vertices to draw
  13882. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13883. */
  13884. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13885. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13886. };
  13887. /**
  13888. * Draw a list of indexed primitives
  13889. * @param fillMode defines the primitive to use
  13890. * @param indexStart defines the starting index
  13891. * @param indexCount defines the number of index to draw
  13892. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13893. */
  13894. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13895. // Apply states
  13896. this.applyStates();
  13897. this._drawCalls.addCount(1, false);
  13898. // Render
  13899. var drawMode = this._drawMode(fillMode);
  13900. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13901. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13902. if (instancesCount) {
  13903. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13904. }
  13905. else {
  13906. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13907. }
  13908. };
  13909. /**
  13910. * Draw a list of unindexed primitives
  13911. * @param fillMode defines the primitive to use
  13912. * @param verticesStart defines the index of first vertex to draw
  13913. * @param verticesCount defines the count of vertices to draw
  13914. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13915. */
  13916. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13917. // Apply states
  13918. this.applyStates();
  13919. this._drawCalls.addCount(1, false);
  13920. var drawMode = this._drawMode(fillMode);
  13921. if (instancesCount) {
  13922. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13923. }
  13924. else {
  13925. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13926. }
  13927. };
  13928. Engine.prototype._drawMode = function (fillMode) {
  13929. switch (fillMode) {
  13930. // Triangle views
  13931. case BABYLON.Material.TriangleFillMode:
  13932. return this._gl.TRIANGLES;
  13933. case BABYLON.Material.PointFillMode:
  13934. return this._gl.POINTS;
  13935. case BABYLON.Material.WireFrameFillMode:
  13936. return this._gl.LINES;
  13937. // Draw modes
  13938. case BABYLON.Material.PointListDrawMode:
  13939. return this._gl.POINTS;
  13940. case BABYLON.Material.LineListDrawMode:
  13941. return this._gl.LINES;
  13942. case BABYLON.Material.LineLoopDrawMode:
  13943. return this._gl.LINE_LOOP;
  13944. case BABYLON.Material.LineStripDrawMode:
  13945. return this._gl.LINE_STRIP;
  13946. case BABYLON.Material.TriangleStripDrawMode:
  13947. return this._gl.TRIANGLE_STRIP;
  13948. case BABYLON.Material.TriangleFanDrawMode:
  13949. return this._gl.TRIANGLE_FAN;
  13950. default:
  13951. return this._gl.TRIANGLES;
  13952. }
  13953. };
  13954. // Shaders
  13955. /** @hidden */
  13956. Engine.prototype._releaseEffect = function (effect) {
  13957. if (this._compiledEffects[effect._key]) {
  13958. delete this._compiledEffects[effect._key];
  13959. this._deleteProgram(effect.getProgram());
  13960. }
  13961. };
  13962. /** @hidden */
  13963. Engine.prototype._deleteProgram = function (program) {
  13964. if (program) {
  13965. program.__SPECTOR_rebuildProgram = null;
  13966. if (program.transformFeedback) {
  13967. this.deleteTransformFeedback(program.transformFeedback);
  13968. program.transformFeedback = null;
  13969. }
  13970. this._gl.deleteProgram(program);
  13971. }
  13972. };
  13973. /**
  13974. * Create a new effect (used to store vertex/fragment shaders)
  13975. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13976. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13977. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13978. * @param samplers defines an array of string used to represent textures
  13979. * @param defines defines the string containing the defines to use to compile the shaders
  13980. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13981. * @param onCompiled defines a function to call when the effect creation is successful
  13982. * @param onError defines a function to call when the effect creation has failed
  13983. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13984. * @returns the new Effect
  13985. */
  13986. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13987. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13988. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13989. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13990. if (this._compiledEffects[name]) {
  13991. var compiledEffect = this._compiledEffects[name];
  13992. if (onCompiled && compiledEffect.isReady()) {
  13993. onCompiled(compiledEffect);
  13994. }
  13995. return compiledEffect;
  13996. }
  13997. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13998. effect._key = name;
  13999. this._compiledEffects[name] = effect;
  14000. return effect;
  14001. };
  14002. /**
  14003. * Create an effect to use with particle systems
  14004. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  14005. * @param uniformsNames defines a list of attribute names
  14006. * @param samplers defines an array of string used to represent textures
  14007. * @param defines defines the string containing the defines to use to compile the shaders
  14008. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14009. * @param onCompiled defines a function to call when the effect creation is successful
  14010. * @param onError defines a function to call when the effect creation has failed
  14011. * @returns the new Effect
  14012. */
  14013. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  14014. if (uniformsNames === void 0) { uniformsNames = []; }
  14015. if (samplers === void 0) { samplers = []; }
  14016. if (defines === void 0) { defines = ""; }
  14017. return this.createEffect({
  14018. vertex: "particles",
  14019. fragmentElement: fragmentName
  14020. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  14021. };
  14022. /**
  14023. * Directly creates a webGL program
  14024. * @param vertexCode defines the vertex shader code to use
  14025. * @param fragmentCode defines the fragment shader code to use
  14026. * @param context defines the webGL context to use (if not set, the current one will be used)
  14027. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14028. * @returns the new webGL program
  14029. */
  14030. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14031. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14032. context = context || this._gl;
  14033. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  14034. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  14035. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14036. };
  14037. /**
  14038. * Creates a webGL program
  14039. * @param vertexCode defines the vertex shader code to use
  14040. * @param fragmentCode defines the fragment shader code to use
  14041. * @param defines defines the string containing the defines to use to compile the shaders
  14042. * @param context defines the webGL context to use (if not set, the current one will be used)
  14043. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14044. * @returns the new webGL program
  14045. */
  14046. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14047. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14048. context = context || this._gl;
  14049. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14050. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14051. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  14052. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  14053. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14054. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14055. return program;
  14056. };
  14057. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14058. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14059. var shaderProgram = context.createProgram();
  14060. if (!shaderProgram) {
  14061. throw new Error("Unable to create program");
  14062. }
  14063. context.attachShader(shaderProgram, vertexShader);
  14064. context.attachShader(shaderProgram, fragmentShader);
  14065. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14066. var transformFeedback = this.createTransformFeedback();
  14067. this.bindTransformFeedback(transformFeedback);
  14068. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14069. shaderProgram.transformFeedback = transformFeedback;
  14070. }
  14071. context.linkProgram(shaderProgram);
  14072. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14073. this.bindTransformFeedback(null);
  14074. }
  14075. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14076. if (!linked) {
  14077. context.validateProgram(shaderProgram);
  14078. var error = context.getProgramInfoLog(shaderProgram);
  14079. if (error) {
  14080. throw new Error(error);
  14081. }
  14082. }
  14083. context.deleteShader(vertexShader);
  14084. context.deleteShader(fragmentShader);
  14085. return shaderProgram;
  14086. };
  14087. /**
  14088. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14089. * @param shaderProgram defines the webGL program to use
  14090. * @param uniformsNames defines the list of uniform names
  14091. * @returns an array of webGL uniform locations
  14092. */
  14093. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14094. var results = new Array();
  14095. for (var index = 0; index < uniformsNames.length; index++) {
  14096. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14097. }
  14098. return results;
  14099. };
  14100. /**
  14101. * Gets the lsit of active attributes for a given webGL program
  14102. * @param shaderProgram defines the webGL program to use
  14103. * @param attributesNames defines the list of attribute names to get
  14104. * @returns an array of indices indicating the offset of each attribute
  14105. */
  14106. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14107. var results = [];
  14108. for (var index = 0; index < attributesNames.length; index++) {
  14109. try {
  14110. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14111. }
  14112. catch (e) {
  14113. results.push(-1);
  14114. }
  14115. }
  14116. return results;
  14117. };
  14118. /**
  14119. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14120. * @param effect defines the effect to activate
  14121. */
  14122. Engine.prototype.enableEffect = function (effect) {
  14123. if (!effect) {
  14124. return;
  14125. }
  14126. // Use program
  14127. this.bindSamplers(effect);
  14128. this._currentEffect = effect;
  14129. if (effect.onBind) {
  14130. effect.onBind(effect);
  14131. }
  14132. effect.onBindObservable.notifyObservers(effect);
  14133. };
  14134. /**
  14135. * Set the value of an uniform to an array of int32
  14136. * @param uniform defines the webGL uniform location where to store the value
  14137. * @param array defines the array of int32 to store
  14138. */
  14139. Engine.prototype.setIntArray = function (uniform, array) {
  14140. if (!uniform)
  14141. return;
  14142. this._gl.uniform1iv(uniform, array);
  14143. };
  14144. /**
  14145. * Set the value of an uniform to an array of int32 (stored as vec2)
  14146. * @param uniform defines the webGL uniform location where to store the value
  14147. * @param array defines the array of int32 to store
  14148. */
  14149. Engine.prototype.setIntArray2 = function (uniform, array) {
  14150. if (!uniform || array.length % 2 !== 0)
  14151. return;
  14152. this._gl.uniform2iv(uniform, array);
  14153. };
  14154. /**
  14155. * Set the value of an uniform to an array of int32 (stored as vec3)
  14156. * @param uniform defines the webGL uniform location where to store the value
  14157. * @param array defines the array of int32 to store
  14158. */
  14159. Engine.prototype.setIntArray3 = function (uniform, array) {
  14160. if (!uniform || array.length % 3 !== 0)
  14161. return;
  14162. this._gl.uniform3iv(uniform, array);
  14163. };
  14164. /**
  14165. * Set the value of an uniform to an array of int32 (stored as vec4)
  14166. * @param uniform defines the webGL uniform location where to store the value
  14167. * @param array defines the array of int32 to store
  14168. */
  14169. Engine.prototype.setIntArray4 = function (uniform, array) {
  14170. if (!uniform || array.length % 4 !== 0)
  14171. return;
  14172. this._gl.uniform4iv(uniform, array);
  14173. };
  14174. /**
  14175. * Set the value of an uniform to an array of float32
  14176. * @param uniform defines the webGL uniform location where to store the value
  14177. * @param array defines the array of float32 to store
  14178. */
  14179. Engine.prototype.setFloatArray = function (uniform, array) {
  14180. if (!uniform)
  14181. return;
  14182. this._gl.uniform1fv(uniform, array);
  14183. };
  14184. /**
  14185. * Set the value of an uniform to an array of float32 (stored as vec2)
  14186. * @param uniform defines the webGL uniform location where to store the value
  14187. * @param array defines the array of float32 to store
  14188. */
  14189. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14190. if (!uniform || array.length % 2 !== 0)
  14191. return;
  14192. this._gl.uniform2fv(uniform, array);
  14193. };
  14194. /**
  14195. * Set the value of an uniform to an array of float32 (stored as vec3)
  14196. * @param uniform defines the webGL uniform location where to store the value
  14197. * @param array defines the array of float32 to store
  14198. */
  14199. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14200. if (!uniform || array.length % 3 !== 0)
  14201. return;
  14202. this._gl.uniform3fv(uniform, array);
  14203. };
  14204. /**
  14205. * Set the value of an uniform to an array of float32 (stored as vec4)
  14206. * @param uniform defines the webGL uniform location where to store the value
  14207. * @param array defines the array of float32 to store
  14208. */
  14209. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14210. if (!uniform || array.length % 4 !== 0)
  14211. return;
  14212. this._gl.uniform4fv(uniform, array);
  14213. };
  14214. /**
  14215. * Set the value of an uniform to an array of number
  14216. * @param uniform defines the webGL uniform location where to store the value
  14217. * @param array defines the array of number to store
  14218. */
  14219. Engine.prototype.setArray = function (uniform, array) {
  14220. if (!uniform)
  14221. return;
  14222. this._gl.uniform1fv(uniform, array);
  14223. };
  14224. /**
  14225. * Set the value of an uniform to an array of number (stored as vec2)
  14226. * @param uniform defines the webGL uniform location where to store the value
  14227. * @param array defines the array of number to store
  14228. */
  14229. Engine.prototype.setArray2 = function (uniform, array) {
  14230. if (!uniform || array.length % 2 !== 0)
  14231. return;
  14232. this._gl.uniform2fv(uniform, array);
  14233. };
  14234. /**
  14235. * Set the value of an uniform to an array of number (stored as vec3)
  14236. * @param uniform defines the webGL uniform location where to store the value
  14237. * @param array defines the array of number to store
  14238. */
  14239. Engine.prototype.setArray3 = function (uniform, array) {
  14240. if (!uniform || array.length % 3 !== 0)
  14241. return;
  14242. this._gl.uniform3fv(uniform, array);
  14243. };
  14244. /**
  14245. * Set the value of an uniform to an array of number (stored as vec4)
  14246. * @param uniform defines the webGL uniform location where to store the value
  14247. * @param array defines the array of number to store
  14248. */
  14249. Engine.prototype.setArray4 = function (uniform, array) {
  14250. if (!uniform || array.length % 4 !== 0)
  14251. return;
  14252. this._gl.uniform4fv(uniform, array);
  14253. };
  14254. /**
  14255. * Set the value of an uniform to an array of float32 (stored as matrices)
  14256. * @param uniform defines the webGL uniform location where to store the value
  14257. * @param matrices defines the array of float32 to store
  14258. */
  14259. Engine.prototype.setMatrices = function (uniform, matrices) {
  14260. if (!uniform)
  14261. return;
  14262. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14263. };
  14264. /**
  14265. * Set the value of an uniform to a matrix
  14266. * @param uniform defines the webGL uniform location where to store the value
  14267. * @param matrix defines the matrix to store
  14268. */
  14269. Engine.prototype.setMatrix = function (uniform, matrix) {
  14270. if (!uniform)
  14271. return;
  14272. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14273. };
  14274. /**
  14275. * Set the value of an uniform to a matrix (3x3)
  14276. * @param uniform defines the webGL uniform location where to store the value
  14277. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14278. */
  14279. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14280. if (!uniform)
  14281. return;
  14282. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14283. };
  14284. /**
  14285. * Set the value of an uniform to a matrix (2x2)
  14286. * @param uniform defines the webGL uniform location where to store the value
  14287. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14288. */
  14289. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14290. if (!uniform)
  14291. return;
  14292. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14293. };
  14294. /**
  14295. * Set the value of an uniform to a number (int)
  14296. * @param uniform defines the webGL uniform location where to store the value
  14297. * @param value defines the int number to store
  14298. */
  14299. Engine.prototype.setInt = function (uniform, value) {
  14300. if (!uniform)
  14301. return;
  14302. this._gl.uniform1i(uniform, value);
  14303. };
  14304. /**
  14305. * Set the value of an uniform to a number (float)
  14306. * @param uniform defines the webGL uniform location where to store the value
  14307. * @param value defines the float number to store
  14308. */
  14309. Engine.prototype.setFloat = function (uniform, value) {
  14310. if (!uniform)
  14311. return;
  14312. this._gl.uniform1f(uniform, value);
  14313. };
  14314. /**
  14315. * Set the value of an uniform to a vec2
  14316. * @param uniform defines the webGL uniform location where to store the value
  14317. * @param x defines the 1st component of the value
  14318. * @param y defines the 2nd component of the value
  14319. */
  14320. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14321. if (!uniform)
  14322. return;
  14323. this._gl.uniform2f(uniform, x, y);
  14324. };
  14325. /**
  14326. * Set the value of an uniform to a vec3
  14327. * @param uniform defines the webGL uniform location where to store the value
  14328. * @param x defines the 1st component of the value
  14329. * @param y defines the 2nd component of the value
  14330. * @param z defines the 3rd component of the value
  14331. */
  14332. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14333. if (!uniform)
  14334. return;
  14335. this._gl.uniform3f(uniform, x, y, z);
  14336. };
  14337. /**
  14338. * Set the value of an uniform to a boolean
  14339. * @param uniform defines the webGL uniform location where to store the value
  14340. * @param bool defines the boolean to store
  14341. */
  14342. Engine.prototype.setBool = function (uniform, bool) {
  14343. if (!uniform)
  14344. return;
  14345. this._gl.uniform1i(uniform, bool);
  14346. };
  14347. /**
  14348. * Set the value of an uniform to a vec4
  14349. * @param uniform defines the webGL uniform location where to store the value
  14350. * @param x defines the 1st component of the value
  14351. * @param y defines the 2nd component of the value
  14352. * @param z defines the 3rd component of the value
  14353. * @param w defines the 4th component of the value
  14354. */
  14355. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14356. if (!uniform)
  14357. return;
  14358. this._gl.uniform4f(uniform, x, y, z, w);
  14359. };
  14360. /**
  14361. * Set the value of an uniform to a Color3
  14362. * @param uniform defines the webGL uniform location where to store the value
  14363. * @param color3 defines the color to store
  14364. */
  14365. Engine.prototype.setColor3 = function (uniform, color3) {
  14366. if (!uniform)
  14367. return;
  14368. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14369. };
  14370. /**
  14371. * Set the value of an uniform to a Color3 and an alpha value
  14372. * @param uniform defines the webGL uniform location where to store the value
  14373. * @param color3 defines the color to store
  14374. * @param alpha defines the alpha component to store
  14375. */
  14376. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14377. if (!uniform)
  14378. return;
  14379. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14380. };
  14381. /**
  14382. * Sets a Color4 on a uniform variable
  14383. * @param uniform defines the uniform location
  14384. * @param color4 defines the value to be set
  14385. */
  14386. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14387. if (!uniform)
  14388. return;
  14389. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14390. };
  14391. // States
  14392. /**
  14393. * Set various states to the webGL context
  14394. * @param culling defines backface culling state
  14395. * @param zOffset defines the value to apply to zOffset (0 by default)
  14396. * @param force defines if states must be applied even if cache is up to date
  14397. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14398. */
  14399. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14400. if (zOffset === void 0) { zOffset = 0; }
  14401. if (reverseSide === void 0) { reverseSide = false; }
  14402. // Culling
  14403. if (this._depthCullingState.cull !== culling || force) {
  14404. this._depthCullingState.cull = culling;
  14405. }
  14406. // Cull face
  14407. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14408. if (this._depthCullingState.cullFace !== cullFace || force) {
  14409. this._depthCullingState.cullFace = cullFace;
  14410. }
  14411. // Z offset
  14412. this.setZOffset(zOffset);
  14413. // Front face
  14414. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14415. if (this._depthCullingState.frontFace !== frontFace || force) {
  14416. this._depthCullingState.frontFace = frontFace;
  14417. }
  14418. };
  14419. /**
  14420. * Set the z offset to apply to current rendering
  14421. * @param value defines the offset to apply
  14422. */
  14423. Engine.prototype.setZOffset = function (value) {
  14424. this._depthCullingState.zOffset = value;
  14425. };
  14426. /**
  14427. * Gets the current value of the zOffset
  14428. * @returns the current zOffset state
  14429. */
  14430. Engine.prototype.getZOffset = function () {
  14431. return this._depthCullingState.zOffset;
  14432. };
  14433. /**
  14434. * Enable or disable depth buffering
  14435. * @param enable defines the state to set
  14436. */
  14437. Engine.prototype.setDepthBuffer = function (enable) {
  14438. this._depthCullingState.depthTest = enable;
  14439. };
  14440. /**
  14441. * Gets a boolean indicating if depth writing is enabled
  14442. * @returns the current depth writing state
  14443. */
  14444. Engine.prototype.getDepthWrite = function () {
  14445. return this._depthCullingState.depthMask;
  14446. };
  14447. /**
  14448. * Enable or disable depth writing
  14449. * @param enable defines the state to set
  14450. */
  14451. Engine.prototype.setDepthWrite = function (enable) {
  14452. this._depthCullingState.depthMask = enable;
  14453. };
  14454. /**
  14455. * Enable or disable color writing
  14456. * @param enable defines the state to set
  14457. */
  14458. Engine.prototype.setColorWrite = function (enable) {
  14459. this._gl.colorMask(enable, enable, enable, enable);
  14460. this._colorWrite = enable;
  14461. };
  14462. /**
  14463. * Gets a boolean indicating if color writing is enabled
  14464. * @returns the current color writing state
  14465. */
  14466. Engine.prototype.getColorWrite = function () {
  14467. return this._colorWrite;
  14468. };
  14469. /**
  14470. * Sets alpha constants used by some alpha blending modes
  14471. * @param r defines the red component
  14472. * @param g defines the green component
  14473. * @param b defines the blue component
  14474. * @param a defines the alpha component
  14475. */
  14476. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14477. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14478. };
  14479. /**
  14480. * Sets the current alpha mode
  14481. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14482. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14483. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14484. */
  14485. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14486. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14487. if (this._alphaMode === mode) {
  14488. return;
  14489. }
  14490. switch (mode) {
  14491. case Engine.ALPHA_DISABLE:
  14492. this._alphaState.alphaBlend = false;
  14493. break;
  14494. case Engine.ALPHA_PREMULTIPLIED:
  14495. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14496. this._alphaState.alphaBlend = true;
  14497. break;
  14498. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14499. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14500. this._alphaState.alphaBlend = true;
  14501. break;
  14502. case Engine.ALPHA_COMBINE:
  14503. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14504. this._alphaState.alphaBlend = true;
  14505. break;
  14506. case Engine.ALPHA_ONEONE:
  14507. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14508. this._alphaState.alphaBlend = true;
  14509. break;
  14510. case Engine.ALPHA_ADD:
  14511. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14512. this._alphaState.alphaBlend = true;
  14513. break;
  14514. case Engine.ALPHA_SUBTRACT:
  14515. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14516. this._alphaState.alphaBlend = true;
  14517. break;
  14518. case Engine.ALPHA_MULTIPLY:
  14519. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14520. this._alphaState.alphaBlend = true;
  14521. break;
  14522. case Engine.ALPHA_MAXIMIZED:
  14523. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14524. this._alphaState.alphaBlend = true;
  14525. break;
  14526. case Engine.ALPHA_INTERPOLATE:
  14527. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14528. this._alphaState.alphaBlend = true;
  14529. break;
  14530. case Engine.ALPHA_SCREENMODE:
  14531. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14532. this._alphaState.alphaBlend = true;
  14533. break;
  14534. }
  14535. if (!noDepthWriteChange) {
  14536. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14537. }
  14538. this._alphaMode = mode;
  14539. };
  14540. /**
  14541. * Gets the current alpha mode
  14542. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14543. * @returns the current alpha mode
  14544. */
  14545. Engine.prototype.getAlphaMode = function () {
  14546. return this._alphaMode;
  14547. };
  14548. // Textures
  14549. /**
  14550. * Force the entire cache to be cleared
  14551. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14552. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14553. */
  14554. Engine.prototype.wipeCaches = function (bruteForce) {
  14555. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14556. return;
  14557. }
  14558. this._currentEffect = null;
  14559. if (bruteForce) {
  14560. this.resetTextureCache();
  14561. this._currentProgram = null;
  14562. this._stencilState.reset();
  14563. this._depthCullingState.reset();
  14564. this.setDepthFunctionToLessOrEqual();
  14565. this._alphaState.reset();
  14566. }
  14567. this._resetVertexBufferBinding();
  14568. this._cachedIndexBuffer = null;
  14569. this._cachedEffectForVertexBuffers = null;
  14570. this._unbindVertexArrayObject();
  14571. this.bindIndexBuffer(null);
  14572. };
  14573. /**
  14574. * Set the compressed texture format to use, based on the formats you have, and the formats
  14575. * supported by the hardware / browser.
  14576. *
  14577. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14578. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14579. * to API arguments needed to compressed textures. This puts the burden on the container
  14580. * generator to house the arcane code for determining these for current & future formats.
  14581. *
  14582. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14583. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14584. *
  14585. * Note: The result of this call is not taken into account when a texture is base64.
  14586. *
  14587. * @param formatsAvailable defines the list of those format families you have created
  14588. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14589. *
  14590. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14591. * @returns The extension selected.
  14592. */
  14593. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14594. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14595. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14596. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14597. return this._textureFormatInUse = this._texturesSupported[i];
  14598. }
  14599. }
  14600. }
  14601. // actively set format to nothing, to allow this to be called more than once
  14602. // and possibly fail the 2nd time
  14603. this._textureFormatInUse = null;
  14604. return null;
  14605. };
  14606. /** @hidden */
  14607. Engine.prototype._createTexture = function () {
  14608. var texture = this._gl.createTexture();
  14609. if (!texture) {
  14610. throw new Error("Unable to create texture");
  14611. }
  14612. return texture;
  14613. };
  14614. /**
  14615. * Usually called from BABYLON.Texture.ts.
  14616. * Passed information to create a WebGLTexture
  14617. * @param urlArg defines a value which contains one of the following:
  14618. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14619. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14620. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14621. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14622. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14623. * @param scene needed for loading to the correct scene
  14624. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14625. * @param onLoad optional callback to be called upon successful completion
  14626. * @param onError optional callback to be called upon failure
  14627. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  14628. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14629. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14630. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14631. */
  14632. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14633. var _this = this;
  14634. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14635. if (onLoad === void 0) { onLoad = null; }
  14636. if (onError === void 0) { onError = null; }
  14637. if (buffer === void 0) { buffer = null; }
  14638. if (fallback === void 0) { fallback = null; }
  14639. if (format === void 0) { format = null; }
  14640. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14641. var fromData = url.substr(0, 5) === "data:";
  14642. var fromBlob = url.substr(0, 5) === "blob:";
  14643. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14644. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14645. // establish the file extension, if possible
  14646. var lastDot = url.lastIndexOf('.');
  14647. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14648. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14649. var isTGA = (extension.indexOf(".tga") === 0);
  14650. // determine if a ktx file should be substituted
  14651. var isKTX = false;
  14652. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14653. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14654. isKTX = true;
  14655. }
  14656. if (scene) {
  14657. scene._addPendingData(texture);
  14658. }
  14659. texture.url = url;
  14660. texture.generateMipMaps = !noMipmap;
  14661. texture.samplingMode = samplingMode;
  14662. texture.invertY = invertY;
  14663. if (!this._doNotHandleContextLost) {
  14664. // Keep a link to the buffer only if we plan to handle context lost
  14665. texture._buffer = buffer;
  14666. }
  14667. var onLoadObserver = null;
  14668. if (onLoad && !fallback) {
  14669. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14670. }
  14671. if (!fallback)
  14672. this._internalTexturesCache.push(texture);
  14673. var onerror = function (message, exception) {
  14674. if (scene) {
  14675. scene._removePendingData(texture);
  14676. }
  14677. if (onLoadObserver) {
  14678. texture.onLoadedObservable.remove(onLoadObserver);
  14679. }
  14680. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14681. if (isKTX) {
  14682. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14683. }
  14684. else if (BABYLON.Tools.UseFallbackTexture) {
  14685. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14686. }
  14687. if (onError) {
  14688. onError(message || "Unknown error", exception);
  14689. }
  14690. };
  14691. var callback = null;
  14692. // processing for non-image formats
  14693. if (isKTX || isTGA || isDDS) {
  14694. if (isKTX) {
  14695. callback = function (data) {
  14696. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14697. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14698. ktx.uploadLevels(_this._gl, !noMipmap);
  14699. return false;
  14700. }, samplingMode);
  14701. };
  14702. }
  14703. else if (isTGA) {
  14704. callback = function (arrayBuffer) {
  14705. var data = new Uint8Array(arrayBuffer);
  14706. var header = BABYLON.TGATools.GetTGAHeader(data);
  14707. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14708. BABYLON.TGATools.UploadContent(_this._gl, data);
  14709. return false;
  14710. }, samplingMode);
  14711. };
  14712. }
  14713. else if (isDDS) {
  14714. callback = function (data) {
  14715. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14716. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14717. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14718. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14719. return false;
  14720. }, samplingMode);
  14721. };
  14722. }
  14723. if (!buffer) {
  14724. this._loadFile(url, function (data) {
  14725. if (callback) {
  14726. callback(data);
  14727. }
  14728. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14729. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14730. });
  14731. }
  14732. else {
  14733. if (callback) {
  14734. callback(buffer);
  14735. }
  14736. }
  14737. // image format processing
  14738. }
  14739. else {
  14740. var onload = function (img) {
  14741. if (fromBlob && !_this._doNotHandleContextLost) {
  14742. // We need to store the image if we need to rebuild the texture
  14743. // in case of a webgl context lost
  14744. texture._buffer = img;
  14745. }
  14746. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14747. var gl = _this._gl;
  14748. var isPot = (img.width === potWidth && img.height === potHeight);
  14749. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14750. if (isPot) {
  14751. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14752. return false;
  14753. }
  14754. // Using shaders to rescale because canvas.drawImage is lossy
  14755. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14756. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14757. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14758. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14759. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14760. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14761. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14762. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14763. _this._releaseTexture(source);
  14764. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14765. continuationCallback();
  14766. });
  14767. return true;
  14768. }, samplingMode);
  14769. };
  14770. if (!fromData || isBase64) {
  14771. if (buffer instanceof HTMLImageElement) {
  14772. onload(buffer);
  14773. }
  14774. else {
  14775. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14776. }
  14777. }
  14778. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14779. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14780. }
  14781. else {
  14782. onload(buffer);
  14783. }
  14784. }
  14785. return texture;
  14786. };
  14787. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14788. var _this = this;
  14789. var rtt = this.createRenderTargetTexture({
  14790. width: destination.width,
  14791. height: destination.height,
  14792. }, {
  14793. generateMipMaps: false,
  14794. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14795. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14796. generateDepthBuffer: false,
  14797. generateStencilBuffer: false
  14798. });
  14799. if (!this._rescalePostProcess) {
  14800. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14801. }
  14802. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14803. _this._rescalePostProcess.onApply = function (effect) {
  14804. effect._bindTexture("textureSampler", source);
  14805. };
  14806. var hostingScene = scene;
  14807. if (!hostingScene) {
  14808. hostingScene = _this.scenes[_this.scenes.length - 1];
  14809. }
  14810. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14811. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14812. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14813. _this.unBindFramebuffer(rtt);
  14814. _this._releaseTexture(rtt);
  14815. if (onComplete) {
  14816. onComplete();
  14817. }
  14818. });
  14819. };
  14820. /**
  14821. * Update a raw texture
  14822. * @param texture defines the texture to update
  14823. * @param data defines the data to store in the texture
  14824. * @param format defines the format of the data
  14825. * @param invertY defines if data must be stored with Y axis inverted
  14826. * @param compression defines the compression used (null by default)
  14827. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14828. */
  14829. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14830. if (compression === void 0) { compression = null; }
  14831. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14832. if (!texture) {
  14833. return;
  14834. }
  14835. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14836. var internalFormat = this._getInternalFormat(format);
  14837. var textureType = this._getWebGLTextureType(type);
  14838. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14839. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14840. if (!this._doNotHandleContextLost) {
  14841. texture._bufferView = data;
  14842. texture.format = format;
  14843. texture.type = type;
  14844. texture.invertY = invertY;
  14845. texture._compression = compression;
  14846. }
  14847. if (texture.width % 4 !== 0) {
  14848. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14849. }
  14850. if (compression && data) {
  14851. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14852. }
  14853. else {
  14854. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14855. }
  14856. if (texture.generateMipMaps) {
  14857. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14858. }
  14859. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14860. // this.resetTextureCache();
  14861. texture.isReady = true;
  14862. };
  14863. /**
  14864. * Creates a raw texture
  14865. * @param data defines the data to store in the texture
  14866. * @param width defines the width of the texture
  14867. * @param height defines the height of the texture
  14868. * @param format defines the format of the data
  14869. * @param generateMipMaps defines if the engine should generate the mip levels
  14870. * @param invertY defines if data must be stored with Y axis inverted
  14871. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14872. * @param compression defines the compression used (null by default)
  14873. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14874. * @returns the raw texture inside an InternalTexture
  14875. */
  14876. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14877. if (compression === void 0) { compression = null; }
  14878. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14879. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14880. texture.baseWidth = width;
  14881. texture.baseHeight = height;
  14882. texture.width = width;
  14883. texture.height = height;
  14884. texture.format = format;
  14885. texture.generateMipMaps = generateMipMaps;
  14886. texture.samplingMode = samplingMode;
  14887. texture.invertY = invertY;
  14888. texture._compression = compression;
  14889. texture.type = type;
  14890. if (!this._doNotHandleContextLost) {
  14891. texture._bufferView = data;
  14892. }
  14893. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14894. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14895. // Filters
  14896. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14897. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14898. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14899. if (generateMipMaps) {
  14900. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14901. }
  14902. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14903. this._internalTexturesCache.push(texture);
  14904. return texture;
  14905. };
  14906. /**
  14907. * Creates a dynamic texture
  14908. * @param width defines the width of the texture
  14909. * @param height defines the height of the texture
  14910. * @param generateMipMaps defines if the engine should generate the mip levels
  14911. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14912. * @returns the dynamic texture inside an InternalTexture
  14913. */
  14914. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14915. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14916. texture.baseWidth = width;
  14917. texture.baseHeight = height;
  14918. if (generateMipMaps) {
  14919. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14920. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14921. }
  14922. // this.resetTextureCache();
  14923. texture.width = width;
  14924. texture.height = height;
  14925. texture.isReady = false;
  14926. texture.generateMipMaps = generateMipMaps;
  14927. texture.samplingMode = samplingMode;
  14928. this.updateTextureSamplingMode(samplingMode, texture);
  14929. this._internalTexturesCache.push(texture);
  14930. return texture;
  14931. };
  14932. /**
  14933. * Update the sampling mode of a given texture
  14934. * @param samplingMode defines the required sampling mode
  14935. * @param texture defines the texture to update
  14936. */
  14937. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14938. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14939. if (texture.isCube) {
  14940. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14941. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14942. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14943. }
  14944. else if (texture.is3D) {
  14945. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14946. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14947. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14948. }
  14949. else {
  14950. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14951. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14952. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14953. }
  14954. texture.samplingMode = samplingMode;
  14955. };
  14956. /**
  14957. * Update the content of a dynamic texture
  14958. * @param texture defines the texture to update
  14959. * @param canvas defines the canvas containing the source
  14960. * @param invertY defines if data must be stored with Y axis inverted
  14961. * @param premulAlpha defines if alpha is stored as premultiplied
  14962. * @param format defines the format of the data
  14963. */
  14964. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14965. if (premulAlpha === void 0) { premulAlpha = false; }
  14966. if (!texture) {
  14967. return;
  14968. }
  14969. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14970. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14971. if (premulAlpha) {
  14972. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14973. }
  14974. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14975. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14976. if (texture.generateMipMaps) {
  14977. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14978. }
  14979. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14980. if (premulAlpha) {
  14981. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14982. }
  14983. texture.isReady = true;
  14984. };
  14985. /**
  14986. * Update a video texture
  14987. * @param texture defines the texture to update
  14988. * @param video defines the video element to use
  14989. * @param invertY defines if data must be stored with Y axis inverted
  14990. */
  14991. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14992. if (!texture || texture._isDisabled) {
  14993. return;
  14994. }
  14995. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14996. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14997. try {
  14998. // Testing video texture support
  14999. if (this._videoTextureSupported === undefined) {
  15000. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15001. if (this._gl.getError() !== 0) {
  15002. this._videoTextureSupported = false;
  15003. }
  15004. else {
  15005. this._videoTextureSupported = true;
  15006. }
  15007. }
  15008. // Copy video through the current working canvas if video texture is not supported
  15009. if (!this._videoTextureSupported) {
  15010. if (!texture._workingCanvas) {
  15011. texture._workingCanvas = document.createElement("canvas");
  15012. var context = texture._workingCanvas.getContext("2d");
  15013. if (!context) {
  15014. throw new Error("Unable to get 2d context");
  15015. }
  15016. texture._workingContext = context;
  15017. texture._workingCanvas.width = texture.width;
  15018. texture._workingCanvas.height = texture.height;
  15019. }
  15020. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15021. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15022. }
  15023. else {
  15024. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15025. }
  15026. if (texture.generateMipMaps) {
  15027. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15028. }
  15029. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15030. // this.resetTextureCache();
  15031. texture.isReady = true;
  15032. }
  15033. catch (ex) {
  15034. // Something unexpected
  15035. // Let's disable the texture
  15036. texture._isDisabled = true;
  15037. }
  15038. };
  15039. /**
  15040. * Updates a depth texture Comparison Mode and Function.
  15041. * If the comparison Function is equal to 0, the mode will be set to none.
  15042. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15043. * @param texture The texture to set the comparison function for
  15044. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15045. */
  15046. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15047. if (this.webGLVersion === 1) {
  15048. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15049. return;
  15050. }
  15051. var gl = this._gl;
  15052. if (texture.isCube) {
  15053. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15054. if (comparisonFunction === 0) {
  15055. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15056. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15057. }
  15058. else {
  15059. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15060. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15061. }
  15062. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15063. }
  15064. else {
  15065. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15066. if (comparisonFunction === 0) {
  15067. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15068. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15069. }
  15070. else {
  15071. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15072. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15073. }
  15074. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15075. }
  15076. texture._comparisonFunction = comparisonFunction;
  15077. };
  15078. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15079. var width = size.width || size;
  15080. var height = size.height || size;
  15081. internalTexture.baseWidth = width;
  15082. internalTexture.baseHeight = height;
  15083. internalTexture.width = width;
  15084. internalTexture.height = height;
  15085. internalTexture.isReady = true;
  15086. internalTexture.samples = 1;
  15087. internalTexture.generateMipMaps = false;
  15088. internalTexture._generateDepthBuffer = true;
  15089. internalTexture._generateStencilBuffer = generateStencil;
  15090. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15091. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15092. internalTexture._comparisonFunction = comparisonFunction;
  15093. var gl = this._gl;
  15094. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15095. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15096. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15097. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15098. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15099. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15100. if (comparisonFunction === 0) {
  15101. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15102. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15103. }
  15104. else {
  15105. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15106. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15107. }
  15108. };
  15109. /**
  15110. * Creates a depth stencil texture.
  15111. * This is only available in WebGL 2 or with the depth texture extension available.
  15112. * @param size The size of face edge in the texture.
  15113. * @param options The options defining the texture.
  15114. * @returns The texture
  15115. */
  15116. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15117. if (options.isCube) {
  15118. var width = size.width || size;
  15119. return this._createDepthStencilCubeTexture(width, options);
  15120. }
  15121. else {
  15122. return this._createDepthStencilTexture(size, options);
  15123. }
  15124. };
  15125. /**
  15126. * Creates a depth stencil texture.
  15127. * This is only available in WebGL 2 or with the depth texture extension available.
  15128. * @param size The size of face edge in the texture.
  15129. * @param options The options defining the texture.
  15130. * @returns The texture
  15131. */
  15132. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15133. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15134. if (!this._caps.depthTextureExtension) {
  15135. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15136. return internalTexture;
  15137. }
  15138. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15139. var gl = this._gl;
  15140. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15141. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15142. if (this.webGLVersion > 1) {
  15143. if (internalOptions.generateStencil) {
  15144. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15145. }
  15146. else {
  15147. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15148. }
  15149. }
  15150. else {
  15151. if (internalOptions.generateStencil) {
  15152. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15153. }
  15154. else {
  15155. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15156. }
  15157. }
  15158. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15159. return internalTexture;
  15160. };
  15161. /**
  15162. * Creates a depth stencil cube texture.
  15163. * This is only available in WebGL 2.
  15164. * @param size The size of face edge in the cube texture.
  15165. * @param options The options defining the cube texture.
  15166. * @returns The cube texture
  15167. */
  15168. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15169. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15170. internalTexture.isCube = true;
  15171. if (this.webGLVersion === 1) {
  15172. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15173. return internalTexture;
  15174. }
  15175. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15176. var gl = this._gl;
  15177. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15178. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15179. // Create the depth/stencil buffer
  15180. for (var face = 0; face < 6; face++) {
  15181. if (internalOptions.generateStencil) {
  15182. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15183. }
  15184. else {
  15185. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15186. }
  15187. }
  15188. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15189. return internalTexture;
  15190. };
  15191. /**
  15192. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15193. * @param renderTarget The render target to set the frame buffer for
  15194. */
  15195. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15196. // Create the framebuffer
  15197. var internalTexture = renderTarget.getInternalTexture();
  15198. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15199. return;
  15200. }
  15201. var gl = this._gl;
  15202. var depthStencilTexture = renderTarget.depthStencilTexture;
  15203. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15204. if (depthStencilTexture.isCube) {
  15205. if (depthStencilTexture._generateStencilBuffer) {
  15206. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15207. }
  15208. else {
  15209. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15210. }
  15211. }
  15212. else {
  15213. if (depthStencilTexture._generateStencilBuffer) {
  15214. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15215. }
  15216. else {
  15217. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15218. }
  15219. }
  15220. this.bindUnboundFramebuffer(null);
  15221. };
  15222. /**
  15223. * Creates a new render target texture
  15224. * @param size defines the size of the texture
  15225. * @param options defines the options used to create the texture
  15226. * @returns a new render target texture stored in an InternalTexture
  15227. */
  15228. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15229. var fullOptions = new RenderTargetCreationOptions();
  15230. if (options !== undefined && typeof options === "object") {
  15231. fullOptions.generateMipMaps = options.generateMipMaps;
  15232. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15233. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15234. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15235. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15236. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15237. }
  15238. else {
  15239. fullOptions.generateMipMaps = options;
  15240. fullOptions.generateDepthBuffer = true;
  15241. fullOptions.generateStencilBuffer = false;
  15242. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15243. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15244. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15245. }
  15246. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15247. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15248. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15249. }
  15250. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15251. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15252. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15253. }
  15254. var gl = this._gl;
  15255. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15256. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15257. var width = size.width || size;
  15258. var height = size.height || size;
  15259. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15260. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15261. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15262. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15263. }
  15264. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15265. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15266. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15267. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15268. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15269. // Create the framebuffer
  15270. var currentFrameBuffer = this._currentFramebuffer;
  15271. var framebuffer = gl.createFramebuffer();
  15272. this.bindUnboundFramebuffer(framebuffer);
  15273. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15274. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15275. if (fullOptions.generateMipMaps) {
  15276. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15277. }
  15278. // Unbind
  15279. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15280. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15281. this.bindUnboundFramebuffer(currentFrameBuffer);
  15282. texture._framebuffer = framebuffer;
  15283. texture.baseWidth = width;
  15284. texture.baseHeight = height;
  15285. texture.width = width;
  15286. texture.height = height;
  15287. texture.isReady = true;
  15288. texture.samples = 1;
  15289. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15290. texture.samplingMode = fullOptions.samplingMode;
  15291. texture.type = fullOptions.type;
  15292. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15293. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15294. // this.resetTextureCache();
  15295. this._internalTexturesCache.push(texture);
  15296. return texture;
  15297. };
  15298. /**
  15299. * Create a multi render target texture
  15300. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15301. * @param size defines the size of the texture
  15302. * @param options defines the creation options
  15303. * @returns the cube texture as an InternalTexture
  15304. */
  15305. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15306. var generateMipMaps = false;
  15307. var generateDepthBuffer = true;
  15308. var generateStencilBuffer = false;
  15309. var generateDepthTexture = false;
  15310. var textureCount = 1;
  15311. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15312. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15313. var types = new Array();
  15314. var samplingModes = new Array();
  15315. if (options !== undefined) {
  15316. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15317. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15318. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15319. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15320. textureCount = options.textureCount || 1;
  15321. if (options.types) {
  15322. types = options.types;
  15323. }
  15324. if (options.samplingModes) {
  15325. samplingModes = options.samplingModes;
  15326. }
  15327. }
  15328. var gl = this._gl;
  15329. // Create the framebuffer
  15330. var framebuffer = gl.createFramebuffer();
  15331. this.bindUnboundFramebuffer(framebuffer);
  15332. var width = size.width || size;
  15333. var height = size.height || size;
  15334. var textures = [];
  15335. var attachments = [];
  15336. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15337. for (var i = 0; i < textureCount; i++) {
  15338. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15339. var type = types[i] || defaultType;
  15340. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15341. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15342. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15343. }
  15344. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15345. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15346. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15347. }
  15348. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15349. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15350. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15351. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15352. }
  15353. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15354. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15355. textures.push(texture);
  15356. attachments.push(attachment);
  15357. gl.activeTexture(gl["TEXTURE" + i]);
  15358. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15359. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15360. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15361. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15362. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15363. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15364. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15365. if (generateMipMaps) {
  15366. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15367. }
  15368. // Unbind
  15369. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15370. texture._framebuffer = framebuffer;
  15371. texture._depthStencilBuffer = depthStencilBuffer;
  15372. texture.baseWidth = width;
  15373. texture.baseHeight = height;
  15374. texture.width = width;
  15375. texture.height = height;
  15376. texture.isReady = true;
  15377. texture.samples = 1;
  15378. texture.generateMipMaps = generateMipMaps;
  15379. texture.samplingMode = samplingMode;
  15380. texture.type = type;
  15381. texture._generateDepthBuffer = generateDepthBuffer;
  15382. texture._generateStencilBuffer = generateStencilBuffer;
  15383. texture._attachments = attachments;
  15384. this._internalTexturesCache.push(texture);
  15385. }
  15386. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15387. // Depth texture
  15388. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15389. gl.activeTexture(gl.TEXTURE0);
  15390. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15391. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15392. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15393. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15394. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15395. gl.texImage2D(gl.TEXTURE_2D, 0, this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  15396. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15397. depthTexture._framebuffer = framebuffer;
  15398. depthTexture.baseWidth = width;
  15399. depthTexture.baseHeight = height;
  15400. depthTexture.width = width;
  15401. depthTexture.height = height;
  15402. depthTexture.isReady = true;
  15403. depthTexture.samples = 1;
  15404. depthTexture.generateMipMaps = generateMipMaps;
  15405. depthTexture.samplingMode = gl.NEAREST;
  15406. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15407. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15408. textures.push(depthTexture);
  15409. this._internalTexturesCache.push(depthTexture);
  15410. }
  15411. gl.drawBuffers(attachments);
  15412. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15413. this.bindUnboundFramebuffer(null);
  15414. this.resetTextureCache();
  15415. return textures;
  15416. };
  15417. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15418. if (samples === void 0) { samples = 1; }
  15419. var depthStencilBuffer = null;
  15420. var gl = this._gl;
  15421. // Create the depth/stencil buffer
  15422. if (generateStencilBuffer) {
  15423. depthStencilBuffer = gl.createRenderbuffer();
  15424. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15425. if (samples > 1) {
  15426. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15427. }
  15428. else {
  15429. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15430. }
  15431. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15432. }
  15433. else if (generateDepthBuffer) {
  15434. depthStencilBuffer = gl.createRenderbuffer();
  15435. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15436. if (samples > 1) {
  15437. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15438. }
  15439. else {
  15440. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15441. }
  15442. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15443. }
  15444. return depthStencilBuffer;
  15445. };
  15446. /**
  15447. * Updates the sample count of a render target texture
  15448. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15449. * @param texture defines the texture to update
  15450. * @param samples defines the sample count to set
  15451. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15452. */
  15453. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15454. if (this.webGLVersion < 2 || !texture) {
  15455. return 1;
  15456. }
  15457. if (texture.samples === samples) {
  15458. return samples;
  15459. }
  15460. var gl = this._gl;
  15461. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15462. // Dispose previous render buffers
  15463. if (texture._depthStencilBuffer) {
  15464. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15465. texture._depthStencilBuffer = null;
  15466. }
  15467. if (texture._MSAAFramebuffer) {
  15468. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15469. texture._MSAAFramebuffer = null;
  15470. }
  15471. if (texture._MSAARenderBuffer) {
  15472. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15473. texture._MSAARenderBuffer = null;
  15474. }
  15475. if (samples > 1) {
  15476. var framebuffer = gl.createFramebuffer();
  15477. if (!framebuffer) {
  15478. throw new Error("Unable to create multi sampled framebuffer");
  15479. }
  15480. texture._MSAAFramebuffer = framebuffer;
  15481. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15482. var colorRenderbuffer = gl.createRenderbuffer();
  15483. if (!colorRenderbuffer) {
  15484. throw new Error("Unable to create multi sampled framebuffer");
  15485. }
  15486. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15487. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15488. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15489. texture._MSAARenderBuffer = colorRenderbuffer;
  15490. }
  15491. else {
  15492. this.bindUnboundFramebuffer(texture._framebuffer);
  15493. }
  15494. texture.samples = samples;
  15495. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15496. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15497. this.bindUnboundFramebuffer(null);
  15498. return samples;
  15499. };
  15500. /**
  15501. * Update the sample count for a given multiple render target texture
  15502. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15503. * @param textures defines the textures to update
  15504. * @param samples defines the sample count to set
  15505. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15506. */
  15507. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15508. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15509. return 1;
  15510. }
  15511. if (textures[0].samples === samples) {
  15512. return samples;
  15513. }
  15514. var gl = this._gl;
  15515. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15516. // Dispose previous render buffers
  15517. if (textures[0]._depthStencilBuffer) {
  15518. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15519. textures[0]._depthStencilBuffer = null;
  15520. }
  15521. if (textures[0]._MSAAFramebuffer) {
  15522. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15523. textures[0]._MSAAFramebuffer = null;
  15524. }
  15525. for (var i = 0; i < textures.length; i++) {
  15526. if (textures[i]._MSAARenderBuffer) {
  15527. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15528. textures[i]._MSAARenderBuffer = null;
  15529. }
  15530. }
  15531. if (samples > 1) {
  15532. var framebuffer = gl.createFramebuffer();
  15533. if (!framebuffer) {
  15534. throw new Error("Unable to create multi sampled framebuffer");
  15535. }
  15536. this.bindUnboundFramebuffer(framebuffer);
  15537. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15538. var attachments = [];
  15539. for (var i = 0; i < textures.length; i++) {
  15540. var texture = textures[i];
  15541. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15542. var colorRenderbuffer = gl.createRenderbuffer();
  15543. if (!colorRenderbuffer) {
  15544. throw new Error("Unable to create multi sampled framebuffer");
  15545. }
  15546. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15547. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15548. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15549. texture._MSAAFramebuffer = framebuffer;
  15550. texture._MSAARenderBuffer = colorRenderbuffer;
  15551. texture.samples = samples;
  15552. texture._depthStencilBuffer = depthStencilBuffer;
  15553. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15554. attachments.push(attachment);
  15555. }
  15556. gl.drawBuffers(attachments);
  15557. }
  15558. else {
  15559. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15560. }
  15561. this.bindUnboundFramebuffer(null);
  15562. return samples;
  15563. };
  15564. /** @hidden */
  15565. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15566. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15567. };
  15568. /** @hidden */
  15569. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15570. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15571. };
  15572. /**
  15573. * Creates a new render target cube texture
  15574. * @param size defines the size of the texture
  15575. * @param options defines the options used to create the texture
  15576. * @returns a new render target cube texture stored in an InternalTexture
  15577. */
  15578. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15579. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15580. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15581. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15582. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15583. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15584. }
  15585. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15586. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15587. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15588. }
  15589. var gl = this._gl;
  15590. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15591. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15592. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15593. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15594. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15595. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15596. }
  15597. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15598. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15599. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15600. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15601. for (var face = 0; face < 6; face++) {
  15602. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15603. }
  15604. // Create the framebuffer
  15605. var framebuffer = gl.createFramebuffer();
  15606. this.bindUnboundFramebuffer(framebuffer);
  15607. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15608. // MipMaps
  15609. if (fullOptions.generateMipMaps) {
  15610. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15611. }
  15612. // Unbind
  15613. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15614. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15615. this.bindUnboundFramebuffer(null);
  15616. texture._framebuffer = framebuffer;
  15617. texture.width = size;
  15618. texture.height = size;
  15619. texture.isReady = true;
  15620. texture.isCube = true;
  15621. texture.samples = 1;
  15622. texture.generateMipMaps = fullOptions.generateMipMaps;
  15623. texture.samplingMode = fullOptions.samplingMode;
  15624. texture.type = fullOptions.type;
  15625. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15626. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15627. this._internalTexturesCache.push(texture);
  15628. return texture;
  15629. };
  15630. /**
  15631. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15632. * @param rootUrl defines the url where the file to load is located
  15633. * @param scene defines the current scene
  15634. * @param scale defines scale to apply to the mip map selection
  15635. * @param offset defines offset to apply to the mip map selection
  15636. * @param onLoad defines an optional callback raised when the texture is loaded
  15637. * @param onError defines an optional callback raised if there is an issue to load the texture
  15638. * @param format defines the format of the data
  15639. * @param forcedExtension defines the extension to use to pick the right loader
  15640. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15641. * @returns the cube texture as an InternalTexture
  15642. */
  15643. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15644. var _this = this;
  15645. if (onLoad === void 0) { onLoad = null; }
  15646. if (onError === void 0) { onError = null; }
  15647. if (forcedExtension === void 0) { forcedExtension = null; }
  15648. if (createPolynomials === void 0) { createPolynomials = true; }
  15649. var callback = function (loadData) {
  15650. if (!loadData) {
  15651. if (onLoad) {
  15652. onLoad(null);
  15653. }
  15654. return;
  15655. }
  15656. var texture = loadData.texture;
  15657. if (!createPolynomials) {
  15658. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15659. }
  15660. else if (loadData.info.sphericalPolynomial) {
  15661. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15662. }
  15663. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15664. texture._lodGenerationScale = scale;
  15665. texture._lodGenerationOffset = offset;
  15666. if (_this._caps.textureLOD) {
  15667. // Do not add extra process if texture lod is supported.
  15668. if (onLoad) {
  15669. onLoad(texture);
  15670. }
  15671. return;
  15672. }
  15673. var mipSlices = 3;
  15674. var gl = _this._gl;
  15675. var width = loadData.width;
  15676. if (!width) {
  15677. return;
  15678. }
  15679. var textures = [];
  15680. for (var i = 0; i < mipSlices; i++) {
  15681. //compute LOD from even spacing in smoothness (matching shader calculation)
  15682. var smoothness = i / (mipSlices - 1);
  15683. var roughness = 1 - smoothness;
  15684. var minLODIndex = offset; // roughness = 0
  15685. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15686. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15687. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15688. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15689. glTextureFromLod.isCube = true;
  15690. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15691. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15692. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15693. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15694. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15695. if (loadData.isDDS) {
  15696. var info = loadData.info;
  15697. var data = loadData.data;
  15698. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15699. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15700. }
  15701. else {
  15702. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15703. }
  15704. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15705. // Wrap in a base texture for easy binding.
  15706. var lodTexture = new BABYLON.BaseTexture(scene);
  15707. lodTexture.isCube = true;
  15708. lodTexture._texture = glTextureFromLod;
  15709. glTextureFromLod.isReady = true;
  15710. textures.push(lodTexture);
  15711. }
  15712. texture._lodTextureHigh = textures[2];
  15713. texture._lodTextureMid = textures[1];
  15714. texture._lodTextureLow = textures[0];
  15715. if (onLoad) {
  15716. onLoad(texture);
  15717. }
  15718. };
  15719. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials);
  15720. };
  15721. /**
  15722. * Creates a cube texture
  15723. * @param rootUrl defines the url where the files to load is located
  15724. * @param scene defines the current scene
  15725. * @param files defines the list of files to load (1 per face)
  15726. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15727. * @param onLoad defines an optional callback raised when the texture is loaded
  15728. * @param onError defines an optional callback raised if there is an issue to load the texture
  15729. * @param format defines the format of the data
  15730. * @param forcedExtension defines the extension to use to pick the right loader
  15731. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15732. * @returns the cube texture as an InternalTexture
  15733. */
  15734. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials) {
  15735. var _this = this;
  15736. if (onLoad === void 0) { onLoad = null; }
  15737. if (onError === void 0) { onError = null; }
  15738. if (forcedExtension === void 0) { forcedExtension = null; }
  15739. if (createPolynomials === void 0) { createPolynomials = false; }
  15740. var gl = this._gl;
  15741. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15742. texture.isCube = true;
  15743. texture.url = rootUrl;
  15744. texture.generateMipMaps = !noMipmap;
  15745. if (!this._doNotHandleContextLost) {
  15746. texture._extension = forcedExtension;
  15747. texture._files = files;
  15748. }
  15749. var isKTX = false;
  15750. var isDDS = false;
  15751. var lastDot = rootUrl.lastIndexOf('.');
  15752. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15753. if (this._textureFormatInUse) {
  15754. extension = this._textureFormatInUse;
  15755. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15756. isKTX = true;
  15757. }
  15758. else {
  15759. isDDS = (extension === ".dds");
  15760. }
  15761. var onerror = function (request, exception) {
  15762. if (onError && request) {
  15763. onError(request.status + " " + request.statusText, exception);
  15764. }
  15765. };
  15766. if (isKTX) {
  15767. this._loadFile(rootUrl, function (data) {
  15768. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15769. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15770. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15771. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15772. ktx.uploadLevels(_this._gl, !noMipmap);
  15773. _this.setCubeMapTextureParams(gl, loadMipmap);
  15774. texture.width = ktx.pixelWidth;
  15775. texture.height = ktx.pixelHeight;
  15776. texture.isReady = true;
  15777. }, undefined, undefined, true, onerror);
  15778. }
  15779. else if (isDDS) {
  15780. if (files && files.length === 6) {
  15781. this._cascadeLoadFiles(scene, function (imgs) {
  15782. var info;
  15783. var loadMipmap = false;
  15784. var width = 0;
  15785. for (var index = 0; index < imgs.length; index++) {
  15786. var data = imgs[index];
  15787. info = BABYLON.DDSTools.GetDDSInfo(data);
  15788. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15789. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15790. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15791. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15792. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15793. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15794. }
  15795. texture.width = info.width;
  15796. texture.height = info.height;
  15797. texture.type = info.textureType;
  15798. width = info.width;
  15799. }
  15800. _this.setCubeMapTextureParams(gl, loadMipmap);
  15801. texture.isReady = true;
  15802. if (onLoad) {
  15803. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15804. }
  15805. }, files, onError);
  15806. }
  15807. else {
  15808. this._loadFile(rootUrl, function (data) {
  15809. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15810. if (createPolynomials) {
  15811. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15812. }
  15813. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15814. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15815. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15816. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15817. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15818. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15819. }
  15820. _this.setCubeMapTextureParams(gl, loadMipmap);
  15821. texture.width = info.width;
  15822. texture.height = info.height;
  15823. texture.isReady = true;
  15824. texture.type = info.textureType;
  15825. if (onLoad) {
  15826. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15827. }
  15828. }, undefined, undefined, true, onerror);
  15829. }
  15830. }
  15831. else {
  15832. if (!files) {
  15833. throw new Error("Cannot load cubemap because files were not defined");
  15834. }
  15835. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15836. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15837. var height = width;
  15838. _this._prepareWorkingCanvas();
  15839. if (!_this._workingCanvas || !_this._workingContext) {
  15840. return;
  15841. }
  15842. _this._workingCanvas.width = width;
  15843. _this._workingCanvas.height = height;
  15844. var faces = [
  15845. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15846. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15847. ];
  15848. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15849. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15850. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15851. for (var index = 0; index < faces.length; index++) {
  15852. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15853. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15854. }
  15855. if (!noMipmap) {
  15856. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15857. }
  15858. _this.setCubeMapTextureParams(gl, !noMipmap);
  15859. texture.width = width;
  15860. texture.height = height;
  15861. texture.isReady = true;
  15862. if (format) {
  15863. texture.format = format;
  15864. }
  15865. texture.onLoadedObservable.notifyObservers(texture);
  15866. texture.onLoadedObservable.clear();
  15867. if (onLoad) {
  15868. onLoad();
  15869. }
  15870. }, files, onError);
  15871. }
  15872. this._internalTexturesCache.push(texture);
  15873. return texture;
  15874. };
  15875. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15876. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15877. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15878. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15879. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15880. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15881. // this.resetTextureCache();
  15882. };
  15883. /**
  15884. * Update a raw cube texture
  15885. * @param texture defines the texture to udpdate
  15886. * @param data defines the data to store
  15887. * @param format defines the data format
  15888. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15889. * @param invertY defines if data must be stored with Y axis inverted
  15890. * @param compression defines the compression used (null by default)
  15891. * @param level defines which level of the texture to update
  15892. */
  15893. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15894. if (compression === void 0) { compression = null; }
  15895. if (level === void 0) { level = 0; }
  15896. texture._bufferViewArray = data;
  15897. texture.format = format;
  15898. texture.type = type;
  15899. texture.invertY = invertY;
  15900. texture._compression = compression;
  15901. var gl = this._gl;
  15902. var textureType = this._getWebGLTextureType(type);
  15903. var internalFormat = this._getInternalFormat(format);
  15904. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15905. var needConversion = false;
  15906. if (internalFormat === gl.RGB) {
  15907. internalFormat = gl.RGBA;
  15908. needConversion = true;
  15909. }
  15910. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15911. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15912. if (texture.width % 4 !== 0) {
  15913. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15914. }
  15915. // Data are known to be in +X +Y +Z -X -Y -Z
  15916. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15917. var faceData = data[faceIndex];
  15918. if (compression) {
  15919. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15920. }
  15921. else {
  15922. if (needConversion) {
  15923. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15924. }
  15925. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15926. }
  15927. }
  15928. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15929. if (isPot && texture.generateMipMaps && level === 0) {
  15930. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15931. }
  15932. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15933. // this.resetTextureCache();
  15934. texture.isReady = true;
  15935. };
  15936. /**
  15937. * Creates a new raw cube texture
  15938. * @param data defines the array of data to use to create each face
  15939. * @param size defines the size of the textures
  15940. * @param format defines the format of the data
  15941. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15942. * @param generateMipMaps defines if the engine should generate the mip levels
  15943. * @param invertY defines if data must be stored with Y axis inverted
  15944. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15945. * @param compression defines the compression used (null by default)
  15946. * @returns the cube texture as an InternalTexture
  15947. */
  15948. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15949. if (compression === void 0) { compression = null; }
  15950. var gl = this._gl;
  15951. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15952. texture.isCube = true;
  15953. texture.generateMipMaps = generateMipMaps;
  15954. texture.format = format;
  15955. texture.type = type;
  15956. if (!this._doNotHandleContextLost) {
  15957. texture._bufferViewArray = data;
  15958. }
  15959. var textureType = this._getWebGLTextureType(type);
  15960. var internalFormat = this._getInternalFormat(format);
  15961. if (internalFormat === gl.RGB) {
  15962. internalFormat = gl.RGBA;
  15963. }
  15964. var width = size;
  15965. var height = width;
  15966. texture.width = width;
  15967. texture.height = height;
  15968. // Double check on POT to generate Mips.
  15969. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15970. if (!isPot) {
  15971. generateMipMaps = false;
  15972. }
  15973. // Upload data if needed. The texture won't be ready until then.
  15974. if (data) {
  15975. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15976. }
  15977. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15978. // Filters
  15979. if (data && generateMipMaps) {
  15980. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15981. }
  15982. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15983. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15984. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15985. }
  15986. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15987. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15988. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15989. }
  15990. else {
  15991. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15992. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15993. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15994. }
  15995. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15996. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15997. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15998. return texture;
  15999. };
  16000. /**
  16001. * Creates a new raw cube texture from a specified url
  16002. * @param url defines the url where the data is located
  16003. * @param scene defines the current scene
  16004. * @param size defines the size of the textures
  16005. * @param format defines the format of the data
  16006. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16007. * @param noMipmap defines if the engine should avoid generating the mip levels
  16008. * @param callback defines a callback used to extract texture data from loaded data
  16009. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16010. * @param onLoad defines a callback called when texture is loaded
  16011. * @param onError defines a callback called if there is an error
  16012. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16013. * @param invertY defines if data must be stored with Y axis inverted
  16014. * @returns the cube texture as an InternalTexture
  16015. */
  16016. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16017. var _this = this;
  16018. if (onLoad === void 0) { onLoad = null; }
  16019. if (onError === void 0) { onError = null; }
  16020. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16021. if (invertY === void 0) { invertY = false; }
  16022. var gl = this._gl;
  16023. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16024. scene._addPendingData(texture);
  16025. texture.url = url;
  16026. this._internalTexturesCache.push(texture);
  16027. var onerror = function (request, exception) {
  16028. scene._removePendingData(texture);
  16029. if (onError && request) {
  16030. onError(request.status + " " + request.statusText, exception);
  16031. }
  16032. };
  16033. var internalCallback = function (data) {
  16034. var width = texture.width;
  16035. var faceDataArrays = callback(data);
  16036. if (!faceDataArrays) {
  16037. return;
  16038. }
  16039. if (mipmapGenerator) {
  16040. var textureType = _this._getWebGLTextureType(type);
  16041. var internalFormat = _this._getInternalFormat(format);
  16042. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16043. var needConversion = false;
  16044. if (internalFormat === gl.RGB) {
  16045. internalFormat = gl.RGBA;
  16046. needConversion = true;
  16047. }
  16048. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16049. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  16050. var mipData = mipmapGenerator(faceDataArrays);
  16051. for (var level = 0; level < mipData.length; level++) {
  16052. var mipSize = width >> level;
  16053. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16054. var mipFaceData = mipData[level][faceIndex];
  16055. if (needConversion) {
  16056. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16057. }
  16058. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16059. }
  16060. }
  16061. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16062. }
  16063. else {
  16064. texture.generateMipMaps = !noMipmap;
  16065. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16066. }
  16067. texture.isReady = true;
  16068. // this.resetTextureCache();
  16069. scene._removePendingData(texture);
  16070. if (onLoad) {
  16071. onLoad();
  16072. }
  16073. };
  16074. this._loadFile(url, function (data) {
  16075. internalCallback(data);
  16076. }, undefined, scene.database, true, onerror);
  16077. return texture;
  16078. };
  16079. ;
  16080. /**
  16081. * Update a raw 3D texture
  16082. * @param texture defines the texture to update
  16083. * @param data defines the data to store
  16084. * @param format defines the data format
  16085. * @param invertY defines if data must be stored with Y axis inverted
  16086. * @param compression defines the used compression (can be null)
  16087. */
  16088. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  16089. if (compression === void 0) { compression = null; }
  16090. var internalFormat = this._getInternalFormat(format);
  16091. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16092. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16093. if (!this._doNotHandleContextLost) {
  16094. texture._bufferView = data;
  16095. texture.format = format;
  16096. texture.invertY = invertY;
  16097. texture._compression = compression;
  16098. }
  16099. if (texture.width % 4 !== 0) {
  16100. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16101. }
  16102. if (compression && data) {
  16103. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16104. }
  16105. else {
  16106. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  16107. }
  16108. if (texture.generateMipMaps) {
  16109. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16110. }
  16111. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16112. // this.resetTextureCache();
  16113. texture.isReady = true;
  16114. };
  16115. /**
  16116. * Creates a new raw 3D texture
  16117. * @param data defines the data used to create the texture
  16118. * @param width defines the width of the texture
  16119. * @param height defines the height of the texture
  16120. * @param depth defines the depth of the texture
  16121. * @param format defines the format of the texture
  16122. * @param generateMipMaps defines if the engine must generate mip levels
  16123. * @param invertY defines if data must be stored with Y axis inverted
  16124. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16125. * @param compression defines the compressed used (can be null)
  16126. * @returns a new raw 3D texture (stored in an InternalTexture)
  16127. */
  16128. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  16129. if (compression === void 0) { compression = null; }
  16130. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16131. texture.baseWidth = width;
  16132. texture.baseHeight = height;
  16133. texture.baseDepth = depth;
  16134. texture.width = width;
  16135. texture.height = height;
  16136. texture.depth = depth;
  16137. texture.format = format;
  16138. texture.generateMipMaps = generateMipMaps;
  16139. texture.samplingMode = samplingMode;
  16140. texture.is3D = true;
  16141. if (!this._doNotHandleContextLost) {
  16142. texture._bufferView = data;
  16143. }
  16144. this.updateRawTexture3D(texture, data, format, invertY, compression);
  16145. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16146. // Filters
  16147. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16148. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16149. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16150. if (generateMipMaps) {
  16151. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16152. }
  16153. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16154. this._internalTexturesCache.push(texture);
  16155. return texture;
  16156. };
  16157. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16158. var gl = this._gl;
  16159. if (!gl) {
  16160. return;
  16161. }
  16162. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16163. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16164. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16165. if (!noMipmap && !isCompressed) {
  16166. gl.generateMipmap(gl.TEXTURE_2D);
  16167. }
  16168. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16169. // this.resetTextureCache();
  16170. if (scene) {
  16171. scene._removePendingData(texture);
  16172. }
  16173. texture.onLoadedObservable.notifyObservers(texture);
  16174. texture.onLoadedObservable.clear();
  16175. };
  16176. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16177. var _this = this;
  16178. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16179. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16180. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16181. var gl = this._gl;
  16182. if (!gl) {
  16183. return;
  16184. }
  16185. if (!texture._webGLTexture) {
  16186. // this.resetTextureCache();
  16187. if (scene) {
  16188. scene._removePendingData(texture);
  16189. }
  16190. return;
  16191. }
  16192. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16193. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16194. texture.baseWidth = width;
  16195. texture.baseHeight = height;
  16196. texture.width = potWidth;
  16197. texture.height = potHeight;
  16198. texture.isReady = true;
  16199. if (processFunction(potWidth, potHeight, function () {
  16200. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16201. })) {
  16202. // Returning as texture needs extra async steps
  16203. return;
  16204. }
  16205. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16206. };
  16207. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16208. // Create new RGBA data container.
  16209. var rgbaData;
  16210. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16211. rgbaData = new Float32Array(width * height * 4);
  16212. }
  16213. else {
  16214. rgbaData = new Uint32Array(width * height * 4);
  16215. }
  16216. // Convert each pixel.
  16217. for (var x = 0; x < width; x++) {
  16218. for (var y = 0; y < height; y++) {
  16219. var index = (y * width + x) * 3;
  16220. var newIndex = (y * width + x) * 4;
  16221. // Map Old Value to new value.
  16222. rgbaData[newIndex + 0] = rgbData[index + 0];
  16223. rgbaData[newIndex + 1] = rgbData[index + 1];
  16224. rgbaData[newIndex + 2] = rgbData[index + 2];
  16225. // Add fully opaque alpha channel.
  16226. rgbaData[newIndex + 3] = 1;
  16227. }
  16228. }
  16229. return rgbaData;
  16230. };
  16231. /** @hidden */
  16232. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16233. var gl = this._gl;
  16234. if (texture._framebuffer) {
  16235. gl.deleteFramebuffer(texture._framebuffer);
  16236. texture._framebuffer = null;
  16237. }
  16238. if (texture._depthStencilBuffer) {
  16239. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16240. texture._depthStencilBuffer = null;
  16241. }
  16242. if (texture._MSAAFramebuffer) {
  16243. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16244. texture._MSAAFramebuffer = null;
  16245. }
  16246. if (texture._MSAARenderBuffer) {
  16247. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16248. texture._MSAARenderBuffer = null;
  16249. }
  16250. };
  16251. /** @hidden */
  16252. Engine.prototype._releaseTexture = function (texture) {
  16253. var gl = this._gl;
  16254. this._releaseFramebufferObjects(texture);
  16255. gl.deleteTexture(texture._webGLTexture);
  16256. // Unbind channels
  16257. this.unbindAllTextures();
  16258. var index = this._internalTexturesCache.indexOf(texture);
  16259. if (index !== -1) {
  16260. this._internalTexturesCache.splice(index, 1);
  16261. }
  16262. // Integrated fixed lod samplers.
  16263. if (texture._lodTextureHigh) {
  16264. texture._lodTextureHigh.dispose();
  16265. }
  16266. if (texture._lodTextureMid) {
  16267. texture._lodTextureMid.dispose();
  16268. }
  16269. if (texture._lodTextureLow) {
  16270. texture._lodTextureLow.dispose();
  16271. }
  16272. // Set output texture of post process to null if the texture has been released/disposed
  16273. this.scenes.forEach(function (scene) {
  16274. scene.postProcesses.forEach(function (postProcess) {
  16275. if (postProcess._outputTexture == texture) {
  16276. postProcess._outputTexture = null;
  16277. }
  16278. });
  16279. scene.cameras.forEach(function (camera) {
  16280. camera._postProcesses.forEach(function (postProcess) {
  16281. if (postProcess) {
  16282. if (postProcess._outputTexture == texture) {
  16283. postProcess._outputTexture = null;
  16284. }
  16285. }
  16286. });
  16287. });
  16288. });
  16289. };
  16290. Engine.prototype.setProgram = function (program) {
  16291. if (this._currentProgram !== program) {
  16292. this._gl.useProgram(program);
  16293. this._currentProgram = program;
  16294. }
  16295. };
  16296. /**
  16297. * Binds an effect to the webGL context
  16298. * @param effect defines the effect to bind
  16299. */
  16300. Engine.prototype.bindSamplers = function (effect) {
  16301. this.setProgram(effect.getProgram());
  16302. var samplers = effect.getSamplers();
  16303. for (var index = 0; index < samplers.length; index++) {
  16304. var uniform = effect.getUniform(samplers[index]);
  16305. if (uniform) {
  16306. this._boundUniforms[index] = uniform;
  16307. }
  16308. }
  16309. this._currentEffect = null;
  16310. };
  16311. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16312. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16313. return;
  16314. }
  16315. // Remove
  16316. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16317. // Bind last to it
  16318. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16319. // Bind to dummy
  16320. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16321. };
  16322. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16323. if (!internalTexture) {
  16324. return -1;
  16325. }
  16326. internalTexture._initialSlot = channel;
  16327. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16328. if (channel !== internalTexture._designatedSlot) {
  16329. this._textureCollisions.addCount(1, false);
  16330. }
  16331. }
  16332. else {
  16333. if (channel !== internalTexture._designatedSlot) {
  16334. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16335. return internalTexture._designatedSlot;
  16336. }
  16337. else {
  16338. // No slot for this texture, let's pick a new one (if we find a free slot)
  16339. if (this._nextFreeTextureSlots.length) {
  16340. return this._nextFreeTextureSlots[0];
  16341. }
  16342. // We need to recycle the oldest bound texture, sorry.
  16343. this._textureCollisions.addCount(1, false);
  16344. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16345. }
  16346. }
  16347. }
  16348. return channel;
  16349. };
  16350. Engine.prototype._linkTrackers = function (previous, next) {
  16351. previous.next = next;
  16352. next.previous = previous;
  16353. };
  16354. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16355. var currentSlot = internalTexture._designatedSlot;
  16356. if (currentSlot === -1) {
  16357. return -1;
  16358. }
  16359. internalTexture._designatedSlot = -1;
  16360. if (this.disableTextureBindingOptimization) {
  16361. return -1;
  16362. }
  16363. // Remove from bound list
  16364. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16365. // Free the slot
  16366. this._boundTexturesCache[currentSlot] = null;
  16367. this._nextFreeTextureSlots.push(currentSlot);
  16368. return currentSlot;
  16369. };
  16370. Engine.prototype._activateCurrentTexture = function () {
  16371. if (this._currentTextureChannel !== this._activeChannel) {
  16372. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16373. this._currentTextureChannel = this._activeChannel;
  16374. }
  16375. };
  16376. /** @hidden */
  16377. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16378. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16379. if (force === void 0) { force = false; }
  16380. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16381. this._activeChannel = texture._designatedSlot;
  16382. }
  16383. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16384. var isTextureForRendering = texture && texture._initialSlot > -1;
  16385. if (currentTextureBound !== texture || force) {
  16386. if (currentTextureBound) {
  16387. this._removeDesignatedSlot(currentTextureBound);
  16388. }
  16389. this._activateCurrentTexture();
  16390. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16391. this._boundTexturesCache[this._activeChannel] = texture;
  16392. if (texture) {
  16393. if (!this.disableTextureBindingOptimization) {
  16394. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16395. if (slotIndex > -1) {
  16396. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16397. }
  16398. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16399. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16400. }
  16401. texture._designatedSlot = this._activeChannel;
  16402. }
  16403. }
  16404. else if (forTextureDataUpdate) {
  16405. this._activateCurrentTexture();
  16406. }
  16407. if (isTextureForRendering && !forTextureDataUpdate) {
  16408. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16409. }
  16410. };
  16411. /** @hidden */
  16412. Engine.prototype._bindTexture = function (channel, texture) {
  16413. if (channel < 0) {
  16414. return;
  16415. }
  16416. if (texture) {
  16417. channel = this._getCorrectTextureChannel(channel, texture);
  16418. }
  16419. this._activeChannel = channel;
  16420. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16421. };
  16422. /**
  16423. * Sets a texture to the webGL context from a postprocess
  16424. * @param channel defines the channel to use
  16425. * @param postProcess defines the source postprocess
  16426. */
  16427. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16428. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16429. };
  16430. /**
  16431. * Binds the output of the passed in post process to the texture channel specified
  16432. * @param channel The channel the texture should be bound to
  16433. * @param postProcess The post process which's output should be bound
  16434. */
  16435. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16436. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16437. };
  16438. /**
  16439. * Unbind all textures from the webGL context
  16440. */
  16441. Engine.prototype.unbindAllTextures = function () {
  16442. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16443. this._activeChannel = channel;
  16444. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16445. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16446. if (this.webGLVersion > 1) {
  16447. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16448. }
  16449. }
  16450. };
  16451. /**
  16452. * Sets a texture to the according uniform.
  16453. * @param channel The texture channel
  16454. * @param uniform The uniform to set
  16455. * @param texture The texture to apply
  16456. */
  16457. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16458. if (channel < 0) {
  16459. return;
  16460. }
  16461. if (uniform) {
  16462. this._boundUniforms[channel] = uniform;
  16463. }
  16464. this._setTexture(channel, texture);
  16465. };
  16466. /**
  16467. * Sets a depth stencil texture from a render target to the according uniform.
  16468. * @param channel The texture channel
  16469. * @param uniform The uniform to set
  16470. * @param texture The render target texture containing the depth stencil texture to apply
  16471. */
  16472. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16473. if (channel < 0) {
  16474. return;
  16475. }
  16476. if (uniform) {
  16477. this._boundUniforms[channel] = uniform;
  16478. }
  16479. if (!texture || !texture.depthStencilTexture) {
  16480. this._setTexture(channel, null);
  16481. }
  16482. else {
  16483. this._setTexture(channel, texture, false, true);
  16484. }
  16485. };
  16486. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16487. var uniform = this._boundUniforms[sourceSlot];
  16488. if (uniform._currentState === destination) {
  16489. return;
  16490. }
  16491. this._gl.uniform1i(uniform, destination);
  16492. uniform._currentState = destination;
  16493. };
  16494. Engine.prototype._getTextureWrapMode = function (mode) {
  16495. switch (mode) {
  16496. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16497. return this._gl.REPEAT;
  16498. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16499. return this._gl.CLAMP_TO_EDGE;
  16500. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16501. return this._gl.MIRRORED_REPEAT;
  16502. }
  16503. return this._gl.REPEAT;
  16504. };
  16505. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16506. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16507. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16508. // Not ready?
  16509. if (!texture) {
  16510. if (this._boundTexturesCache[channel] != null) {
  16511. this._activeChannel = channel;
  16512. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16513. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16514. if (this.webGLVersion > 1) {
  16515. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16516. }
  16517. }
  16518. return false;
  16519. }
  16520. // Video
  16521. if (texture.video) {
  16522. this._activeChannel = channel;
  16523. texture.update();
  16524. }
  16525. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16526. texture.delayLoad();
  16527. return false;
  16528. }
  16529. var internalTexture;
  16530. if (depthStencilTexture) {
  16531. internalTexture = texture.depthStencilTexture;
  16532. }
  16533. else if (texture.isReady()) {
  16534. internalTexture = texture.getInternalTexture();
  16535. }
  16536. else if (texture.isCube) {
  16537. internalTexture = this.emptyCubeTexture;
  16538. }
  16539. else if (texture.is3D) {
  16540. internalTexture = this.emptyTexture3D;
  16541. }
  16542. else {
  16543. internalTexture = this.emptyTexture;
  16544. }
  16545. if (!isPartOfTextureArray) {
  16546. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16547. }
  16548. var needToBind = true;
  16549. if (this._boundTexturesCache[channel] === internalTexture) {
  16550. this._moveBoundTextureOnTop(internalTexture);
  16551. if (!isPartOfTextureArray) {
  16552. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16553. }
  16554. needToBind = false;
  16555. }
  16556. this._activeChannel = channel;
  16557. if (internalTexture && internalTexture.is3D) {
  16558. if (needToBind) {
  16559. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16560. }
  16561. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16562. internalTexture._cachedWrapU = texture.wrapU;
  16563. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16564. }
  16565. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16566. internalTexture._cachedWrapV = texture.wrapV;
  16567. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16568. }
  16569. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16570. internalTexture._cachedWrapR = texture.wrapR;
  16571. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16572. }
  16573. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16574. }
  16575. else if (internalTexture && internalTexture.isCube) {
  16576. if (needToBind) {
  16577. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16578. }
  16579. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16580. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16581. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16582. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16583. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16584. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16585. }
  16586. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16587. }
  16588. else {
  16589. if (needToBind) {
  16590. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16591. }
  16592. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16593. internalTexture._cachedWrapU = texture.wrapU;
  16594. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16595. }
  16596. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16597. internalTexture._cachedWrapV = texture.wrapV;
  16598. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16599. }
  16600. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16601. }
  16602. return true;
  16603. };
  16604. /**
  16605. * Sets an array of texture to the webGL context
  16606. * @param channel defines the channel where the texture array must be set
  16607. * @param uniform defines the associated uniform location
  16608. * @param textures defines the array of textures to bind
  16609. */
  16610. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16611. if (channel < 0 || !uniform) {
  16612. return;
  16613. }
  16614. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16615. this._textureUnits = new Int32Array(textures.length);
  16616. }
  16617. for (var i = 0; i < textures.length; i++) {
  16618. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16619. }
  16620. this._gl.uniform1iv(uniform, this._textureUnits);
  16621. for (var index = 0; index < textures.length; index++) {
  16622. this._setTexture(this._textureUnits[index], textures[index], true);
  16623. }
  16624. };
  16625. /** @hidden */
  16626. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16627. var internalTexture = texture.getInternalTexture();
  16628. if (!internalTexture) {
  16629. return;
  16630. }
  16631. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16632. var value = texture.anisotropicFilteringLevel;
  16633. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16634. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16635. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16636. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16637. }
  16638. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16639. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16640. internalTexture._cachedAnisotropicFilteringLevel = value;
  16641. }
  16642. };
  16643. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16644. this._bindTextureDirectly(target, texture, true, true);
  16645. this._gl.texParameterf(target, parameter, value);
  16646. };
  16647. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16648. if (texture) {
  16649. this._bindTextureDirectly(target, texture, true, true);
  16650. }
  16651. this._gl.texParameteri(target, parameter, value);
  16652. };
  16653. /**
  16654. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16655. * @param x defines the x coordinate of the rectangle where pixels must be read
  16656. * @param y defines the y coordinate of the rectangle where pixels must be read
  16657. * @param width defines the width of the rectangle where pixels must be read
  16658. * @param height defines the height of the rectangle where pixels must be read
  16659. * @returns a Uint8Array containing RGBA colors
  16660. */
  16661. Engine.prototype.readPixels = function (x, y, width, height) {
  16662. var data = new Uint8Array(height * width * 4);
  16663. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16664. return data;
  16665. };
  16666. /**
  16667. * Add an externaly attached data from its key.
  16668. * This method call will fail and return false, if such key already exists.
  16669. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16670. * @param key the unique key that identifies the data
  16671. * @param data the data object to associate to the key for this Engine instance
  16672. * @return true if no such key were already present and the data was added successfully, false otherwise
  16673. */
  16674. Engine.prototype.addExternalData = function (key, data) {
  16675. if (!this._externalData) {
  16676. this._externalData = new BABYLON.StringDictionary();
  16677. }
  16678. return this._externalData.add(key, data);
  16679. };
  16680. /**
  16681. * Get an externaly attached data from its key
  16682. * @param key the unique key that identifies the data
  16683. * @return the associated data, if present (can be null), or undefined if not present
  16684. */
  16685. Engine.prototype.getExternalData = function (key) {
  16686. if (!this._externalData) {
  16687. this._externalData = new BABYLON.StringDictionary();
  16688. }
  16689. return this._externalData.get(key);
  16690. };
  16691. /**
  16692. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16693. * @param key the unique key that identifies the data
  16694. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16695. * @return the associated data, can be null if the factory returned null.
  16696. */
  16697. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16698. if (!this._externalData) {
  16699. this._externalData = new BABYLON.StringDictionary();
  16700. }
  16701. return this._externalData.getOrAddWithFactory(key, factory);
  16702. };
  16703. /**
  16704. * Remove an externaly attached data from the Engine instance
  16705. * @param key the unique key that identifies the data
  16706. * @return true if the data was successfully removed, false if it doesn't exist
  16707. */
  16708. Engine.prototype.removeExternalData = function (key) {
  16709. if (!this._externalData) {
  16710. this._externalData = new BABYLON.StringDictionary();
  16711. }
  16712. return this._externalData.remove(key);
  16713. };
  16714. /**
  16715. * Unbind all vertex attributes from the webGL context
  16716. */
  16717. Engine.prototype.unbindAllAttributes = function () {
  16718. if (this._mustWipeVertexAttributes) {
  16719. this._mustWipeVertexAttributes = false;
  16720. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16721. this._gl.disableVertexAttribArray(i);
  16722. this._vertexAttribArraysEnabled[i] = false;
  16723. this._currentBufferPointers[i].active = false;
  16724. }
  16725. return;
  16726. }
  16727. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16728. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16729. continue;
  16730. }
  16731. this._gl.disableVertexAttribArray(i);
  16732. this._vertexAttribArraysEnabled[i] = false;
  16733. this._currentBufferPointers[i].active = false;
  16734. }
  16735. };
  16736. /**
  16737. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  16738. */
  16739. Engine.prototype.releaseEffects = function () {
  16740. for (var name in this._compiledEffects) {
  16741. this._deleteProgram(this._compiledEffects[name]._program);
  16742. }
  16743. this._compiledEffects = {};
  16744. };
  16745. /**
  16746. * Dispose and release all associated resources
  16747. */
  16748. Engine.prototype.dispose = function () {
  16749. this.hideLoadingUI();
  16750. this.stopRenderLoop();
  16751. // Release postProcesses
  16752. while (this.postProcesses.length) {
  16753. this.postProcesses[0].dispose();
  16754. }
  16755. // Empty texture
  16756. if (this._emptyTexture) {
  16757. this._releaseTexture(this._emptyTexture);
  16758. this._emptyTexture = null;
  16759. }
  16760. if (this._emptyCubeTexture) {
  16761. this._releaseTexture(this._emptyCubeTexture);
  16762. this._emptyCubeTexture = null;
  16763. }
  16764. // Rescale PP
  16765. if (this._rescalePostProcess) {
  16766. this._rescalePostProcess.dispose();
  16767. }
  16768. // Release scenes
  16769. while (this.scenes.length) {
  16770. this.scenes[0].dispose();
  16771. }
  16772. // Release audio engine
  16773. if (Engine.audioEngine) {
  16774. Engine.audioEngine.dispose();
  16775. }
  16776. // Release effects
  16777. this.releaseEffects();
  16778. // Unbind
  16779. this.unbindAllAttributes();
  16780. this._boundUniforms = [];
  16781. if (this._dummyFramebuffer) {
  16782. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16783. }
  16784. //WebVR
  16785. this.disableVR();
  16786. // Events
  16787. if (BABYLON.Tools.IsWindowObjectExist()) {
  16788. window.removeEventListener("blur", this._onBlur);
  16789. window.removeEventListener("focus", this._onFocus);
  16790. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16791. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16792. if (this._renderingCanvas) {
  16793. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16794. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16795. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16796. if (!this._doNotHandleContextLost) {
  16797. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16798. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16799. }
  16800. }
  16801. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16802. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16803. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16804. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16805. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16806. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16807. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16808. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16809. if (this._onVrDisplayConnect) {
  16810. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16811. if (this._onVrDisplayDisconnect) {
  16812. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16813. }
  16814. if (this._onVrDisplayPresentChange) {
  16815. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16816. }
  16817. this._onVrDisplayConnect = null;
  16818. this._onVrDisplayDisconnect = null;
  16819. }
  16820. }
  16821. // Remove from Instances
  16822. var index = Engine.Instances.indexOf(this);
  16823. if (index >= 0) {
  16824. Engine.Instances.splice(index, 1);
  16825. }
  16826. this._workingCanvas = null;
  16827. this._workingContext = null;
  16828. this._currentBufferPointers = [];
  16829. this._renderingCanvas = null;
  16830. this._currentProgram = null;
  16831. this._bindedRenderFunction = null;
  16832. this.onResizeObservable.clear();
  16833. this.onCanvasBlurObservable.clear();
  16834. this.onCanvasFocusObservable.clear();
  16835. this.onCanvasPointerOutObservable.clear();
  16836. this.onBeginFrameObservable.clear();
  16837. this.onEndFrameObservable.clear();
  16838. BABYLON.Effect.ResetCache();
  16839. // Abort active requests
  16840. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16841. var request = _a[_i];
  16842. request.abort();
  16843. }
  16844. };
  16845. // Loading screen
  16846. /**
  16847. * Display the loading screen
  16848. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16849. */
  16850. Engine.prototype.displayLoadingUI = function () {
  16851. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16852. return;
  16853. }
  16854. var loadingScreen = this.loadingScreen;
  16855. if (loadingScreen) {
  16856. loadingScreen.displayLoadingUI();
  16857. }
  16858. };
  16859. /**
  16860. * Hide the loading screen
  16861. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16862. */
  16863. Engine.prototype.hideLoadingUI = function () {
  16864. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16865. return;
  16866. }
  16867. var loadingScreen = this.loadingScreen;
  16868. if (loadingScreen) {
  16869. loadingScreen.hideLoadingUI();
  16870. }
  16871. };
  16872. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16873. /**
  16874. * Gets the current loading screen object
  16875. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16876. */
  16877. get: function () {
  16878. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16879. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16880. return this._loadingScreen;
  16881. },
  16882. /**
  16883. * Sets the current loading screen object
  16884. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16885. */
  16886. set: function (loadingScreen) {
  16887. this._loadingScreen = loadingScreen;
  16888. },
  16889. enumerable: true,
  16890. configurable: true
  16891. });
  16892. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16893. /**
  16894. * Sets the current loading screen text
  16895. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16896. */
  16897. set: function (text) {
  16898. this.loadingScreen.loadingUIText = text;
  16899. },
  16900. enumerable: true,
  16901. configurable: true
  16902. });
  16903. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16904. /**
  16905. * Sets the current loading screen background color
  16906. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16907. */
  16908. set: function (color) {
  16909. this.loadingScreen.loadingUIBackgroundColor = color;
  16910. },
  16911. enumerable: true,
  16912. configurable: true
  16913. });
  16914. /**
  16915. * Attach a new callback raised when context lost event is fired
  16916. * @param callback defines the callback to call
  16917. */
  16918. Engine.prototype.attachContextLostEvent = function (callback) {
  16919. if (this._renderingCanvas) {
  16920. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16921. }
  16922. };
  16923. /**
  16924. * Attach a new callback raised when context restored event is fired
  16925. * @param callback defines the callback to call
  16926. */
  16927. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16928. if (this._renderingCanvas) {
  16929. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16930. }
  16931. };
  16932. /**
  16933. * Gets the source code of the vertex shader associated with a specific webGL program
  16934. * @param program defines the program to use
  16935. * @returns a string containing the source code of the vertex shader associated with the program
  16936. */
  16937. Engine.prototype.getVertexShaderSource = function (program) {
  16938. var shaders = this._gl.getAttachedShaders(program);
  16939. if (!shaders) {
  16940. return null;
  16941. }
  16942. return this._gl.getShaderSource(shaders[0]);
  16943. };
  16944. /**
  16945. * Gets the source code of the fragment shader associated with a specific webGL program
  16946. * @param program defines the program to use
  16947. * @returns a string containing the source code of the fragment shader associated with the program
  16948. */
  16949. Engine.prototype.getFragmentShaderSource = function (program) {
  16950. var shaders = this._gl.getAttachedShaders(program);
  16951. if (!shaders) {
  16952. return null;
  16953. }
  16954. return this._gl.getShaderSource(shaders[1]);
  16955. };
  16956. /**
  16957. * Get the current error code of the webGL context
  16958. * @returns the error code
  16959. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16960. */
  16961. Engine.prototype.getError = function () {
  16962. return this._gl.getError();
  16963. };
  16964. // FPS
  16965. /**
  16966. * Gets the current framerate
  16967. * @returns a number representing the framerate
  16968. */
  16969. Engine.prototype.getFps = function () {
  16970. return this._fps;
  16971. };
  16972. /**
  16973. * Gets the time spent between current and previous frame
  16974. * @returns a number representing the delta time in ms
  16975. */
  16976. Engine.prototype.getDeltaTime = function () {
  16977. return this._deltaTime;
  16978. };
  16979. Engine.prototype._measureFps = function () {
  16980. this._performanceMonitor.sampleFrame();
  16981. this._fps = this._performanceMonitor.averageFPS;
  16982. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16983. };
  16984. /** @hidden */
  16985. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16986. if (faceIndex === void 0) { faceIndex = -1; }
  16987. var gl = this._gl;
  16988. if (!this._dummyFramebuffer) {
  16989. var dummy = gl.createFramebuffer();
  16990. if (!dummy) {
  16991. throw new Error("Unable to create dummy framebuffer");
  16992. }
  16993. this._dummyFramebuffer = dummy;
  16994. }
  16995. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16996. if (faceIndex > -1) {
  16997. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16998. }
  16999. else {
  17000. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  17001. }
  17002. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17003. var buffer;
  17004. switch (readType) {
  17005. case gl.UNSIGNED_BYTE:
  17006. buffer = new Uint8Array(4 * width * height);
  17007. readType = gl.UNSIGNED_BYTE;
  17008. break;
  17009. default:
  17010. buffer = new Float32Array(4 * width * height);
  17011. readType = gl.FLOAT;
  17012. break;
  17013. }
  17014. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17015. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17016. return buffer;
  17017. };
  17018. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17019. if (this._webGLVersion > 1) {
  17020. return this._caps.colorBufferFloat;
  17021. }
  17022. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17023. };
  17024. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17025. if (this._webGLVersion > 1) {
  17026. return this._caps.colorBufferFloat;
  17027. }
  17028. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17029. };
  17030. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17031. Engine.prototype._canRenderToFramebuffer = function (type) {
  17032. var gl = this._gl;
  17033. //clear existing errors
  17034. while (gl.getError() !== gl.NO_ERROR) { }
  17035. var successful = true;
  17036. var texture = gl.createTexture();
  17037. gl.bindTexture(gl.TEXTURE_2D, texture);
  17038. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17039. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17040. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17041. var fb = gl.createFramebuffer();
  17042. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17043. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17044. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17045. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17046. successful = successful && (gl.getError() === gl.NO_ERROR);
  17047. //try render by clearing frame buffer's color buffer
  17048. if (successful) {
  17049. gl.clear(gl.COLOR_BUFFER_BIT);
  17050. successful = successful && (gl.getError() === gl.NO_ERROR);
  17051. }
  17052. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17053. if (successful) {
  17054. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17055. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17056. var readFormat = gl.RGBA;
  17057. var readType = gl.UNSIGNED_BYTE;
  17058. var buffer = new Uint8Array(4);
  17059. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17060. successful = successful && (gl.getError() === gl.NO_ERROR);
  17061. }
  17062. //clean up
  17063. gl.deleteTexture(texture);
  17064. gl.deleteFramebuffer(fb);
  17065. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17066. //clear accumulated errors
  17067. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17068. return successful;
  17069. };
  17070. /** @hidden */
  17071. Engine.prototype._getWebGLTextureType = function (type) {
  17072. if (type === Engine.TEXTURETYPE_FLOAT) {
  17073. return this._gl.FLOAT;
  17074. }
  17075. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17076. // Add Half Float Constant.
  17077. return this._gl.HALF_FLOAT_OES;
  17078. }
  17079. return this._gl.UNSIGNED_BYTE;
  17080. };
  17081. ;
  17082. Engine.prototype._getInternalFormat = function (format) {
  17083. var internalFormat = this._gl.RGBA;
  17084. switch (format) {
  17085. case Engine.TEXTUREFORMAT_ALPHA:
  17086. internalFormat = this._gl.ALPHA;
  17087. break;
  17088. case Engine.TEXTUREFORMAT_LUMINANCE:
  17089. internalFormat = this._gl.LUMINANCE;
  17090. break;
  17091. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17092. internalFormat = this._gl.LUMINANCE_ALPHA;
  17093. break;
  17094. case Engine.TEXTUREFORMAT_RGB:
  17095. case Engine.TEXTUREFORMAT_RGB32F:
  17096. internalFormat = this._gl.RGB;
  17097. break;
  17098. case Engine.TEXTUREFORMAT_RGBA:
  17099. case Engine.TEXTUREFORMAT_RGBA32F:
  17100. internalFormat = this._gl.RGBA;
  17101. break;
  17102. case Engine.TEXTUREFORMAT_R32F:
  17103. internalFormat = this._gl.RED;
  17104. break;
  17105. case Engine.TEXTUREFORMAT_RG32F:
  17106. internalFormat = this._gl.RG;
  17107. break;
  17108. }
  17109. return internalFormat;
  17110. };
  17111. /** @hidden */
  17112. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17113. if (this._webGLVersion === 1) {
  17114. if (format) {
  17115. switch (format) {
  17116. case Engine.TEXTUREFORMAT_LUMINANCE:
  17117. return this._gl.LUMINANCE;
  17118. }
  17119. }
  17120. return this._gl.RGBA;
  17121. }
  17122. if (type === Engine.TEXTURETYPE_FLOAT) {
  17123. if (format) {
  17124. switch (format) {
  17125. case Engine.TEXTUREFORMAT_R32F:
  17126. return this._gl.R32F;
  17127. case Engine.TEXTUREFORMAT_RG32F:
  17128. return this._gl.RG32F;
  17129. case Engine.TEXTUREFORMAT_RGB32F:
  17130. return this._gl.RGB32F;
  17131. }
  17132. }
  17133. return this._gl.RGBA32F;
  17134. }
  17135. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17136. return this._gl.RGBA16F;
  17137. }
  17138. if (format) {
  17139. switch (format) {
  17140. case Engine.TEXTUREFORMAT_LUMINANCE:
  17141. return this._gl.LUMINANCE;
  17142. case Engine.TEXTUREFORMAT_RGB:
  17143. return this._gl.RGB;
  17144. }
  17145. }
  17146. return this._gl.RGBA;
  17147. };
  17148. ;
  17149. /** @hidden */
  17150. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17151. if (type === Engine.TEXTURETYPE_FLOAT) {
  17152. return this._gl.RGBA32F;
  17153. }
  17154. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17155. return this._gl.RGBA16F;
  17156. }
  17157. return this._gl.RGBA8;
  17158. };
  17159. ;
  17160. /**
  17161. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17162. * @return the new query
  17163. */
  17164. Engine.prototype.createQuery = function () {
  17165. return this._gl.createQuery();
  17166. };
  17167. /**
  17168. * Delete and release a webGL query
  17169. * @param query defines the query to delete
  17170. * @return the current engine
  17171. */
  17172. Engine.prototype.deleteQuery = function (query) {
  17173. this._gl.deleteQuery(query);
  17174. return this;
  17175. };
  17176. /**
  17177. * Check if a given query has resolved and got its value
  17178. * @param query defines the query to check
  17179. * @returns true if the query got its value
  17180. */
  17181. Engine.prototype.isQueryResultAvailable = function (query) {
  17182. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17183. };
  17184. /**
  17185. * Gets the value of a given query
  17186. * @param query defines the query to check
  17187. * @returns the value of the query
  17188. */
  17189. Engine.prototype.getQueryResult = function (query) {
  17190. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17191. };
  17192. /**
  17193. * Initiates an occlusion query
  17194. * @param algorithmType defines the algorithm to use
  17195. * @param query defines the query to use
  17196. * @returns the current engine
  17197. * @see http://doc.babylonjs.com/features/occlusionquery
  17198. */
  17199. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17200. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17201. this._gl.beginQuery(glAlgorithm, query);
  17202. return this;
  17203. };
  17204. /**
  17205. * Ends an occlusion query
  17206. * @see http://doc.babylonjs.com/features/occlusionquery
  17207. * @param algorithmType defines the algorithm to use
  17208. * @returns the current engine
  17209. */
  17210. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17211. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17212. this._gl.endQuery(glAlgorithm);
  17213. return this;
  17214. };
  17215. /* Time queries */
  17216. Engine.prototype._createTimeQuery = function () {
  17217. var timerQuery = this._caps.timerQuery;
  17218. if (timerQuery.createQueryEXT) {
  17219. return timerQuery.createQueryEXT();
  17220. }
  17221. return this.createQuery();
  17222. };
  17223. Engine.prototype._deleteTimeQuery = function (query) {
  17224. var timerQuery = this._caps.timerQuery;
  17225. if (timerQuery.deleteQueryEXT) {
  17226. timerQuery.deleteQueryEXT(query);
  17227. return;
  17228. }
  17229. this.deleteQuery(query);
  17230. };
  17231. Engine.prototype._getTimeQueryResult = function (query) {
  17232. var timerQuery = this._caps.timerQuery;
  17233. if (timerQuery.getQueryObjectEXT) {
  17234. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17235. }
  17236. return this.getQueryResult(query);
  17237. };
  17238. Engine.prototype._getTimeQueryAvailability = function (query) {
  17239. var timerQuery = this._caps.timerQuery;
  17240. if (timerQuery.getQueryObjectEXT) {
  17241. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17242. }
  17243. return this.isQueryResultAvailable(query);
  17244. };
  17245. /**
  17246. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17247. * Please note that only one query can be issued at a time
  17248. * @returns a time token used to track the time span
  17249. */
  17250. Engine.prototype.startTimeQuery = function () {
  17251. var timerQuery = this._caps.timerQuery;
  17252. if (!timerQuery) {
  17253. return null;
  17254. }
  17255. var token = new BABYLON._TimeToken();
  17256. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17257. if (this._caps.canUseTimestampForTimerQuery) {
  17258. token._startTimeQuery = this._createTimeQuery();
  17259. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17260. }
  17261. else {
  17262. if (this._currentNonTimestampToken) {
  17263. return this._currentNonTimestampToken;
  17264. }
  17265. token._timeElapsedQuery = this._createTimeQuery();
  17266. if (timerQuery.beginQueryEXT) {
  17267. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17268. }
  17269. else {
  17270. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17271. }
  17272. this._currentNonTimestampToken = token;
  17273. }
  17274. return token;
  17275. };
  17276. /**
  17277. * Ends a time query
  17278. * @param token defines the token used to measure the time span
  17279. * @returns the time spent (in ns)
  17280. */
  17281. Engine.prototype.endTimeQuery = function (token) {
  17282. var timerQuery = this._caps.timerQuery;
  17283. if (!timerQuery || !token) {
  17284. return -1;
  17285. }
  17286. if (this._caps.canUseTimestampForTimerQuery) {
  17287. if (!token._startTimeQuery) {
  17288. return -1;
  17289. }
  17290. if (!token._endTimeQuery) {
  17291. token._endTimeQuery = this._createTimeQuery();
  17292. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17293. }
  17294. }
  17295. else if (!token._timeElapsedQueryEnded) {
  17296. if (!token._timeElapsedQuery) {
  17297. return -1;
  17298. }
  17299. if (timerQuery.endQueryEXT) {
  17300. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17301. }
  17302. else {
  17303. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17304. }
  17305. token._timeElapsedQueryEnded = true;
  17306. }
  17307. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17308. var available = false;
  17309. if (token._endTimeQuery) {
  17310. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17311. }
  17312. else if (token._timeElapsedQuery) {
  17313. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17314. }
  17315. if (available && !disjoint) {
  17316. var result = 0;
  17317. if (this._caps.canUseTimestampForTimerQuery) {
  17318. if (!token._startTimeQuery || !token._endTimeQuery) {
  17319. return -1;
  17320. }
  17321. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17322. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17323. result = timeEnd - timeStart;
  17324. this._deleteTimeQuery(token._startTimeQuery);
  17325. this._deleteTimeQuery(token._endTimeQuery);
  17326. token._startTimeQuery = null;
  17327. token._endTimeQuery = null;
  17328. }
  17329. else {
  17330. if (!token._timeElapsedQuery) {
  17331. return -1;
  17332. }
  17333. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17334. this._deleteTimeQuery(token._timeElapsedQuery);
  17335. token._timeElapsedQuery = null;
  17336. token._timeElapsedQueryEnded = false;
  17337. this._currentNonTimestampToken = null;
  17338. }
  17339. return result;
  17340. }
  17341. return -1;
  17342. };
  17343. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17344. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17345. };
  17346. // Transform feedback
  17347. /**
  17348. * Creates a webGL transform feedback object
  17349. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17350. * @returns the webGL transform feedback object
  17351. */
  17352. Engine.prototype.createTransformFeedback = function () {
  17353. return this._gl.createTransformFeedback();
  17354. };
  17355. /**
  17356. * Delete a webGL transform feedback object
  17357. * @param value defines the webGL transform feedback object to delete
  17358. */
  17359. Engine.prototype.deleteTransformFeedback = function (value) {
  17360. this._gl.deleteTransformFeedback(value);
  17361. };
  17362. /**
  17363. * Bind a webGL transform feedback object to the webgl context
  17364. * @param value defines the webGL transform feedback object to bind
  17365. */
  17366. Engine.prototype.bindTransformFeedback = function (value) {
  17367. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17368. };
  17369. /**
  17370. * Begins a transform feedback operation
  17371. * @param usePoints defines if points or triangles must be used
  17372. */
  17373. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17374. if (usePoints === void 0) { usePoints = true; }
  17375. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17376. };
  17377. /**
  17378. * Ends a transform feedback operation
  17379. */
  17380. Engine.prototype.endTransformFeedback = function () {
  17381. this._gl.endTransformFeedback();
  17382. };
  17383. /**
  17384. * Specify the varyings to use with transform feedback
  17385. * @param program defines the associated webGL program
  17386. * @param value defines the list of strings representing the varying names
  17387. */
  17388. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17389. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17390. };
  17391. /**
  17392. * Bind a webGL buffer for a transform feedback operation
  17393. * @param value defines the webGL buffer to bind
  17394. */
  17395. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17396. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17397. };
  17398. /** @hidden */
  17399. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17400. var _this = this;
  17401. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17402. this._activeRequests.push(request);
  17403. request.onCompleteObservable.add(function (request) {
  17404. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17405. });
  17406. return request;
  17407. };
  17408. /** @hidden */
  17409. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17410. var _this = this;
  17411. return new Promise(function (resolve, reject) {
  17412. _this._loadFile(url, function (data) {
  17413. resolve(data);
  17414. }, undefined, database, useArrayBuffer, function (request, exception) {
  17415. reject(exception);
  17416. });
  17417. });
  17418. };
  17419. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17420. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17421. var onload = function (data) {
  17422. loadedFiles[index] = data;
  17423. loadedFiles._internalCount++;
  17424. if (loadedFiles._internalCount === 6) {
  17425. onfinish(loadedFiles);
  17426. }
  17427. };
  17428. var onerror = function (request, exception) {
  17429. if (onErrorCallBack && request) {
  17430. onErrorCallBack(request.status + " " + request.statusText, exception);
  17431. }
  17432. };
  17433. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17434. };
  17435. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17436. if (onError === void 0) { onError = null; }
  17437. var loadedFiles = [];
  17438. loadedFiles._internalCount = 0;
  17439. for (var index = 0; index < 6; index++) {
  17440. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17441. }
  17442. };
  17443. // Statics
  17444. /**
  17445. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17446. * @returns true if the engine can be created
  17447. * @ignorenaming
  17448. */
  17449. Engine.isSupported = function () {
  17450. try {
  17451. var tempcanvas = document.createElement("canvas");
  17452. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17453. return gl != null && !!window.WebGLRenderingContext;
  17454. }
  17455. catch (e) {
  17456. return false;
  17457. }
  17458. };
  17459. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17460. Engine.ExceptionList = [
  17461. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17462. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17463. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17464. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17465. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17466. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17467. ];
  17468. /** Gets the list of created engines */
  17469. Engine.Instances = new Array();
  17470. // Const statics
  17471. Engine._ALPHA_DISABLE = 0;
  17472. Engine._ALPHA_ADD = 1;
  17473. Engine._ALPHA_COMBINE = 2;
  17474. Engine._ALPHA_SUBTRACT = 3;
  17475. Engine._ALPHA_MULTIPLY = 4;
  17476. Engine._ALPHA_MAXIMIZED = 5;
  17477. Engine._ALPHA_ONEONE = 6;
  17478. Engine._ALPHA_PREMULTIPLIED = 7;
  17479. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17480. Engine._ALPHA_INTERPOLATE = 9;
  17481. Engine._ALPHA_SCREENMODE = 10;
  17482. Engine._DELAYLOADSTATE_NONE = 0;
  17483. Engine._DELAYLOADSTATE_LOADED = 1;
  17484. Engine._DELAYLOADSTATE_LOADING = 2;
  17485. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17486. Engine._TEXTUREFORMAT_ALPHA = 0;
  17487. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17488. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17489. Engine._TEXTUREFORMAT_RGB = 4;
  17490. Engine._TEXTUREFORMAT_RGBA = 5;
  17491. Engine._TEXTUREFORMAT_R32F = 6;
  17492. Engine._TEXTUREFORMAT_RG32F = 7;
  17493. Engine._TEXTUREFORMAT_RGB32F = 8;
  17494. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17495. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17496. Engine._TEXTURETYPE_FLOAT = 1;
  17497. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17498. // Depht or Stencil test Constants.
  17499. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17500. Engine._ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  17501. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  17502. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  17503. Engine._LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  17504. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  17505. Engine._GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  17506. Engine._NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  17507. // Stencil Actions Constants.
  17508. Engine._KEEP = 0x1E00;
  17509. Engine._REPLACE = 0x1E01;
  17510. Engine._INCR = 0x1E02;
  17511. Engine._DECR = 0x1E03;
  17512. Engine._INVERT = 0x150A;
  17513. Engine._INCR_WRAP = 0x8507;
  17514. Engine._DECR_WRAP = 0x8508;
  17515. // Texture rescaling mode
  17516. Engine._SCALEMODE_FLOOR = 1;
  17517. Engine._SCALEMODE_NEAREST = 2;
  17518. Engine._SCALEMODE_CEILING = 3;
  17519. // Updatable statics so stick with vars here
  17520. /**
  17521. * Gets or sets the epsilon value used by collision engine
  17522. */
  17523. Engine.CollisionsEpsilon = 0.001;
  17524. /**
  17525. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17526. */
  17527. Engine.CodeRepository = "src/";
  17528. /**
  17529. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17530. */
  17531. Engine.ShadersRepository = "src/Shaders/";
  17532. return Engine;
  17533. }());
  17534. BABYLON.Engine = Engine;
  17535. })(BABYLON || (BABYLON = {}));
  17536. //# sourceMappingURL=babylon.engine.js.map
  17537. var BABYLON;
  17538. (function (BABYLON) {
  17539. /**
  17540. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17541. */
  17542. var Node = /** @class */ (function () {
  17543. /**
  17544. * Creates a new Node
  17545. * @param {string} name - the name and id to be given to this node
  17546. * @param {BABYLON.Scene} the scene this node will be added to
  17547. */
  17548. function Node(name, scene) {
  17549. if (scene === void 0) { scene = null; }
  17550. /**
  17551. * Gets or sets a string used to store user defined state for the node
  17552. */
  17553. this.state = "";
  17554. /**
  17555. * Gets or sets an object used to store user defined information for the node
  17556. */
  17557. this.metadata = null;
  17558. /**
  17559. * Gets or sets a boolean used to define if the node must be serialized
  17560. */
  17561. this.doNotSerialize = false;
  17562. /** @hidden */
  17563. this._isDisposed = false;
  17564. /**
  17565. * Gets a list of Animations associated with the node
  17566. */
  17567. this.animations = new Array();
  17568. this._ranges = {};
  17569. this._isEnabled = true;
  17570. this._isReady = true;
  17571. /** @hidden */
  17572. this._currentRenderId = -1;
  17573. this._parentRenderId = -1;
  17574. this._childRenderId = -1;
  17575. this._animationPropertiesOverride = null;
  17576. /**
  17577. * An event triggered when the mesh is disposed
  17578. */
  17579. this.onDisposeObservable = new BABYLON.Observable();
  17580. // Behaviors
  17581. this._behaviors = new Array();
  17582. this.name = name;
  17583. this.id = name;
  17584. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17585. this.uniqueId = this._scene.getUniqueId();
  17586. this._initCache();
  17587. }
  17588. /**
  17589. * Gets a boolean indicating if the node has been disposed
  17590. * @returns true if the node was disposed
  17591. */
  17592. Node.prototype.isDisposed = function () {
  17593. return this._isDisposed;
  17594. };
  17595. Object.defineProperty(Node.prototype, "parent", {
  17596. get: function () {
  17597. return this._parentNode;
  17598. },
  17599. /**
  17600. * Gets or sets the parent of the node
  17601. */
  17602. set: function (parent) {
  17603. if (this._parentNode === parent) {
  17604. return;
  17605. }
  17606. // Remove self from list of children of parent
  17607. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17608. var index = this._parentNode._children.indexOf(this);
  17609. if (index !== -1) {
  17610. this._parentNode._children.splice(index, 1);
  17611. }
  17612. }
  17613. // Store new parent
  17614. this._parentNode = parent;
  17615. // Add as child to new parent
  17616. if (this._parentNode) {
  17617. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17618. this._parentNode._children = new Array();
  17619. }
  17620. this._parentNode._children.push(this);
  17621. }
  17622. },
  17623. enumerable: true,
  17624. configurable: true
  17625. });
  17626. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17627. /**
  17628. * Gets or sets the animation properties override
  17629. */
  17630. get: function () {
  17631. if (!this._animationPropertiesOverride) {
  17632. return this._scene.animationPropertiesOverride;
  17633. }
  17634. return this._animationPropertiesOverride;
  17635. },
  17636. set: function (value) {
  17637. this._animationPropertiesOverride = value;
  17638. },
  17639. enumerable: true,
  17640. configurable: true
  17641. });
  17642. /**
  17643. * Gets a string idenfifying the name of the class
  17644. * @returns "Node" string
  17645. */
  17646. Node.prototype.getClassName = function () {
  17647. return "Node";
  17648. };
  17649. Object.defineProperty(Node.prototype, "onDispose", {
  17650. /**
  17651. * Sets a callback that will be raised when the node will be disposed
  17652. */
  17653. set: function (callback) {
  17654. if (this._onDisposeObserver) {
  17655. this.onDisposeObservable.remove(this._onDisposeObserver);
  17656. }
  17657. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17658. },
  17659. enumerable: true,
  17660. configurable: true
  17661. });
  17662. /**
  17663. * Gets the scene of the node
  17664. * @returns a {BABYLON.Scene}
  17665. */
  17666. Node.prototype.getScene = function () {
  17667. return this._scene;
  17668. };
  17669. /**
  17670. * Gets the engine of the node
  17671. * @returns a {BABYLON.Engine}
  17672. */
  17673. Node.prototype.getEngine = function () {
  17674. return this._scene.getEngine();
  17675. };
  17676. /**
  17677. * Attach a behavior to the node
  17678. * @see http://doc.babylonjs.com/features/behaviour
  17679. * @param behavior defines the behavior to attach
  17680. * @returns the current Node
  17681. */
  17682. Node.prototype.addBehavior = function (behavior) {
  17683. var _this = this;
  17684. var index = this._behaviors.indexOf(behavior);
  17685. if (index !== -1) {
  17686. return this;
  17687. }
  17688. behavior.init();
  17689. if (this._scene.isLoading) {
  17690. // We defer the attach when the scene will be loaded
  17691. this._scene.onDataLoadedObservable.addOnce(function () {
  17692. behavior.attach(_this);
  17693. });
  17694. }
  17695. else {
  17696. behavior.attach(this);
  17697. }
  17698. this._behaviors.push(behavior);
  17699. return this;
  17700. };
  17701. /**
  17702. * Remove an attached behavior
  17703. * @see http://doc.babylonjs.com/features/behaviour
  17704. * @param behavior defines the behavior to attach
  17705. * @returns the current Node
  17706. */
  17707. Node.prototype.removeBehavior = function (behavior) {
  17708. var index = this._behaviors.indexOf(behavior);
  17709. if (index === -1) {
  17710. return this;
  17711. }
  17712. this._behaviors[index].detach();
  17713. this._behaviors.splice(index, 1);
  17714. return this;
  17715. };
  17716. Object.defineProperty(Node.prototype, "behaviors", {
  17717. /**
  17718. * Gets the list of attached behaviors
  17719. * @see http://doc.babylonjs.com/features/behaviour
  17720. */
  17721. get: function () {
  17722. return this._behaviors;
  17723. },
  17724. enumerable: true,
  17725. configurable: true
  17726. });
  17727. /**
  17728. * Gets an attached behavior by name
  17729. * @param name defines the name of the behavior to look for
  17730. * @see http://doc.babylonjs.com/features/behaviour
  17731. * @returns null if behavior was not found else the requested behavior
  17732. */
  17733. Node.prototype.getBehaviorByName = function (name) {
  17734. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17735. var behavior = _a[_i];
  17736. if (behavior.name === name) {
  17737. return behavior;
  17738. }
  17739. }
  17740. return null;
  17741. };
  17742. /**
  17743. * Returns the world matrix of the node
  17744. * @returns a matrix containing the node's world matrix
  17745. */
  17746. Node.prototype.getWorldMatrix = function () {
  17747. return BABYLON.Matrix.Identity();
  17748. };
  17749. /** @hidden */
  17750. Node.prototype._getWorldMatrixDeterminant = function () {
  17751. return 1;
  17752. };
  17753. // override it in derived class if you add new variables to the cache
  17754. // and call the parent class method
  17755. /** @hidden */
  17756. Node.prototype._initCache = function () {
  17757. this._cache = {};
  17758. this._cache.parent = undefined;
  17759. };
  17760. /** @hidden */
  17761. Node.prototype.updateCache = function (force) {
  17762. if (!force && this.isSynchronized())
  17763. return;
  17764. this._cache.parent = this.parent;
  17765. this._updateCache();
  17766. };
  17767. // override it in derived class if you add new variables to the cache
  17768. // and call the parent class method if !ignoreParentClass
  17769. /** @hidden */
  17770. Node.prototype._updateCache = function (ignoreParentClass) {
  17771. };
  17772. // override it in derived class if you add new variables to the cache
  17773. /** @hidden */
  17774. Node.prototype._isSynchronized = function () {
  17775. return true;
  17776. };
  17777. /** @hidden */
  17778. Node.prototype._markSyncedWithParent = function () {
  17779. if (this.parent) {
  17780. this._parentRenderId = this.parent._childRenderId;
  17781. }
  17782. };
  17783. /** @hidden */
  17784. Node.prototype.isSynchronizedWithParent = function () {
  17785. if (!this.parent) {
  17786. return true;
  17787. }
  17788. if (this._parentRenderId !== this.parent._childRenderId) {
  17789. return false;
  17790. }
  17791. return this.parent.isSynchronized();
  17792. };
  17793. /** @hidden */
  17794. Node.prototype.isSynchronized = function (updateCache) {
  17795. var check = this.hasNewParent();
  17796. check = check || !this.isSynchronizedWithParent();
  17797. check = check || !this._isSynchronized();
  17798. if (updateCache)
  17799. this.updateCache(true);
  17800. return !check;
  17801. };
  17802. /** @hidden */
  17803. Node.prototype.hasNewParent = function (update) {
  17804. if (this._cache.parent === this.parent)
  17805. return false;
  17806. if (update)
  17807. this._cache.parent = this.parent;
  17808. return true;
  17809. };
  17810. /**
  17811. * Is this node ready to be used/rendered
  17812. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17813. * @return true if the node is ready
  17814. */
  17815. Node.prototype.isReady = function (completeCheck) {
  17816. if (completeCheck === void 0) { completeCheck = false; }
  17817. return this._isReady;
  17818. };
  17819. /**
  17820. * Is this node enabled?
  17821. * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true
  17822. * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors
  17823. * @return whether this node (and its parent) is enabled
  17824. */
  17825. Node.prototype.isEnabled = function (checkAncestors) {
  17826. if (checkAncestors === void 0) { checkAncestors = true; }
  17827. if (checkAncestors === false) {
  17828. return this._isEnabled;
  17829. }
  17830. if (this._isEnabled === false) {
  17831. return false;
  17832. }
  17833. if (this.parent !== undefined && this.parent !== null) {
  17834. return this.parent.isEnabled(checkAncestors);
  17835. }
  17836. return true;
  17837. };
  17838. /**
  17839. * Set the enabled state of this node
  17840. * @param value defines the new enabled state
  17841. */
  17842. Node.prototype.setEnabled = function (value) {
  17843. this._isEnabled = value;
  17844. };
  17845. /**
  17846. * Is this node a descendant of the given node?
  17847. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17848. * @param ancestor defines the parent node to inspect
  17849. * @returns a boolean indicating if this node is a descendant of the given node
  17850. */
  17851. Node.prototype.isDescendantOf = function (ancestor) {
  17852. if (this.parent) {
  17853. if (this.parent === ancestor) {
  17854. return true;
  17855. }
  17856. return this.parent.isDescendantOf(ancestor);
  17857. }
  17858. return false;
  17859. };
  17860. /** @hidden */
  17861. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17862. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17863. if (!this._children) {
  17864. return;
  17865. }
  17866. for (var index = 0; index < this._children.length; index++) {
  17867. var item = this._children[index];
  17868. if (!predicate || predicate(item)) {
  17869. results.push(item);
  17870. }
  17871. if (!directDescendantsOnly) {
  17872. item._getDescendants(results, false, predicate);
  17873. }
  17874. }
  17875. };
  17876. /**
  17877. * Will return all nodes that have this node as ascendant
  17878. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  17879. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  17880. * @return all children nodes of all types
  17881. */
  17882. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17883. var results = new Array();
  17884. this._getDescendants(results, directDescendantsOnly, predicate);
  17885. return results;
  17886. };
  17887. /**
  17888. * Get all child-meshes of this node
  17889. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  17890. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  17891. * @returns an array of {BABYLON.AbstractMesh}
  17892. */
  17893. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17894. var results = [];
  17895. this._getDescendants(results, directDescendantsOnly, function (node) {
  17896. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17897. });
  17898. return results;
  17899. };
  17900. /**
  17901. * Get all child-transformNodes of this node
  17902. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  17903. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  17904. * @returns an array of {BABYLON.TransformNode}
  17905. */
  17906. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17907. var results = [];
  17908. this._getDescendants(results, directDescendantsOnly, function (node) {
  17909. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17910. });
  17911. return results;
  17912. };
  17913. /**
  17914. * Get all direct children of this node
  17915. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  17916. * @returns an array of {BABYLON.Node}
  17917. */
  17918. Node.prototype.getChildren = function (predicate) {
  17919. return this.getDescendants(true, predicate);
  17920. };
  17921. /** @hidden */
  17922. Node.prototype._setReady = function (state) {
  17923. if (state === this._isReady) {
  17924. return;
  17925. }
  17926. if (!state) {
  17927. this._isReady = false;
  17928. return;
  17929. }
  17930. if (this.onReady) {
  17931. this.onReady(this);
  17932. }
  17933. this._isReady = true;
  17934. };
  17935. /**
  17936. * Get an animation by name
  17937. * @param name defines the name of the animation to look for
  17938. * @returns null if not found else the requested animation
  17939. */
  17940. Node.prototype.getAnimationByName = function (name) {
  17941. for (var i = 0; i < this.animations.length; i++) {
  17942. var animation = this.animations[i];
  17943. if (animation.name === name) {
  17944. return animation;
  17945. }
  17946. }
  17947. return null;
  17948. };
  17949. /**
  17950. * Creates an animation range for this node
  17951. * @param name defines the name of the range
  17952. * @param from defines the starting key
  17953. * @param to defines the end key
  17954. */
  17955. Node.prototype.createAnimationRange = function (name, from, to) {
  17956. // check name not already in use
  17957. if (!this._ranges[name]) {
  17958. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17959. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17960. if (this.animations[i]) {
  17961. this.animations[i].createRange(name, from, to);
  17962. }
  17963. }
  17964. }
  17965. };
  17966. /**
  17967. * Delete a specific animation range
  17968. * @param name defines the name of the range to delete
  17969. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17970. */
  17971. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17972. if (deleteFrames === void 0) { deleteFrames = true; }
  17973. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17974. if (this.animations[i]) {
  17975. this.animations[i].deleteRange(name, deleteFrames);
  17976. }
  17977. }
  17978. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17979. };
  17980. /**
  17981. * Get an animation range by name
  17982. * @param name defines the name of the animation range to look for
  17983. * @returns null if not found else the requested animation range
  17984. */
  17985. Node.prototype.getAnimationRange = function (name) {
  17986. return this._ranges[name];
  17987. };
  17988. /**
  17989. * Will start the animation sequence
  17990. * @param name defines the range frames for animation sequence
  17991. * @param loop defines if the animation should loop (false by default)
  17992. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17993. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17994. * @returns the object created for this animation. If range does not exist, it will return null
  17995. */
  17996. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17997. var range = this.getAnimationRange(name);
  17998. if (!range) {
  17999. return null;
  18000. }
  18001. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18002. };
  18003. /**
  18004. * Serialize animation ranges into a JSON compatible object
  18005. * @returns serialization object
  18006. */
  18007. Node.prototype.serializeAnimationRanges = function () {
  18008. var serializationRanges = [];
  18009. for (var name in this._ranges) {
  18010. var localRange = this._ranges[name];
  18011. if (!localRange) {
  18012. continue;
  18013. }
  18014. var range = {};
  18015. range.name = name;
  18016. range.from = localRange.from;
  18017. range.to = localRange.to;
  18018. serializationRanges.push(range);
  18019. }
  18020. return serializationRanges;
  18021. };
  18022. /**
  18023. * Computes the world matrix of the node
  18024. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18025. * @returns the world matrix
  18026. */
  18027. Node.prototype.computeWorldMatrix = function (force) {
  18028. return BABYLON.Matrix.Identity();
  18029. };
  18030. /**
  18031. * Releases resources associated with this node.
  18032. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18033. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18034. */
  18035. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18036. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18037. if (!doNotRecurse) {
  18038. var nodes = this.getDescendants(true);
  18039. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18040. var node = nodes_1[_i];
  18041. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18042. }
  18043. }
  18044. else {
  18045. var transformNodes = this.getChildTransformNodes(true);
  18046. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18047. var transformNode = transformNodes_1[_a];
  18048. transformNode.parent = null;
  18049. transformNode.computeWorldMatrix(true);
  18050. }
  18051. }
  18052. this.parent = null;
  18053. // Callback
  18054. this.onDisposeObservable.notifyObservers(this);
  18055. this.onDisposeObservable.clear();
  18056. // Behaviors
  18057. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18058. var behavior = _c[_b];
  18059. behavior.detach();
  18060. }
  18061. this._behaviors = [];
  18062. this._isDisposed = true;
  18063. };
  18064. /**
  18065. * Parse animation range data from a serialization object and store them into a given node
  18066. * @param node defines where to store the animation ranges
  18067. * @param parsedNode defines the serialization object to read data from
  18068. * @param scene defines the hosting scene
  18069. */
  18070. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18071. if (parsedNode.ranges) {
  18072. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18073. var data = parsedNode.ranges[index];
  18074. node.createAnimationRange(data.name, data.from, data.to);
  18075. }
  18076. }
  18077. };
  18078. __decorate([
  18079. BABYLON.serialize()
  18080. ], Node.prototype, "name", void 0);
  18081. __decorate([
  18082. BABYLON.serialize()
  18083. ], Node.prototype, "id", void 0);
  18084. __decorate([
  18085. BABYLON.serialize()
  18086. ], Node.prototype, "uniqueId", void 0);
  18087. __decorate([
  18088. BABYLON.serialize()
  18089. ], Node.prototype, "state", void 0);
  18090. __decorate([
  18091. BABYLON.serialize()
  18092. ], Node.prototype, "metadata", void 0);
  18093. return Node;
  18094. }());
  18095. BABYLON.Node = Node;
  18096. })(BABYLON || (BABYLON = {}));
  18097. //# sourceMappingURL=babylon.node.js.map
  18098. var BABYLON;
  18099. (function (BABYLON) {
  18100. var BoundingSphere = /** @class */ (function () {
  18101. /**
  18102. * Creates a new bounding sphere
  18103. * @param min defines the minimum vector (in local space)
  18104. * @param max defines the maximum vector (in local space)
  18105. */
  18106. function BoundingSphere(min, max) {
  18107. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18108. this.reConstruct(min, max);
  18109. }
  18110. /**
  18111. * Recreates the entire bounding sphere from scratch
  18112. * @param min defines the new minimum vector (in local space)
  18113. * @param max defines the new maximum vector (in local space)
  18114. */
  18115. BoundingSphere.prototype.reConstruct = function (min, max) {
  18116. this.minimum = min.clone();
  18117. this.maximum = max.clone();
  18118. var distance = BABYLON.Vector3.Distance(min, max);
  18119. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18120. this.radius = distance * 0.5;
  18121. this.centerWorld = BABYLON.Vector3.Zero();
  18122. this._update(BABYLON.Matrix.Identity());
  18123. };
  18124. // Methods
  18125. BoundingSphere.prototype._update = function (world) {
  18126. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18127. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18128. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18129. };
  18130. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18131. for (var i = 0; i < 6; i++) {
  18132. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18133. return false;
  18134. }
  18135. return true;
  18136. };
  18137. BoundingSphere.prototype.intersectsPoint = function (point) {
  18138. var x = this.centerWorld.x - point.x;
  18139. var y = this.centerWorld.y - point.y;
  18140. var z = this.centerWorld.z - point.z;
  18141. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18142. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18143. return false;
  18144. return true;
  18145. };
  18146. // Statics
  18147. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18148. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18149. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18150. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18151. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18152. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18153. return false;
  18154. return true;
  18155. };
  18156. return BoundingSphere;
  18157. }());
  18158. BABYLON.BoundingSphere = BoundingSphere;
  18159. })(BABYLON || (BABYLON = {}));
  18160. //# sourceMappingURL=babylon.boundingSphere.js.map
  18161. var BABYLON;
  18162. (function (BABYLON) {
  18163. var BoundingBox = /** @class */ (function () {
  18164. /**
  18165. * Creates a new bounding box
  18166. * @param min defines the minimum vector (in local space)
  18167. * @param max defines the maximum vector (in local space)
  18168. */
  18169. function BoundingBox(min, max) {
  18170. this.vectorsWorld = new Array();
  18171. this.reConstruct(min, max);
  18172. }
  18173. // Methods
  18174. /**
  18175. * Recreates the entire bounding box from scratch
  18176. * @param min defines the new minimum vector (in local space)
  18177. * @param max defines the new maximum vector (in local space)
  18178. */
  18179. BoundingBox.prototype.reConstruct = function (min, max) {
  18180. this.minimum = min.clone();
  18181. this.maximum = max.clone();
  18182. // Bounding vectors
  18183. this.vectors = new Array();
  18184. this.vectors.push(this.minimum.clone());
  18185. this.vectors.push(this.maximum.clone());
  18186. this.vectors.push(this.minimum.clone());
  18187. this.vectors[2].x = this.maximum.x;
  18188. this.vectors.push(this.minimum.clone());
  18189. this.vectors[3].y = this.maximum.y;
  18190. this.vectors.push(this.minimum.clone());
  18191. this.vectors[4].z = this.maximum.z;
  18192. this.vectors.push(this.maximum.clone());
  18193. this.vectors[5].z = this.minimum.z;
  18194. this.vectors.push(this.maximum.clone());
  18195. this.vectors[6].x = this.minimum.x;
  18196. this.vectors.push(this.maximum.clone());
  18197. this.vectors[7].y = this.minimum.y;
  18198. // OBB
  18199. this.center = this.maximum.add(this.minimum).scale(0.5);
  18200. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18201. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18202. // World
  18203. for (var index = 0; index < this.vectors.length; index++) {
  18204. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18205. }
  18206. this.minimumWorld = BABYLON.Vector3.Zero();
  18207. this.maximumWorld = BABYLON.Vector3.Zero();
  18208. this.centerWorld = BABYLON.Vector3.Zero();
  18209. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18210. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18211. };
  18212. BoundingBox.prototype.getWorldMatrix = function () {
  18213. return this._worldMatrix;
  18214. };
  18215. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18216. this._worldMatrix.copyFrom(matrix);
  18217. return this;
  18218. };
  18219. BoundingBox.prototype._update = function (world) {
  18220. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18221. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18222. for (var index = 0; index < this.vectors.length; index++) {
  18223. var v = this.vectorsWorld[index];
  18224. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18225. if (v.x < this.minimumWorld.x)
  18226. this.minimumWorld.x = v.x;
  18227. if (v.y < this.minimumWorld.y)
  18228. this.minimumWorld.y = v.y;
  18229. if (v.z < this.minimumWorld.z)
  18230. this.minimumWorld.z = v.z;
  18231. if (v.x > this.maximumWorld.x)
  18232. this.maximumWorld.x = v.x;
  18233. if (v.y > this.maximumWorld.y)
  18234. this.maximumWorld.y = v.y;
  18235. if (v.z > this.maximumWorld.z)
  18236. this.maximumWorld.z = v.z;
  18237. }
  18238. // Extend
  18239. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18240. this.extendSizeWorld.scaleInPlace(0.5);
  18241. // OBB
  18242. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18243. this.centerWorld.scaleInPlace(0.5);
  18244. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18245. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18246. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18247. this._worldMatrix = world;
  18248. };
  18249. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18250. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18251. };
  18252. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18253. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18254. };
  18255. BoundingBox.prototype.intersectsPoint = function (point) {
  18256. var delta = -BABYLON.Epsilon;
  18257. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18258. return false;
  18259. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18260. return false;
  18261. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18262. return false;
  18263. return true;
  18264. };
  18265. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18266. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18267. };
  18268. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18269. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18270. return false;
  18271. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18272. return false;
  18273. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18274. return false;
  18275. return true;
  18276. };
  18277. // Statics
  18278. BoundingBox.Intersects = function (box0, box1) {
  18279. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18280. return false;
  18281. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18282. return false;
  18283. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18284. return false;
  18285. return true;
  18286. };
  18287. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18288. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18289. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18290. return (num <= (sphereRadius * sphereRadius));
  18291. };
  18292. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18293. for (var p = 0; p < 6; p++) {
  18294. for (var i = 0; i < 8; i++) {
  18295. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18296. return false;
  18297. }
  18298. }
  18299. }
  18300. return true;
  18301. };
  18302. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18303. for (var p = 0; p < 6; p++) {
  18304. var inCount = 8;
  18305. for (var i = 0; i < 8; i++) {
  18306. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18307. --inCount;
  18308. }
  18309. else {
  18310. break;
  18311. }
  18312. }
  18313. if (inCount === 0)
  18314. return false;
  18315. }
  18316. return true;
  18317. };
  18318. return BoundingBox;
  18319. }());
  18320. BABYLON.BoundingBox = BoundingBox;
  18321. })(BABYLON || (BABYLON = {}));
  18322. //# sourceMappingURL=babylon.boundingBox.js.map
  18323. var BABYLON;
  18324. (function (BABYLON) {
  18325. var computeBoxExtents = function (axis, box) {
  18326. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18327. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18328. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18329. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18330. var r = r0 + r1 + r2;
  18331. return {
  18332. min: p - r,
  18333. max: p + r
  18334. };
  18335. };
  18336. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18337. var axisOverlap = function (axis, box0, box1) {
  18338. var result0 = computeBoxExtents(axis, box0);
  18339. var result1 = computeBoxExtents(axis, box1);
  18340. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18341. };
  18342. var BoundingInfo = /** @class */ (function () {
  18343. function BoundingInfo(minimum, maximum) {
  18344. this.minimum = minimum;
  18345. this.maximum = maximum;
  18346. this._isLocked = false;
  18347. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18348. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18349. }
  18350. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18351. get: function () {
  18352. return this._isLocked;
  18353. },
  18354. set: function (value) {
  18355. this._isLocked = value;
  18356. },
  18357. enumerable: true,
  18358. configurable: true
  18359. });
  18360. // Methods
  18361. BoundingInfo.prototype.update = function (world) {
  18362. if (this._isLocked) {
  18363. return;
  18364. }
  18365. this.boundingBox._update(world);
  18366. this.boundingSphere._update(world);
  18367. };
  18368. /**
  18369. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18370. * @param center New center of the bounding info
  18371. * @param extend New extend of the bounding info
  18372. */
  18373. BoundingInfo.prototype.centerOn = function (center, extend) {
  18374. this.minimum = center.subtract(extend);
  18375. this.maximum = center.add(extend);
  18376. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18377. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18378. return this;
  18379. };
  18380. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18381. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18382. return false;
  18383. return this.boundingBox.isInFrustum(frustumPlanes);
  18384. };
  18385. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18386. /**
  18387. * Gets the world distance between the min and max points of the bounding box
  18388. */
  18389. get: function () {
  18390. var boundingBox = this.boundingBox;
  18391. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18392. return size.length();
  18393. },
  18394. enumerable: true,
  18395. configurable: true
  18396. });
  18397. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18398. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18399. };
  18400. BoundingInfo.prototype._checkCollision = function (collider) {
  18401. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18402. };
  18403. BoundingInfo.prototype.intersectsPoint = function (point) {
  18404. if (!this.boundingSphere.centerWorld) {
  18405. return false;
  18406. }
  18407. if (!this.boundingSphere.intersectsPoint(point)) {
  18408. return false;
  18409. }
  18410. if (!this.boundingBox.intersectsPoint(point)) {
  18411. return false;
  18412. }
  18413. return true;
  18414. };
  18415. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18416. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18417. return false;
  18418. }
  18419. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18420. return false;
  18421. }
  18422. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18423. return false;
  18424. }
  18425. if (!precise) {
  18426. return true;
  18427. }
  18428. var box0 = this.boundingBox;
  18429. var box1 = boundingInfo.boundingBox;
  18430. if (!axisOverlap(box0.directions[0], box0, box1))
  18431. return false;
  18432. if (!axisOverlap(box0.directions[1], box0, box1))
  18433. return false;
  18434. if (!axisOverlap(box0.directions[2], box0, box1))
  18435. return false;
  18436. if (!axisOverlap(box1.directions[0], box0, box1))
  18437. return false;
  18438. if (!axisOverlap(box1.directions[1], box0, box1))
  18439. return false;
  18440. if (!axisOverlap(box1.directions[2], box0, box1))
  18441. return false;
  18442. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18443. return false;
  18444. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18445. return false;
  18446. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18447. return false;
  18448. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18449. return false;
  18450. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18451. return false;
  18452. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18453. return false;
  18454. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18455. return false;
  18456. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18457. return false;
  18458. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18459. return false;
  18460. return true;
  18461. };
  18462. return BoundingInfo;
  18463. }());
  18464. BABYLON.BoundingInfo = BoundingInfo;
  18465. })(BABYLON || (BABYLON = {}));
  18466. //# sourceMappingURL=babylon.boundingInfo.js.map
  18467. var BABYLON;
  18468. (function (BABYLON) {
  18469. var TransformNode = /** @class */ (function (_super) {
  18470. __extends(TransformNode, _super);
  18471. function TransformNode(name, scene, isPure) {
  18472. if (scene === void 0) { scene = null; }
  18473. if (isPure === void 0) { isPure = true; }
  18474. var _this = _super.call(this, name, scene) || this;
  18475. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18476. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18477. _this._up = new BABYLON.Vector3(0, 1, 0);
  18478. _this._right = new BABYLON.Vector3(1, 0, 0);
  18479. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18480. // Properties
  18481. _this._rotation = BABYLON.Vector3.Zero();
  18482. _this._scaling = BABYLON.Vector3.One();
  18483. _this._isDirty = false;
  18484. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18485. _this.scalingDeterminant = 1;
  18486. _this.infiniteDistance = false;
  18487. _this.position = BABYLON.Vector3.Zero();
  18488. _this._localWorld = BABYLON.Matrix.Zero();
  18489. _this._worldMatrix = BABYLON.Matrix.Zero();
  18490. _this._worldMatrixDeterminant = 0;
  18491. _this._absolutePosition = BABYLON.Vector3.Zero();
  18492. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18493. _this._postMultiplyPivotMatrix = false;
  18494. _this._isWorldMatrixFrozen = false;
  18495. /**
  18496. * An event triggered after the world matrix is updated
  18497. */
  18498. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18499. _this._nonUniformScaling = false;
  18500. if (isPure) {
  18501. _this.getScene().addTransformNode(_this);
  18502. }
  18503. return _this;
  18504. }
  18505. /**
  18506. * Gets a string idenfifying the name of the class
  18507. * @returns "TransformNode" string
  18508. */
  18509. TransformNode.prototype.getClassName = function () {
  18510. return "TransformNode";
  18511. };
  18512. Object.defineProperty(TransformNode.prototype, "rotation", {
  18513. /**
  18514. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18515. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18516. * Default : (0.0, 0.0, 0.0)
  18517. */
  18518. get: function () {
  18519. return this._rotation;
  18520. },
  18521. set: function (newRotation) {
  18522. this._rotation = newRotation;
  18523. },
  18524. enumerable: true,
  18525. configurable: true
  18526. });
  18527. Object.defineProperty(TransformNode.prototype, "scaling", {
  18528. /**
  18529. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18530. * Default : (1.0, 1.0, 1.0)
  18531. */
  18532. get: function () {
  18533. return this._scaling;
  18534. },
  18535. /**
  18536. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18537. * Default : (1.0, 1.0, 1.0)
  18538. */
  18539. set: function (newScaling) {
  18540. this._scaling = newScaling;
  18541. },
  18542. enumerable: true,
  18543. configurable: true
  18544. });
  18545. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18546. /**
  18547. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18548. * It's null by default.
  18549. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  18550. */
  18551. get: function () {
  18552. return this._rotationQuaternion;
  18553. },
  18554. set: function (quaternion) {
  18555. this._rotationQuaternion = quaternion;
  18556. //reset the rotation vector.
  18557. if (quaternion && this.rotation.length()) {
  18558. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18559. }
  18560. },
  18561. enumerable: true,
  18562. configurable: true
  18563. });
  18564. Object.defineProperty(TransformNode.prototype, "forward", {
  18565. /**
  18566. * The forward direction of that transform in world space.
  18567. */
  18568. get: function () {
  18569. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18570. },
  18571. enumerable: true,
  18572. configurable: true
  18573. });
  18574. Object.defineProperty(TransformNode.prototype, "up", {
  18575. /**
  18576. * The up direction of that transform in world space.
  18577. */
  18578. get: function () {
  18579. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18580. },
  18581. enumerable: true,
  18582. configurable: true
  18583. });
  18584. Object.defineProperty(TransformNode.prototype, "right", {
  18585. /**
  18586. * The right direction of that transform in world space.
  18587. */
  18588. get: function () {
  18589. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18590. },
  18591. enumerable: true,
  18592. configurable: true
  18593. });
  18594. /**
  18595. * Returns the latest update of the World matrix
  18596. * Returns a Matrix.
  18597. */
  18598. TransformNode.prototype.getWorldMatrix = function () {
  18599. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18600. this.computeWorldMatrix();
  18601. }
  18602. return this._worldMatrix;
  18603. };
  18604. /** @hidden */
  18605. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18606. return this._worldMatrixDeterminant;
  18607. };
  18608. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18609. /**
  18610. * Returns directly the latest state of the mesh World matrix.
  18611. * A Matrix is returned.
  18612. */
  18613. get: function () {
  18614. return this._worldMatrix;
  18615. },
  18616. enumerable: true,
  18617. configurable: true
  18618. });
  18619. /**
  18620. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18621. * Returns the TransformNode.
  18622. */
  18623. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18624. this._poseMatrix.copyFrom(matrix);
  18625. return this;
  18626. };
  18627. /**
  18628. * Returns the mesh Pose matrix.
  18629. * Returned object : Matrix
  18630. */
  18631. TransformNode.prototype.getPoseMatrix = function () {
  18632. return this._poseMatrix;
  18633. };
  18634. TransformNode.prototype._isSynchronized = function () {
  18635. if (this._isDirty) {
  18636. return false;
  18637. }
  18638. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18639. return false;
  18640. if (this._cache.pivotMatrixUpdated) {
  18641. return false;
  18642. }
  18643. if (this.infiniteDistance) {
  18644. return false;
  18645. }
  18646. if (!this._cache.position.equals(this.position))
  18647. return false;
  18648. if (this.rotationQuaternion) {
  18649. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18650. return false;
  18651. }
  18652. if (!this._cache.rotation.equals(this.rotation))
  18653. return false;
  18654. if (!this._cache.scaling.equals(this.scaling))
  18655. return false;
  18656. return true;
  18657. };
  18658. TransformNode.prototype._initCache = function () {
  18659. _super.prototype._initCache.call(this);
  18660. this._cache.localMatrixUpdated = false;
  18661. this._cache.position = BABYLON.Vector3.Zero();
  18662. this._cache.scaling = BABYLON.Vector3.Zero();
  18663. this._cache.rotation = BABYLON.Vector3.Zero();
  18664. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18665. this._cache.billboardMode = -1;
  18666. };
  18667. TransformNode.prototype.markAsDirty = function (property) {
  18668. if (property === "rotation") {
  18669. this.rotationQuaternion = null;
  18670. }
  18671. this._currentRenderId = Number.MAX_VALUE;
  18672. this._isDirty = true;
  18673. return this;
  18674. };
  18675. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18676. /**
  18677. * Returns the current mesh absolute position.
  18678. * Retuns a Vector3.
  18679. */
  18680. get: function () {
  18681. return this._absolutePosition;
  18682. },
  18683. enumerable: true,
  18684. configurable: true
  18685. });
  18686. /**
  18687. * Sets a new matrix to apply before all other transformation
  18688. * @param matrix defines the transform matrix
  18689. * @returns the current TransformNode
  18690. */
  18691. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18692. return this.setPivotMatrix(matrix, false);
  18693. };
  18694. /**
  18695. * Sets a new pivot matrix to the current node
  18696. * @param matrix defines the new pivot matrix to use
  18697. * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect
  18698. * @returns the current TransformNode
  18699. */
  18700. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18701. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18702. this._pivotMatrix = matrix.clone();
  18703. this._cache.pivotMatrixUpdated = true;
  18704. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18705. if (this._postMultiplyPivotMatrix) {
  18706. if (!this._pivotMatrixInverse) {
  18707. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18708. }
  18709. else {
  18710. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18711. }
  18712. }
  18713. return this;
  18714. };
  18715. /**
  18716. * Returns the mesh pivot matrix.
  18717. * Default : Identity.
  18718. * A Matrix is returned.
  18719. */
  18720. TransformNode.prototype.getPivotMatrix = function () {
  18721. return this._pivotMatrix;
  18722. };
  18723. /**
  18724. * Prevents the World matrix to be computed any longer.
  18725. * Returns the TransformNode.
  18726. */
  18727. TransformNode.prototype.freezeWorldMatrix = function () {
  18728. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18729. this.computeWorldMatrix(true);
  18730. this._isWorldMatrixFrozen = true;
  18731. return this;
  18732. };
  18733. /**
  18734. * Allows back the World matrix computation.
  18735. * Returns the TransformNode.
  18736. */
  18737. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18738. this._isWorldMatrixFrozen = false;
  18739. this.computeWorldMatrix(true);
  18740. return this;
  18741. };
  18742. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18743. /**
  18744. * True if the World matrix has been frozen.
  18745. * Returns a boolean.
  18746. */
  18747. get: function () {
  18748. return this._isWorldMatrixFrozen;
  18749. },
  18750. enumerable: true,
  18751. configurable: true
  18752. });
  18753. /**
  18754. * Retuns the mesh absolute position in the World.
  18755. * Returns a Vector3.
  18756. */
  18757. TransformNode.prototype.getAbsolutePosition = function () {
  18758. this.computeWorldMatrix();
  18759. return this._absolutePosition;
  18760. };
  18761. /**
  18762. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18763. * Returns the TransformNode.
  18764. */
  18765. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18766. if (!absolutePosition) {
  18767. return this;
  18768. }
  18769. var absolutePositionX;
  18770. var absolutePositionY;
  18771. var absolutePositionZ;
  18772. if (absolutePosition.x === undefined) {
  18773. if (arguments.length < 3) {
  18774. return this;
  18775. }
  18776. absolutePositionX = arguments[0];
  18777. absolutePositionY = arguments[1];
  18778. absolutePositionZ = arguments[2];
  18779. }
  18780. else {
  18781. absolutePositionX = absolutePosition.x;
  18782. absolutePositionY = absolutePosition.y;
  18783. absolutePositionZ = absolutePosition.z;
  18784. }
  18785. if (this.parent) {
  18786. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18787. invertParentWorldMatrix.invert();
  18788. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18789. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18790. }
  18791. else {
  18792. this.position.x = absolutePositionX;
  18793. this.position.y = absolutePositionY;
  18794. this.position.z = absolutePositionZ;
  18795. }
  18796. return this;
  18797. };
  18798. /**
  18799. * Sets the mesh position in its local space.
  18800. * Returns the TransformNode.
  18801. */
  18802. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18803. this.computeWorldMatrix();
  18804. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18805. return this;
  18806. };
  18807. /**
  18808. * Returns the mesh position in the local space from the current World matrix values.
  18809. * Returns a new Vector3.
  18810. */
  18811. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18812. this.computeWorldMatrix();
  18813. var invLocalWorldMatrix = this._localWorld.clone();
  18814. invLocalWorldMatrix.invert();
  18815. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18816. };
  18817. /**
  18818. * Translates the mesh along the passed Vector3 in its local space.
  18819. * Returns the TransformNode.
  18820. */
  18821. TransformNode.prototype.locallyTranslate = function (vector3) {
  18822. this.computeWorldMatrix(true);
  18823. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18824. return this;
  18825. };
  18826. /**
  18827. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18828. * @param targetPoint the position (must be in same space as current mesh) to look at
  18829. * @param yawCor optional yaw (y-axis) correction in radians
  18830. * @param pitchCor optional pitch (x-axis) correction in radians
  18831. * @param rollCor optional roll (z-axis) correction in radians
  18832. * @param space the choosen space of the target
  18833. * @returns the TransformNode.
  18834. */
  18835. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18836. if (yawCor === void 0) { yawCor = 0; }
  18837. if (pitchCor === void 0) { pitchCor = 0; }
  18838. if (rollCor === void 0) { rollCor = 0; }
  18839. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18840. var dv = TransformNode._lookAtVectorCache;
  18841. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18842. targetPoint.subtractToRef(pos, dv);
  18843. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18844. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18845. var pitch = Math.atan2(dv.y, len);
  18846. if (this.rotationQuaternion) {
  18847. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18848. }
  18849. else {
  18850. this.rotation.x = pitch + pitchCor;
  18851. this.rotation.y = yaw + yawCor;
  18852. this.rotation.z = rollCor;
  18853. }
  18854. return this;
  18855. };
  18856. /**
  18857. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18858. * This Vector3 is expressed in the World space.
  18859. */
  18860. TransformNode.prototype.getDirection = function (localAxis) {
  18861. var result = BABYLON.Vector3.Zero();
  18862. this.getDirectionToRef(localAxis, result);
  18863. return result;
  18864. };
  18865. /**
  18866. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18867. * localAxis is expressed in the mesh local space.
  18868. * result is computed in the Wordl space from the mesh World matrix.
  18869. * Returns the TransformNode.
  18870. */
  18871. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18872. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18873. return this;
  18874. };
  18875. /**
  18876. * Sets a new pivot point to the current node
  18877. * @param point defines the new pivot point to use
  18878. * @param space defines if the point is in world or local space (local by default)
  18879. * @returns the current TransformNode
  18880. */
  18881. TransformNode.prototype.setPivotPoint = function (point, space) {
  18882. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18883. if (this.getScene().getRenderId() == 0) {
  18884. this.computeWorldMatrix(true);
  18885. }
  18886. var wm = this.getWorldMatrix();
  18887. if (space == BABYLON.Space.WORLD) {
  18888. var tmat = BABYLON.Tmp.Matrix[0];
  18889. wm.invertToRef(tmat);
  18890. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18891. }
  18892. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18893. };
  18894. /**
  18895. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18896. */
  18897. TransformNode.prototype.getPivotPoint = function () {
  18898. var point = BABYLON.Vector3.Zero();
  18899. this.getPivotPointToRef(point);
  18900. return point;
  18901. };
  18902. /**
  18903. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18904. * Returns the TransformNode.
  18905. */
  18906. TransformNode.prototype.getPivotPointToRef = function (result) {
  18907. result.x = -this._pivotMatrix.m[12];
  18908. result.y = -this._pivotMatrix.m[13];
  18909. result.z = -this._pivotMatrix.m[14];
  18910. return this;
  18911. };
  18912. /**
  18913. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18914. */
  18915. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18916. var point = BABYLON.Vector3.Zero();
  18917. this.getAbsolutePivotPointToRef(point);
  18918. return point;
  18919. };
  18920. /**
  18921. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18922. * Returns the TransformNode.
  18923. */
  18924. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18925. result.x = this._pivotMatrix.m[12];
  18926. result.y = this._pivotMatrix.m[13];
  18927. result.z = this._pivotMatrix.m[14];
  18928. this.getPivotPointToRef(result);
  18929. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18930. return this;
  18931. };
  18932. /**
  18933. * Defines the passed node as the parent of the current node.
  18934. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18935. * Returns the TransformNode.
  18936. */
  18937. TransformNode.prototype.setParent = function (node) {
  18938. if (node === null) {
  18939. var rotation = BABYLON.Tmp.Quaternion[0];
  18940. var position = BABYLON.Tmp.Vector3[0];
  18941. var scale = BABYLON.Tmp.Vector3[1];
  18942. if (this.parent && this.parent.computeWorldMatrix) {
  18943. this.parent.computeWorldMatrix(true);
  18944. }
  18945. this.computeWorldMatrix(true);
  18946. this.getWorldMatrix().decompose(scale, rotation, position);
  18947. if (this.rotationQuaternion) {
  18948. this.rotationQuaternion.copyFrom(rotation);
  18949. }
  18950. else {
  18951. rotation.toEulerAnglesToRef(this.rotation);
  18952. }
  18953. this.scaling.x = scale.x;
  18954. this.scaling.y = scale.y;
  18955. this.scaling.z = scale.z;
  18956. this.position.x = position.x;
  18957. this.position.y = position.y;
  18958. this.position.z = position.z;
  18959. }
  18960. else {
  18961. var rotation = BABYLON.Tmp.Quaternion[0];
  18962. var position = BABYLON.Tmp.Vector3[0];
  18963. var scale = BABYLON.Tmp.Vector3[1];
  18964. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18965. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18966. this.computeWorldMatrix(true);
  18967. node.computeWorldMatrix(true);
  18968. node.getWorldMatrix().invertToRef(invParentMatrix);
  18969. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18970. diffMatrix.decompose(scale, rotation, position);
  18971. if (this.rotationQuaternion) {
  18972. this.rotationQuaternion.copyFrom(rotation);
  18973. }
  18974. else {
  18975. rotation.toEulerAnglesToRef(this.rotation);
  18976. }
  18977. this.position.x = position.x;
  18978. this.position.y = position.y;
  18979. this.position.z = position.z;
  18980. this.scaling.x = scale.x;
  18981. this.scaling.y = scale.y;
  18982. this.scaling.z = scale.z;
  18983. }
  18984. this.parent = node;
  18985. return this;
  18986. };
  18987. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18988. get: function () {
  18989. return this._nonUniformScaling;
  18990. },
  18991. enumerable: true,
  18992. configurable: true
  18993. });
  18994. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18995. if (this._nonUniformScaling === value) {
  18996. return false;
  18997. }
  18998. this._nonUniformScaling = true;
  18999. return true;
  19000. };
  19001. /**
  19002. * Attach the current TransformNode to another TransformNode associated with a bone
  19003. * @param bone Bone affecting the TransformNode
  19004. * @param affectedTransformNode TransformNode associated with the bone
  19005. */
  19006. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19007. this._transformToBoneReferal = affectedTransformNode;
  19008. this.parent = bone;
  19009. if (bone.getWorldMatrix().determinant() < 0) {
  19010. this.scalingDeterminant *= -1;
  19011. }
  19012. return this;
  19013. };
  19014. TransformNode.prototype.detachFromBone = function () {
  19015. if (!this.parent) {
  19016. return this;
  19017. }
  19018. if (this.parent.getWorldMatrix().determinant() < 0) {
  19019. this.scalingDeterminant *= -1;
  19020. }
  19021. this._transformToBoneReferal = null;
  19022. this.parent = null;
  19023. return this;
  19024. };
  19025. /**
  19026. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19027. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19028. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19029. * The passed axis is also normalized.
  19030. * Returns the TransformNode.
  19031. */
  19032. TransformNode.prototype.rotate = function (axis, amount, space) {
  19033. axis.normalize();
  19034. if (!this.rotationQuaternion) {
  19035. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19036. this.rotation = BABYLON.Vector3.Zero();
  19037. }
  19038. var rotationQuaternion;
  19039. if (!space || space === BABYLON.Space.LOCAL) {
  19040. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19041. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19042. }
  19043. else {
  19044. if (this.parent) {
  19045. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19046. invertParentWorldMatrix.invert();
  19047. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19048. }
  19049. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19050. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19051. }
  19052. return this;
  19053. };
  19054. /**
  19055. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19056. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19057. * The passed axis is also normalized.
  19058. * Returns the TransformNode.
  19059. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19060. */
  19061. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19062. axis.normalize();
  19063. if (!this.rotationQuaternion) {
  19064. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19065. this.rotation.copyFromFloats(0, 0, 0);
  19066. }
  19067. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19068. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19069. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19070. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19071. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19072. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19073. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19074. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19075. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19076. return this;
  19077. };
  19078. /**
  19079. * Translates the mesh along the axis vector for the passed distance in the given space.
  19080. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19081. * Returns the TransformNode.
  19082. */
  19083. TransformNode.prototype.translate = function (axis, distance, space) {
  19084. var displacementVector = axis.scale(distance);
  19085. if (!space || space === BABYLON.Space.LOCAL) {
  19086. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19087. this.setPositionWithLocalVector(tempV3);
  19088. }
  19089. else {
  19090. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19091. }
  19092. return this;
  19093. };
  19094. /**
  19095. * Adds a rotation step to the mesh current rotation.
  19096. * x, y, z are Euler angles expressed in radians.
  19097. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19098. * This means this rotation is made in the mesh local space only.
  19099. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19100. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19101. * ```javascript
  19102. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19103. * ```
  19104. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19105. * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.
  19106. * Returns the TransformNode.
  19107. */
  19108. TransformNode.prototype.addRotation = function (x, y, z) {
  19109. var rotationQuaternion;
  19110. if (this.rotationQuaternion) {
  19111. rotationQuaternion = this.rotationQuaternion;
  19112. }
  19113. else {
  19114. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19115. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19116. }
  19117. var accumulation = BABYLON.Tmp.Quaternion[0];
  19118. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19119. rotationQuaternion.multiplyInPlace(accumulation);
  19120. if (!this.rotationQuaternion) {
  19121. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19122. }
  19123. return this;
  19124. };
  19125. /**
  19126. * Computes the mesh World matrix and returns it.
  19127. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19128. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19129. * If the parameter `force`is set to `true`, the actual computation is done.
  19130. * Returns the mesh World Matrix.
  19131. */
  19132. TransformNode.prototype.computeWorldMatrix = function (force) {
  19133. if (this._isWorldMatrixFrozen) {
  19134. return this._worldMatrix;
  19135. }
  19136. if (!force && this.isSynchronized(true)) {
  19137. this._currentRenderId = this.getScene().getRenderId();
  19138. return this._worldMatrix;
  19139. }
  19140. this._cache.position.copyFrom(this.position);
  19141. this._cache.scaling.copyFrom(this.scaling);
  19142. this._cache.pivotMatrixUpdated = false;
  19143. this._cache.billboardMode = this.billboardMode;
  19144. this._currentRenderId = this.getScene().getRenderId();
  19145. this._childRenderId = this.getScene().getRenderId();
  19146. this._isDirty = false;
  19147. // Scaling
  19148. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19149. // Rotation
  19150. //rotate, if quaternion is set and rotation was used
  19151. if (this.rotationQuaternion) {
  19152. var len = this.rotation.length();
  19153. if (len) {
  19154. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19155. this.rotation.copyFromFloats(0, 0, 0);
  19156. }
  19157. }
  19158. if (this.rotationQuaternion) {
  19159. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19160. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19161. }
  19162. else {
  19163. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19164. this._cache.rotation.copyFrom(this.rotation);
  19165. }
  19166. // Translation
  19167. var camera = this.getScene().activeCamera;
  19168. if (this.infiniteDistance && !this.parent && camera) {
  19169. var cameraWorldMatrix = camera.getWorldMatrix();
  19170. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19171. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19172. }
  19173. else {
  19174. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19175. }
  19176. // Composing transformations
  19177. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19178. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19179. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19180. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19181. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19182. // Need to decompose each rotation here
  19183. var currentPosition = BABYLON.Tmp.Vector3[3];
  19184. if (this.parent && this.parent.getWorldMatrix) {
  19185. if (this._transformToBoneReferal) {
  19186. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19187. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19188. }
  19189. else {
  19190. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19191. }
  19192. }
  19193. else {
  19194. currentPosition.copyFrom(this.position);
  19195. }
  19196. currentPosition.subtractInPlace(camera.globalPosition);
  19197. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19198. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19199. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19200. }
  19201. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19202. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19203. }
  19204. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19205. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19206. }
  19207. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19208. }
  19209. else {
  19210. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19211. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19212. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19213. }
  19214. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19215. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19216. }
  19217. // Local world
  19218. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19219. // Parent
  19220. if (this.parent && this.parent.getWorldMatrix) {
  19221. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19222. if (this._transformToBoneReferal) {
  19223. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19224. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19225. }
  19226. else {
  19227. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19228. }
  19229. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19230. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19231. this._worldMatrix.copyFrom(this._localWorld);
  19232. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19233. }
  19234. else {
  19235. if (this._transformToBoneReferal) {
  19236. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19237. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19238. }
  19239. else {
  19240. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19241. }
  19242. }
  19243. this._markSyncedWithParent();
  19244. }
  19245. else {
  19246. this._worldMatrix.copyFrom(this._localWorld);
  19247. }
  19248. // Post multiply inverse of pivotMatrix
  19249. if (this._postMultiplyPivotMatrix) {
  19250. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19251. }
  19252. // Normal matrix
  19253. if (this.scaling.isNonUniform) {
  19254. this._updateNonUniformScalingState(true);
  19255. }
  19256. else if (this.parent && this.parent._nonUniformScaling) {
  19257. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19258. }
  19259. else {
  19260. this._updateNonUniformScalingState(false);
  19261. }
  19262. this._afterComputeWorldMatrix();
  19263. // Absolute position
  19264. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19265. // Callbacks
  19266. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19267. if (!this._poseMatrix) {
  19268. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19269. }
  19270. // Cache the determinant
  19271. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19272. return this._worldMatrix;
  19273. };
  19274. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19275. };
  19276. /**
  19277. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19278. * @param func: callback function to add
  19279. *
  19280. * Returns the TransformNode.
  19281. */
  19282. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19283. this.onAfterWorldMatrixUpdateObservable.add(func);
  19284. return this;
  19285. };
  19286. /**
  19287. * Removes a registered callback function.
  19288. * Returns the TransformNode.
  19289. */
  19290. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19291. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19292. return this;
  19293. };
  19294. /**
  19295. * Clone the current transform node
  19296. * Returns the new transform node
  19297. * @param name Name of the new clone
  19298. * @param newParent New parent for the clone
  19299. * @param doNotCloneChildren Do not clone children hierarchy
  19300. */
  19301. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19302. var _this = this;
  19303. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19304. result.name = name;
  19305. result.id = name;
  19306. if (newParent) {
  19307. result.parent = newParent;
  19308. }
  19309. if (!doNotCloneChildren) {
  19310. // Children
  19311. var directDescendants = this.getDescendants(true);
  19312. for (var index = 0; index < directDescendants.length; index++) {
  19313. var child = directDescendants[index];
  19314. if (child.clone) {
  19315. child.clone(name + "." + child.name, result);
  19316. }
  19317. }
  19318. }
  19319. return result;
  19320. };
  19321. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19322. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19323. serializationObject.type = this.getClassName();
  19324. // Parent
  19325. if (this.parent) {
  19326. serializationObject.parentId = this.parent.id;
  19327. }
  19328. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19329. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19330. }
  19331. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19332. serializationObject.isEnabled = this.isEnabled();
  19333. // Parent
  19334. if (this.parent) {
  19335. serializationObject.parentId = this.parent.id;
  19336. }
  19337. return serializationObject;
  19338. };
  19339. // Statics
  19340. /**
  19341. * Returns a new TransformNode object parsed from the source provided.
  19342. * The parameter `parsedMesh` is the source.
  19343. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19344. */
  19345. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19346. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19347. if (BABYLON.Tags) {
  19348. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19349. }
  19350. if (parsedTransformNode.localMatrix) {
  19351. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19352. }
  19353. else if (parsedTransformNode.pivotMatrix) {
  19354. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19355. }
  19356. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19357. // Parent
  19358. if (parsedTransformNode.parentId) {
  19359. transformNode._waitingParentId = parsedTransformNode.parentId;
  19360. }
  19361. return transformNode;
  19362. };
  19363. /**
  19364. * Releases resources associated with this transform node.
  19365. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19366. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19367. */
  19368. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19369. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19370. // Animations
  19371. this.getScene().stopAnimation(this);
  19372. // Remove from scene
  19373. this.getScene().removeTransformNode(this);
  19374. this.onAfterWorldMatrixUpdateObservable.clear();
  19375. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19376. };
  19377. // Statics
  19378. TransformNode.BILLBOARDMODE_NONE = 0;
  19379. TransformNode.BILLBOARDMODE_X = 1;
  19380. TransformNode.BILLBOARDMODE_Y = 2;
  19381. TransformNode.BILLBOARDMODE_Z = 4;
  19382. TransformNode.BILLBOARDMODE_ALL = 7;
  19383. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19384. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19385. __decorate([
  19386. BABYLON.serializeAsVector3()
  19387. ], TransformNode.prototype, "_rotation", void 0);
  19388. __decorate([
  19389. BABYLON.serializeAsQuaternion()
  19390. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19391. __decorate([
  19392. BABYLON.serializeAsVector3()
  19393. ], TransformNode.prototype, "_scaling", void 0);
  19394. __decorate([
  19395. BABYLON.serialize()
  19396. ], TransformNode.prototype, "billboardMode", void 0);
  19397. __decorate([
  19398. BABYLON.serialize()
  19399. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19400. __decorate([
  19401. BABYLON.serialize()
  19402. ], TransformNode.prototype, "infiniteDistance", void 0);
  19403. __decorate([
  19404. BABYLON.serializeAsVector3()
  19405. ], TransformNode.prototype, "position", void 0);
  19406. return TransformNode;
  19407. }(BABYLON.Node));
  19408. BABYLON.TransformNode = TransformNode;
  19409. })(BABYLON || (BABYLON = {}));
  19410. //# sourceMappingURL=babylon.transformNode.js.map
  19411. var BABYLON;
  19412. (function (BABYLON) {
  19413. /**
  19414. * Class used to store all common mesh properties
  19415. */
  19416. var AbstractMesh = /** @class */ (function (_super) {
  19417. __extends(AbstractMesh, _super);
  19418. // Constructor
  19419. /**
  19420. * Creates a new AbstractMesh
  19421. * @param name defines the name of the mesh
  19422. * @param scene defines the hosting scene
  19423. */
  19424. function AbstractMesh(name, scene) {
  19425. if (scene === void 0) { scene = null; }
  19426. var _this = _super.call(this, name, scene, false) || this;
  19427. _this._facetNb = 0; // facet number
  19428. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19429. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19430. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19431. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19432. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19433. _this._subDiv = {
  19434. max: 1,
  19435. X: 1,
  19436. Y: 1,
  19437. Z: 1
  19438. };
  19439. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19440. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19441. // Events
  19442. /**
  19443. * An event triggered when this mesh collides with another one
  19444. */
  19445. _this.onCollideObservable = new BABYLON.Observable();
  19446. /**
  19447. * An event triggered when the collision's position changes
  19448. */
  19449. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19450. /**
  19451. * An event triggered when material is changed
  19452. */
  19453. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19454. // Properties
  19455. /**
  19456. * Gets or sets the orientation for POV movement & rotation
  19457. */
  19458. _this.definedFacingForward = true;
  19459. /**
  19460. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19461. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19462. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate.
  19463. * @see http://doc.babylonjs.com/features/occlusionquery
  19464. */
  19465. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19466. /**
  19467. * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values:
  19468. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19469. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19470. * * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show.
  19471. * @see http://doc.babylonjs.com/features/occlusionquery
  19472. */
  19473. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19474. /**
  19475. * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object.
  19476. * The default value is -1 which means don't break the query and wait till the result
  19477. * @see http://doc.babylonjs.com/features/occlusionquery
  19478. */
  19479. _this.occlusionRetryCount = -1;
  19480. _this._occlusionInternalRetryCounter = 0;
  19481. _this._isOccluded = false;
  19482. _this._isOcclusionQueryInProgress = false;
  19483. _this._visibility = 1.0;
  19484. /** Gets or sets the alpha index used to sort transparent meshes
  19485. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19486. */
  19487. _this.alphaIndex = Number.MAX_VALUE;
  19488. /**
  19489. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19490. */
  19491. _this.isVisible = true;
  19492. /**
  19493. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19494. */
  19495. _this.isPickable = true;
  19496. /**
  19497. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19498. */
  19499. _this.showBoundingBox = false;
  19500. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19501. _this.showSubMeshesBoundingBox = false;
  19502. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19503. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19504. */
  19505. _this.isBlocker = false;
  19506. /**
  19507. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19508. */
  19509. _this.enablePointerMoveEvents = false;
  19510. /**
  19511. * Specifies the rendering group id for this mesh (0 by default)
  19512. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19513. */
  19514. _this.renderingGroupId = 0;
  19515. _this._receiveShadows = false;
  19516. /**
  19517. * Gets or sets a boolean indicating if the outline must be rendered as well
  19518. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19519. */
  19520. _this.renderOutline = false;
  19521. /** Defines color to use when rendering outline */
  19522. _this.outlineColor = BABYLON.Color3.Red();
  19523. /** Define width to use when rendering outline */
  19524. _this.outlineWidth = 0.02;
  19525. /**
  19526. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19527. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19528. */
  19529. _this.renderOverlay = false;
  19530. /** Defines color to use when rendering overlay */
  19531. _this.overlayColor = BABYLON.Color3.Red();
  19532. /** Defines alpha to use when rendering overlay */
  19533. _this.overlayAlpha = 0.5;
  19534. _this._hasVertexAlpha = false;
  19535. _this._useVertexColors = true;
  19536. _this._computeBonesUsingShaders = true;
  19537. _this._numBoneInfluencers = 4;
  19538. _this._applyFog = true;
  19539. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19540. _this.useOctreeForRenderingSelection = true;
  19541. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19542. _this.useOctreeForPicking = true;
  19543. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19544. _this.useOctreeForCollisions = true;
  19545. _this._layerMask = 0x0FFFFFFF;
  19546. /**
  19547. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19548. */
  19549. _this.alwaysSelectAsActiveMesh = false;
  19550. /**
  19551. * Gets or sets the current action manager
  19552. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19553. */
  19554. _this.actionManager = null;
  19555. /**
  19556. * Gets or sets impostor used for physic simulation
  19557. * @see http://doc.babylonjs.com/features/physics_engine
  19558. */
  19559. _this.physicsImpostor = null;
  19560. // Collisions
  19561. _this._checkCollisions = false;
  19562. _this._collisionMask = -1;
  19563. _this._collisionGroup = -1;
  19564. /**
  19565. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19566. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19567. */
  19568. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19569. /**
  19570. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19571. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19572. */
  19573. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19574. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19575. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19576. // Edges
  19577. /**
  19578. * Defines edge width used when edgesRenderer is enabled
  19579. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19580. */
  19581. _this.edgesWidth = 1;
  19582. /**
  19583. * Defines edge color used when edgesRenderer is enabled
  19584. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19585. */
  19586. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19587. // Cache
  19588. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19589. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19590. /** @hidden */
  19591. _this._renderId = 0;
  19592. /** @hidden */
  19593. _this._intersectionsInProgress = new Array();
  19594. /** @hidden */
  19595. _this._unIndexed = false;
  19596. /** @hidden */
  19597. _this._lightSources = new Array();
  19598. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19599. if (collidedMesh === void 0) { collidedMesh = null; }
  19600. //TODO move this to the collision coordinator!
  19601. if (_this.getScene().workerCollisions)
  19602. newPosition.multiplyInPlace(_this._collider._radius);
  19603. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19604. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19605. _this.position.addInPlace(_this._diffPositionForCollisions);
  19606. }
  19607. if (collidedMesh) {
  19608. _this.onCollideObservable.notifyObservers(collidedMesh);
  19609. }
  19610. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19611. };
  19612. _this.getScene().addMesh(_this);
  19613. _this._resyncLightSources();
  19614. return _this;
  19615. }
  19616. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19617. /**
  19618. * No billboard
  19619. */
  19620. get: function () {
  19621. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19622. },
  19623. enumerable: true,
  19624. configurable: true
  19625. });
  19626. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19627. /** Billboard on X axis */
  19628. get: function () {
  19629. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19630. },
  19631. enumerable: true,
  19632. configurable: true
  19633. });
  19634. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19635. /** Billboard on Y axis */
  19636. get: function () {
  19637. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19638. },
  19639. enumerable: true,
  19640. configurable: true
  19641. });
  19642. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19643. /** Billboard on Z axis */
  19644. get: function () {
  19645. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19646. },
  19647. enumerable: true,
  19648. configurable: true
  19649. });
  19650. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19651. /** Billboard on all axes */
  19652. get: function () {
  19653. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19654. },
  19655. enumerable: true,
  19656. configurable: true
  19657. });
  19658. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19659. /**
  19660. * Gets the number of facets in the mesh
  19661. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19662. */
  19663. get: function () {
  19664. return this._facetNb;
  19665. },
  19666. enumerable: true,
  19667. configurable: true
  19668. });
  19669. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19670. /**
  19671. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19672. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19673. */
  19674. get: function () {
  19675. return this._partitioningSubdivisions;
  19676. },
  19677. set: function (nb) {
  19678. this._partitioningSubdivisions = nb;
  19679. },
  19680. enumerable: true,
  19681. configurable: true
  19682. });
  19683. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19684. /**
  19685. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19686. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19687. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19688. */
  19689. get: function () {
  19690. return this._partitioningBBoxRatio;
  19691. },
  19692. set: function (ratio) {
  19693. this._partitioningBBoxRatio = ratio;
  19694. },
  19695. enumerable: true,
  19696. configurable: true
  19697. });
  19698. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19699. /**
  19700. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19701. * Works only for updatable meshes.
  19702. * Doesn't work with multi-materials
  19703. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19704. */
  19705. get: function () {
  19706. return this._facetDepthSort;
  19707. },
  19708. set: function (sort) {
  19709. this._facetDepthSort = sort;
  19710. },
  19711. enumerable: true,
  19712. configurable: true
  19713. });
  19714. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19715. /**
  19716. * The location (Vector3) where the facet depth sort must be computed from.
  19717. * By default, the active camera position.
  19718. * Used only when facet depth sort is enabled
  19719. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19720. */
  19721. get: function () {
  19722. return this._facetDepthSortFrom;
  19723. },
  19724. set: function (location) {
  19725. this._facetDepthSortFrom = location;
  19726. },
  19727. enumerable: true,
  19728. configurable: true
  19729. });
  19730. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19731. /**
  19732. * gets a boolean indicating if facetData is enabled
  19733. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19734. */
  19735. get: function () {
  19736. return this._facetDataEnabled;
  19737. },
  19738. enumerable: true,
  19739. configurable: true
  19740. });
  19741. /** @hidden */
  19742. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19743. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19744. return false;
  19745. }
  19746. this._markSubMeshesAsMiscDirty();
  19747. return true;
  19748. };
  19749. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19750. /** Set a function to call when this mesh collides with another one */
  19751. set: function (callback) {
  19752. if (this._onCollideObserver) {
  19753. this.onCollideObservable.remove(this._onCollideObserver);
  19754. }
  19755. this._onCollideObserver = this.onCollideObservable.add(callback);
  19756. },
  19757. enumerable: true,
  19758. configurable: true
  19759. });
  19760. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19761. /** Set a function to call when the collision's position changes */
  19762. set: function (callback) {
  19763. if (this._onCollisionPositionChangeObserver) {
  19764. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19765. }
  19766. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19767. },
  19768. enumerable: true,
  19769. configurable: true
  19770. });
  19771. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19772. /**
  19773. * Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not
  19774. * @see http://doc.babylonjs.com/features/occlusionquery
  19775. */
  19776. get: function () {
  19777. return this._isOccluded;
  19778. },
  19779. set: function (value) {
  19780. this._isOccluded = value;
  19781. },
  19782. enumerable: true,
  19783. configurable: true
  19784. });
  19785. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19786. /**
  19787. * Flag to check the progress status of the query
  19788. * @see http://doc.babylonjs.com/features/occlusionquery
  19789. */
  19790. get: function () {
  19791. return this._isOcclusionQueryInProgress;
  19792. },
  19793. enumerable: true,
  19794. configurable: true
  19795. });
  19796. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19797. /**
  19798. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19799. */
  19800. get: function () {
  19801. return this._visibility;
  19802. },
  19803. /**
  19804. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19805. */
  19806. set: function (value) {
  19807. if (this._visibility === value) {
  19808. return;
  19809. }
  19810. this._visibility = value;
  19811. this._markSubMeshesAsMiscDirty();
  19812. },
  19813. enumerable: true,
  19814. configurable: true
  19815. });
  19816. Object.defineProperty(AbstractMesh.prototype, "material", {
  19817. /** Gets or sets current material */
  19818. get: function () {
  19819. return this._material;
  19820. },
  19821. set: function (value) {
  19822. if (this._material === value) {
  19823. return;
  19824. }
  19825. this._material = value;
  19826. if (this.onMaterialChangedObservable.hasObservers) {
  19827. this.onMaterialChangedObservable.notifyObservers(this);
  19828. }
  19829. if (!this.subMeshes) {
  19830. return;
  19831. }
  19832. this._unBindEffect();
  19833. },
  19834. enumerable: true,
  19835. configurable: true
  19836. });
  19837. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19838. /**
  19839. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19840. * @see http://doc.babylonjs.com/babylon101/shadows
  19841. */
  19842. get: function () {
  19843. return this._receiveShadows;
  19844. },
  19845. set: function (value) {
  19846. if (this._receiveShadows === value) {
  19847. return;
  19848. }
  19849. this._receiveShadows = value;
  19850. this._markSubMeshesAsLightDirty();
  19851. },
  19852. enumerable: true,
  19853. configurable: true
  19854. });
  19855. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19856. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19857. get: function () {
  19858. return this._hasVertexAlpha;
  19859. },
  19860. set: function (value) {
  19861. if (this._hasVertexAlpha === value) {
  19862. return;
  19863. }
  19864. this._hasVertexAlpha = value;
  19865. this._markSubMeshesAsAttributesDirty();
  19866. this._markSubMeshesAsMiscDirty();
  19867. },
  19868. enumerable: true,
  19869. configurable: true
  19870. });
  19871. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19872. /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */
  19873. get: function () {
  19874. return this._useVertexColors;
  19875. },
  19876. set: function (value) {
  19877. if (this._useVertexColors === value) {
  19878. return;
  19879. }
  19880. this._useVertexColors = value;
  19881. this._markSubMeshesAsAttributesDirty();
  19882. },
  19883. enumerable: true,
  19884. configurable: true
  19885. });
  19886. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19887. /**
  19888. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19889. */
  19890. get: function () {
  19891. return this._computeBonesUsingShaders;
  19892. },
  19893. set: function (value) {
  19894. if (this._computeBonesUsingShaders === value) {
  19895. return;
  19896. }
  19897. this._computeBonesUsingShaders = value;
  19898. this._markSubMeshesAsAttributesDirty();
  19899. },
  19900. enumerable: true,
  19901. configurable: true
  19902. });
  19903. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19904. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19905. get: function () {
  19906. return this._numBoneInfluencers;
  19907. },
  19908. set: function (value) {
  19909. if (this._numBoneInfluencers === value) {
  19910. return;
  19911. }
  19912. this._numBoneInfluencers = value;
  19913. this._markSubMeshesAsAttributesDirty();
  19914. },
  19915. enumerable: true,
  19916. configurable: true
  19917. });
  19918. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19919. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19920. get: function () {
  19921. return this._applyFog;
  19922. },
  19923. set: function (value) {
  19924. if (this._applyFog === value) {
  19925. return;
  19926. }
  19927. this._applyFog = value;
  19928. this._markSubMeshesAsMiscDirty();
  19929. },
  19930. enumerable: true,
  19931. configurable: true
  19932. });
  19933. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19934. /**
  19935. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19936. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19937. */
  19938. get: function () {
  19939. return this._layerMask;
  19940. },
  19941. set: function (value) {
  19942. if (value === this._layerMask) {
  19943. return;
  19944. }
  19945. this._layerMask = value;
  19946. this._resyncLightSources();
  19947. },
  19948. enumerable: true,
  19949. configurable: true
  19950. });
  19951. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19952. /**
  19953. * Gets or sets a collision mask used to mask collisions (default is -1).
  19954. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19955. */
  19956. get: function () {
  19957. return this._collisionMask;
  19958. },
  19959. set: function (mask) {
  19960. this._collisionMask = !isNaN(mask) ? mask : -1;
  19961. },
  19962. enumerable: true,
  19963. configurable: true
  19964. });
  19965. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19966. /**
  19967. * Gets or sets the current collision group mask (-1 by default).
  19968. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19969. */
  19970. get: function () {
  19971. return this._collisionGroup;
  19972. },
  19973. set: function (mask) {
  19974. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19975. },
  19976. enumerable: true,
  19977. configurable: true
  19978. });
  19979. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19980. /** @hidden */
  19981. get: function () {
  19982. return null;
  19983. },
  19984. enumerable: true,
  19985. configurable: true
  19986. });
  19987. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19988. get: function () {
  19989. return this._skeleton;
  19990. },
  19991. /**
  19992. * Gets or sets a skeleton to apply skining transformations
  19993. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19994. */
  19995. set: function (value) {
  19996. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19997. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19998. }
  19999. if (value && value.needInitialSkinMatrix) {
  20000. value._registerMeshWithPoseMatrix(this);
  20001. }
  20002. this._skeleton = value;
  20003. if (!this._skeleton) {
  20004. this._bonesTransformMatrices = null;
  20005. }
  20006. this._markSubMeshesAsAttributesDirty();
  20007. },
  20008. enumerable: true,
  20009. configurable: true
  20010. });
  20011. /**
  20012. * Returns the string "AbstractMesh"
  20013. * @returns "AbstractMesh"
  20014. */
  20015. AbstractMesh.prototype.getClassName = function () {
  20016. return "AbstractMesh";
  20017. };
  20018. /**
  20019. * Gets a string representation of the current mesh
  20020. * @param fullDetails defines a boolean indicating if full details must be included
  20021. * @returns a string representation of the current mesh
  20022. */
  20023. AbstractMesh.prototype.toString = function (fullDetails) {
  20024. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20025. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20026. if (this._skeleton) {
  20027. ret += ", skeleton: " + this._skeleton.name;
  20028. }
  20029. if (fullDetails) {
  20030. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20031. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20032. }
  20033. return ret;
  20034. };
  20035. /** @hidden */
  20036. AbstractMesh.prototype._rebuild = function () {
  20037. if (this._occlusionQuery) {
  20038. this._occlusionQuery = null;
  20039. }
  20040. if (this._edgesRenderer) {
  20041. this._edgesRenderer._rebuild();
  20042. }
  20043. if (!this.subMeshes) {
  20044. return;
  20045. }
  20046. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20047. var subMesh = _a[_i];
  20048. subMesh._rebuild();
  20049. }
  20050. };
  20051. /** @hidden */
  20052. AbstractMesh.prototype._resyncLightSources = function () {
  20053. this._lightSources.length = 0;
  20054. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20055. var light = _a[_i];
  20056. if (!light.isEnabled()) {
  20057. continue;
  20058. }
  20059. if (light.canAffectMesh(this)) {
  20060. this._lightSources.push(light);
  20061. }
  20062. }
  20063. this._markSubMeshesAsLightDirty();
  20064. };
  20065. /** @hidden */
  20066. AbstractMesh.prototype._resyncLighSource = function (light) {
  20067. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20068. var index = this._lightSources.indexOf(light);
  20069. if (index === -1) {
  20070. if (!isIn) {
  20071. return;
  20072. }
  20073. this._lightSources.push(light);
  20074. }
  20075. else {
  20076. if (isIn) {
  20077. return;
  20078. }
  20079. this._lightSources.splice(index, 1);
  20080. }
  20081. this._markSubMeshesAsLightDirty();
  20082. };
  20083. /** @hidden */
  20084. AbstractMesh.prototype._unBindEffect = function () {
  20085. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20086. var subMesh = _a[_i];
  20087. subMesh.setEffect(null);
  20088. }
  20089. };
  20090. /** @hidden */
  20091. AbstractMesh.prototype._removeLightSource = function (light) {
  20092. var index = this._lightSources.indexOf(light);
  20093. if (index === -1) {
  20094. return;
  20095. }
  20096. this._lightSources.splice(index, 1);
  20097. this._markSubMeshesAsLightDirty();
  20098. };
  20099. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20100. if (!this.subMeshes) {
  20101. return;
  20102. }
  20103. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20104. var subMesh = _a[_i];
  20105. if (subMesh._materialDefines) {
  20106. func(subMesh._materialDefines);
  20107. }
  20108. }
  20109. };
  20110. /** @hidden */
  20111. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20112. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20113. };
  20114. /** @hidden */
  20115. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20116. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20117. };
  20118. /** @hidden */
  20119. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20120. if (!this.subMeshes) {
  20121. return;
  20122. }
  20123. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20124. var subMesh = _a[_i];
  20125. var material = subMesh.getMaterial();
  20126. if (material) {
  20127. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20128. }
  20129. }
  20130. };
  20131. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20132. /**
  20133. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20134. */
  20135. get: function () {
  20136. return this._scaling;
  20137. },
  20138. set: function (newScaling) {
  20139. this._scaling = newScaling;
  20140. if (this.physicsImpostor) {
  20141. this.physicsImpostor.forceUpdate();
  20142. }
  20143. },
  20144. enumerable: true,
  20145. configurable: true
  20146. });
  20147. // Methods
  20148. /**
  20149. * Disables the mesh edge rendering mode
  20150. * @returns the currentAbstractMesh
  20151. */
  20152. AbstractMesh.prototype.disableEdgesRendering = function () {
  20153. if (this._edgesRenderer) {
  20154. this._edgesRenderer.dispose();
  20155. this._edgesRenderer = null;
  20156. }
  20157. return this;
  20158. };
  20159. /**
  20160. * Enables the edge rendering mode on the mesh.
  20161. * This mode makes the mesh edges visible
  20162. * @param epsilon defines the maximal distance between two angles to detect a face
  20163. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20164. * @returns the currentAbstractMesh
  20165. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20166. */
  20167. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20168. if (epsilon === void 0) { epsilon = 0.95; }
  20169. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20170. this.disableEdgesRendering();
  20171. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20172. return this;
  20173. };
  20174. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20175. /**
  20176. * Gets the edgesRenderer associated with the mesh
  20177. */
  20178. get: function () {
  20179. return this._edgesRenderer;
  20180. },
  20181. enumerable: true,
  20182. configurable: true
  20183. });
  20184. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20185. /**
  20186. * Returns true if the mesh is blocked. Implemented by child classes
  20187. */
  20188. get: function () {
  20189. return false;
  20190. },
  20191. enumerable: true,
  20192. configurable: true
  20193. });
  20194. /**
  20195. * Returns the mesh itself by default. Implemented by child classes
  20196. * @param camera defines the camera to use to pick the right LOD level
  20197. * @returns the currentAbstractMesh
  20198. */
  20199. AbstractMesh.prototype.getLOD = function (camera) {
  20200. return this;
  20201. };
  20202. /**
  20203. * Returns 0 by default. Implemented by child classes
  20204. * @returns an integer
  20205. */
  20206. AbstractMesh.prototype.getTotalVertices = function () {
  20207. return 0;
  20208. };
  20209. /**
  20210. * Returns null by default. Implemented by child classes
  20211. * @returns null
  20212. */
  20213. AbstractMesh.prototype.getIndices = function () {
  20214. return null;
  20215. };
  20216. /**
  20217. * Returns the array of the requested vertex data kind. Implemented by child classes
  20218. * @param kind defines the vertex data kind to use
  20219. * @returns null
  20220. */
  20221. AbstractMesh.prototype.getVerticesData = function (kind) {
  20222. return null;
  20223. };
  20224. /**
  20225. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20226. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20227. * Note that a new underlying VertexBuffer object is created each call.
  20228. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20229. * @param kind defines vertex data kind:
  20230. * * BABYLON.VertexBuffer.PositionKind
  20231. * * BABYLON.VertexBuffer.UVKind
  20232. * * BABYLON.VertexBuffer.UV2Kind
  20233. * * BABYLON.VertexBuffer.UV3Kind
  20234. * * BABYLON.VertexBuffer.UV4Kind
  20235. * * BABYLON.VertexBuffer.UV5Kind
  20236. * * BABYLON.VertexBuffer.UV6Kind
  20237. * * BABYLON.VertexBuffer.ColorKind
  20238. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20239. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20240. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20241. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20242. * @param data defines the data source
  20243. * @param updatable defines if the data must be flagged as updatable (or static)
  20244. * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind
  20245. * @returns the current mesh
  20246. */
  20247. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20248. return this;
  20249. };
  20250. /**
  20251. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20252. * If the mesh has no geometry, it is simply returned as it is.
  20253. * @param kind defines vertex data kind:
  20254. * * BABYLON.VertexBuffer.PositionKind
  20255. * * BABYLON.VertexBuffer.UVKind
  20256. * * BABYLON.VertexBuffer.UV2Kind
  20257. * * BABYLON.VertexBuffer.UV3Kind
  20258. * * BABYLON.VertexBuffer.UV4Kind
  20259. * * BABYLON.VertexBuffer.UV5Kind
  20260. * * BABYLON.VertexBuffer.UV6Kind
  20261. * * BABYLON.VertexBuffer.ColorKind
  20262. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20263. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20264. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20265. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20266. * @param data defines the data source
  20267. * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed
  20268. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20269. * @returns the current mesh
  20270. */
  20271. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20272. return this;
  20273. };
  20274. /**
  20275. * Sets the mesh indices,
  20276. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20277. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20278. * @param totalVertices Defines the total number of vertices
  20279. * @returns the current mesh
  20280. */
  20281. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20282. return this;
  20283. };
  20284. /**
  20285. * Gets a boolean indicating if specific vertex data is present
  20286. * @param kind defines the vertex data kind to use
  20287. * @returns true is data kind is present
  20288. */
  20289. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20290. return false;
  20291. };
  20292. /**
  20293. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20294. * @returns a BoundingInfo
  20295. */
  20296. AbstractMesh.prototype.getBoundingInfo = function () {
  20297. if (this._masterMesh) {
  20298. return this._masterMesh.getBoundingInfo();
  20299. }
  20300. if (!this._boundingInfo) {
  20301. // this._boundingInfo is being created here
  20302. this._updateBoundingInfo();
  20303. }
  20304. // cannot be null.
  20305. return this._boundingInfo;
  20306. };
  20307. /**
  20308. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20309. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20310. * @returns the current mesh
  20311. */
  20312. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20313. if (includeDescendants === void 0) { includeDescendants = true; }
  20314. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20315. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20316. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20317. if (maxDimension === 0) {
  20318. return this;
  20319. }
  20320. var scale = 1 / maxDimension;
  20321. this.scaling.scaleInPlace(scale);
  20322. return this;
  20323. };
  20324. /**
  20325. * Overwrite the current bounding info
  20326. * @param boundingInfo defines the new bounding info
  20327. * @returns the current mesh
  20328. */
  20329. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20330. this._boundingInfo = boundingInfo;
  20331. return this;
  20332. };
  20333. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20334. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20335. get: function () {
  20336. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20337. },
  20338. enumerable: true,
  20339. configurable: true
  20340. });
  20341. /** @hidden */
  20342. AbstractMesh.prototype._preActivate = function () {
  20343. };
  20344. /** @hidden */
  20345. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20346. };
  20347. /** @hidden */
  20348. AbstractMesh.prototype._activate = function (renderId) {
  20349. this._renderId = renderId;
  20350. };
  20351. /**
  20352. * Gets the current world matrix
  20353. * @returns a Matrix
  20354. */
  20355. AbstractMesh.prototype.getWorldMatrix = function () {
  20356. if (this._masterMesh) {
  20357. return this._masterMesh.getWorldMatrix();
  20358. }
  20359. return _super.prototype.getWorldMatrix.call(this);
  20360. };
  20361. /** @hidden */
  20362. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20363. if (this._masterMesh) {
  20364. return this._masterMesh._getWorldMatrixDeterminant();
  20365. }
  20366. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20367. };
  20368. // ================================== Point of View Movement =================================
  20369. /**
  20370. * Perform relative position change from the point of view of behind the front of the mesh.
  20371. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20372. * Supports definition of mesh facing forward or backward
  20373. * @param amountRight defines the distance on the right axis
  20374. * @param amountUp defines the distance on the up axis
  20375. * @param amountForward defines the distance on the forward axis
  20376. * @returns the current mesh
  20377. */
  20378. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20379. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20380. return this;
  20381. };
  20382. /**
  20383. * Calculate relative position change from the point of view of behind the front of the mesh.
  20384. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20385. * Supports definition of mesh facing forward or backward
  20386. * @param amountRight defines the distance on the right axis
  20387. * @param amountUp defines the distance on the up axis
  20388. * @param amountForward defines the distance on the forward axis
  20389. * @returns the new displacement vector
  20390. */
  20391. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20392. var rotMatrix = new BABYLON.Matrix();
  20393. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20394. rotQuaternion.toRotationMatrix(rotMatrix);
  20395. var translationDelta = BABYLON.Vector3.Zero();
  20396. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20397. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20398. return translationDelta;
  20399. };
  20400. // ================================== Point of View Rotation =================================
  20401. /**
  20402. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20403. * Supports definition of mesh facing forward or backward
  20404. * @param flipBack defines the flip
  20405. * @param twirlClockwise defines the twirl
  20406. * @param tiltRight defines the tilt
  20407. * @returns the current mesh
  20408. */
  20409. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20410. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20411. return this;
  20412. };
  20413. /**
  20414. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20415. * Supports definition of mesh facing forward or backward.
  20416. * @param flipBack defines the flip
  20417. * @param twirlClockwise defines the twirl
  20418. * @param tiltRight defines the tilt
  20419. * @returns the new rotation vector
  20420. */
  20421. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20422. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20423. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20424. };
  20425. /**
  20426. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20427. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20428. * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors
  20429. * @returns the new bounding vectors
  20430. */
  20431. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20432. if (includeDescendants === void 0) { includeDescendants = true; }
  20433. if (predicate === void 0) { predicate = null; }
  20434. // Ensures that all world matrix will be recomputed.
  20435. this.getScene().incrementRenderId();
  20436. this.computeWorldMatrix(true);
  20437. var min;
  20438. var max;
  20439. var boundingInfo = this.getBoundingInfo();
  20440. if (!this.subMeshes) {
  20441. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20442. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20443. }
  20444. else {
  20445. min = boundingInfo.boundingBox.minimumWorld;
  20446. max = boundingInfo.boundingBox.maximumWorld;
  20447. }
  20448. if (includeDescendants) {
  20449. var descendants = this.getDescendants(false);
  20450. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20451. var descendant = descendants_1[_i];
  20452. var childMesh = descendant;
  20453. childMesh.computeWorldMatrix(true);
  20454. // Filters meshes based on custom predicate function.
  20455. if (predicate && !predicate(childMesh)) {
  20456. continue;
  20457. }
  20458. //make sure we have the needed params to get mix and max
  20459. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20460. continue;
  20461. }
  20462. var childBoundingInfo = childMesh.getBoundingInfo();
  20463. var boundingBox = childBoundingInfo.boundingBox;
  20464. var minBox = boundingBox.minimumWorld;
  20465. var maxBox = boundingBox.maximumWorld;
  20466. BABYLON.Tools.CheckExtends(minBox, min, max);
  20467. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20468. }
  20469. }
  20470. return {
  20471. min: min,
  20472. max: max
  20473. };
  20474. };
  20475. /** @hidden */
  20476. AbstractMesh.prototype._updateBoundingInfo = function () {
  20477. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20478. this._boundingInfo.update(this.worldMatrixFromCache);
  20479. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20480. return this;
  20481. };
  20482. /** @hidden */
  20483. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20484. if (!this.subMeshes) {
  20485. return this;
  20486. }
  20487. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20488. var subMesh = this.subMeshes[subIndex];
  20489. if (!subMesh.IsGlobal) {
  20490. subMesh.updateBoundingInfo(matrix);
  20491. }
  20492. }
  20493. return this;
  20494. };
  20495. /** @hidden */
  20496. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20497. // Bounding info
  20498. this._updateBoundingInfo();
  20499. };
  20500. /**
  20501. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20502. * A mesh is in the frustum if its bounding box intersects the frustum
  20503. * @param frustumPlanes defines the frustum to test
  20504. * @returns true if the mesh is in the frustum planes
  20505. */
  20506. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20507. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20508. };
  20509. /**
  20510. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20511. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20512. * @param frustumPlanes defines the frustum to test
  20513. * @returns true if the mesh is completely in the frustum planes
  20514. */
  20515. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20516. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20517. };
  20518. /**
  20519. * True if the mesh intersects another mesh or a SolidParticle object
  20520. * @param mesh defines a target mesh or SolidParticle to test
  20521. * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  20522. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20523. * @returns true if there is an intersection
  20524. */
  20525. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20526. if (precise === void 0) { precise = false; }
  20527. if (!this._boundingInfo || !mesh._boundingInfo) {
  20528. return false;
  20529. }
  20530. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20531. return true;
  20532. }
  20533. if (includeDescendants) {
  20534. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20535. var child = _a[_i];
  20536. if (child.intersectsMesh(mesh, precise, true)) {
  20537. return true;
  20538. }
  20539. }
  20540. }
  20541. return false;
  20542. };
  20543. /**
  20544. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20545. * @param point defines the point to test
  20546. * @returns true if there is an intersection
  20547. */
  20548. AbstractMesh.prototype.intersectsPoint = function (point) {
  20549. if (!this._boundingInfo) {
  20550. return false;
  20551. }
  20552. return this._boundingInfo.intersectsPoint(point);
  20553. };
  20554. /**
  20555. * Gets the current physics impostor
  20556. * @see http://doc.babylonjs.com/features/physics_engine
  20557. * @returns a physics impostor or null
  20558. */
  20559. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20560. return this.physicsImpostor;
  20561. };
  20562. /**
  20563. * Gets the position of the current mesh in camera space
  20564. * @param camera defines the camera to use
  20565. * @returns a position
  20566. */
  20567. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20568. if (camera === void 0) { camera = null; }
  20569. if (!camera) {
  20570. camera = this.getScene().activeCamera;
  20571. }
  20572. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20573. };
  20574. /**
  20575. * Returns the distance from the mesh to the active camera
  20576. * @param camera defines the camera to use
  20577. * @returns the distance
  20578. */
  20579. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20580. if (camera === void 0) { camera = null; }
  20581. if (!camera) {
  20582. camera = this.getScene().activeCamera;
  20583. }
  20584. return this.absolutePosition.subtract(camera.position).length();
  20585. };
  20586. /**
  20587. * Apply a physic impulse to the mesh
  20588. * @param force defines the force to apply
  20589. * @param contactPoint defines where to apply the force
  20590. * @returns the current mesh
  20591. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20592. */
  20593. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20594. if (!this.physicsImpostor) {
  20595. return this;
  20596. }
  20597. this.physicsImpostor.applyImpulse(force, contactPoint);
  20598. return this;
  20599. };
  20600. /**
  20601. * Creates a physic joint between two meshes
  20602. * @param otherMesh defines the other mesh to use
  20603. * @param pivot1 defines the pivot to use on this mesh
  20604. * @param pivot2 defines the pivot to use on the other mesh
  20605. * @param options defines additional options (can be plugin dependent)
  20606. * @returns the current mesh
  20607. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20608. */
  20609. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20610. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20611. return this;
  20612. }
  20613. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20614. mainPivot: pivot1,
  20615. connectedPivot: pivot2,
  20616. nativeParams: options
  20617. });
  20618. return this;
  20619. };
  20620. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20621. // Collisions
  20622. /**
  20623. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20624. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20625. */
  20626. get: function () {
  20627. return this._checkCollisions;
  20628. },
  20629. set: function (collisionEnabled) {
  20630. this._checkCollisions = collisionEnabled;
  20631. if (this.getScene().workerCollisions) {
  20632. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20633. }
  20634. },
  20635. enumerable: true,
  20636. configurable: true
  20637. });
  20638. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20639. /**
  20640. * Gets Collider object used to compute collisions (not physics)
  20641. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20642. */
  20643. get: function () {
  20644. return this._collider;
  20645. },
  20646. enumerable: true,
  20647. configurable: true
  20648. });
  20649. /**
  20650. * Move the mesh using collision engine
  20651. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20652. * @param displacement defines the requested displacement vector
  20653. * @returns the current mesh
  20654. */
  20655. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20656. var globalPosition = this.getAbsolutePosition();
  20657. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20658. if (!this._collider) {
  20659. this._collider = new BABYLON.Collider();
  20660. }
  20661. this._collider._radius = this.ellipsoid;
  20662. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20663. return this;
  20664. };
  20665. // Submeshes octree
  20666. /**
  20667. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20668. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20669. * @param maxCapacity defines the maximum size of each block (64 by default)
  20670. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20671. * @returns the new octree
  20672. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20673. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20674. */
  20675. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20676. if (maxCapacity === void 0) { maxCapacity = 64; }
  20677. if (maxDepth === void 0) { maxDepth = 2; }
  20678. if (!this._submeshesOctree) {
  20679. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20680. }
  20681. this.computeWorldMatrix(true);
  20682. var boundingInfo = this.getBoundingInfo();
  20683. // Update octree
  20684. var bbox = boundingInfo.boundingBox;
  20685. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20686. return this._submeshesOctree;
  20687. };
  20688. // Collisions
  20689. /** @hidden */
  20690. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20691. this._generatePointsArray();
  20692. if (!this._positions) {
  20693. return this;
  20694. }
  20695. // Transformation
  20696. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20697. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20698. subMesh._lastColliderWorldVertices = [];
  20699. subMesh._trianglePlanes = [];
  20700. var start = subMesh.verticesStart;
  20701. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20702. for (var i = start; i < end; i++) {
  20703. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20704. }
  20705. }
  20706. // Collide
  20707. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20708. if (collider.collisionFound) {
  20709. collider.collidedMesh = this;
  20710. }
  20711. return this;
  20712. };
  20713. /** @hidden */
  20714. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20715. var subMeshes;
  20716. var len;
  20717. // Octrees
  20718. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20719. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20720. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20721. len = intersections.length;
  20722. subMeshes = intersections.data;
  20723. }
  20724. else {
  20725. subMeshes = this.subMeshes;
  20726. len = subMeshes.length;
  20727. }
  20728. for (var index = 0; index < len; index++) {
  20729. var subMesh = subMeshes[index];
  20730. // Bounding test
  20731. if (len > 1 && !subMesh._checkCollision(collider))
  20732. continue;
  20733. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20734. }
  20735. return this;
  20736. };
  20737. /** @hidden */
  20738. AbstractMesh.prototype._checkCollision = function (collider) {
  20739. // Bounding box test
  20740. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20741. return this;
  20742. // Transformation matrix
  20743. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20744. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20745. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20746. return this;
  20747. };
  20748. // Picking
  20749. /** @hidden */
  20750. AbstractMesh.prototype._generatePointsArray = function () {
  20751. return false;
  20752. };
  20753. /**
  20754. * Checks if the passed Ray intersects with the mesh
  20755. * @param ray defines the ray to use
  20756. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20757. * @returns the picking info
  20758. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20759. */
  20760. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20761. var pickingInfo = new BABYLON.PickingInfo();
  20762. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20763. return pickingInfo;
  20764. }
  20765. if (!this._generatePointsArray()) {
  20766. return pickingInfo;
  20767. }
  20768. var intersectInfo = null;
  20769. // Octrees
  20770. var subMeshes;
  20771. var len;
  20772. if (this._submeshesOctree && this.useOctreeForPicking) {
  20773. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20774. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20775. len = intersections.length;
  20776. subMeshes = intersections.data;
  20777. }
  20778. else {
  20779. subMeshes = this.subMeshes;
  20780. len = subMeshes.length;
  20781. }
  20782. for (var index = 0; index < len; index++) {
  20783. var subMesh = subMeshes[index];
  20784. // Bounding test
  20785. if (len > 1 && !subMesh.canIntersects(ray))
  20786. continue;
  20787. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20788. if (currentIntersectInfo) {
  20789. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20790. intersectInfo = currentIntersectInfo;
  20791. intersectInfo.subMeshId = index;
  20792. if (fastCheck) {
  20793. break;
  20794. }
  20795. }
  20796. }
  20797. }
  20798. if (intersectInfo) {
  20799. // Get picked point
  20800. var world = this.getWorldMatrix();
  20801. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20802. var direction = ray.direction.clone();
  20803. direction = direction.scale(intersectInfo.distance);
  20804. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20805. var pickedPoint = worldOrigin.add(worldDirection);
  20806. // Return result
  20807. pickingInfo.hit = true;
  20808. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20809. pickingInfo.pickedPoint = pickedPoint;
  20810. pickingInfo.pickedMesh = this;
  20811. pickingInfo.bu = intersectInfo.bu || 0;
  20812. pickingInfo.bv = intersectInfo.bv || 0;
  20813. pickingInfo.faceId = intersectInfo.faceId;
  20814. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20815. return pickingInfo;
  20816. }
  20817. return pickingInfo;
  20818. };
  20819. /**
  20820. * Clones the current mesh
  20821. * @param name defines the mesh name
  20822. * @param newParent defines the new mesh parent
  20823. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20824. * @returns the new mesh
  20825. */
  20826. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20827. return null;
  20828. };
  20829. /**
  20830. * Disposes all the submeshes of the current meshnp
  20831. * @returns the current mesh
  20832. */
  20833. AbstractMesh.prototype.releaseSubMeshes = function () {
  20834. if (this.subMeshes) {
  20835. while (this.subMeshes.length) {
  20836. this.subMeshes[0].dispose();
  20837. }
  20838. }
  20839. else {
  20840. this.subMeshes = new Array();
  20841. }
  20842. return this;
  20843. };
  20844. /**
  20845. * Releases resources associated with this abstract mesh.
  20846. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20847. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20848. */
  20849. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20850. var _this = this;
  20851. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20852. var index;
  20853. // Smart Array Retainers.
  20854. this.getScene().freeActiveMeshes();
  20855. this.getScene().freeRenderingGroups();
  20856. // Action manager
  20857. if (this.actionManager !== undefined && this.actionManager !== null) {
  20858. this.actionManager.dispose();
  20859. this.actionManager = null;
  20860. }
  20861. // Skeleton
  20862. this._skeleton = null;
  20863. // Physics
  20864. if (this.physicsImpostor) {
  20865. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20866. }
  20867. // Intersections in progress
  20868. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20869. var other = this._intersectionsInProgress[index];
  20870. var pos = other._intersectionsInProgress.indexOf(this);
  20871. other._intersectionsInProgress.splice(pos, 1);
  20872. }
  20873. this._intersectionsInProgress = [];
  20874. // Lights
  20875. var lights = this.getScene().lights;
  20876. lights.forEach(function (light) {
  20877. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20878. if (meshIndex !== -1) {
  20879. light.includedOnlyMeshes.splice(meshIndex, 1);
  20880. }
  20881. meshIndex = light.excludedMeshes.indexOf(_this);
  20882. if (meshIndex !== -1) {
  20883. light.excludedMeshes.splice(meshIndex, 1);
  20884. }
  20885. // Shadow generators
  20886. var generator = light.getShadowGenerator();
  20887. if (generator) {
  20888. var shadowMap = generator.getShadowMap();
  20889. if (shadowMap && shadowMap.renderList) {
  20890. meshIndex = shadowMap.renderList.indexOf(_this);
  20891. if (meshIndex !== -1) {
  20892. shadowMap.renderList.splice(meshIndex, 1);
  20893. }
  20894. }
  20895. }
  20896. });
  20897. // Edges
  20898. if (this._edgesRenderer) {
  20899. this._edgesRenderer.dispose();
  20900. this._edgesRenderer = null;
  20901. }
  20902. // SubMeshes
  20903. if (this.getClassName() !== "InstancedMesh") {
  20904. this.releaseSubMeshes();
  20905. }
  20906. // Octree
  20907. var sceneOctree = this.getScene().selectionOctree;
  20908. if (sceneOctree !== undefined && sceneOctree !== null) {
  20909. var index = sceneOctree.dynamicContent.indexOf(this);
  20910. if (index !== -1) {
  20911. sceneOctree.dynamicContent.splice(index, 1);
  20912. }
  20913. }
  20914. // Query
  20915. var engine = this.getScene().getEngine();
  20916. if (this._occlusionQuery) {
  20917. this._isOcclusionQueryInProgress = false;
  20918. engine.deleteQuery(this._occlusionQuery);
  20919. this._occlusionQuery = null;
  20920. }
  20921. // Engine
  20922. engine.wipeCaches();
  20923. // Remove from scene
  20924. this.getScene().removeMesh(this);
  20925. if (disposeMaterialAndTextures) {
  20926. if (this.material) {
  20927. this.material.dispose(false, true);
  20928. }
  20929. }
  20930. if (!doNotRecurse) {
  20931. // Particles
  20932. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20933. if (this.getScene().particleSystems[index].emitter === this) {
  20934. this.getScene().particleSystems[index].dispose();
  20935. index--;
  20936. }
  20937. }
  20938. }
  20939. // facet data
  20940. if (this._facetDataEnabled) {
  20941. this.disableFacetData();
  20942. }
  20943. this.onAfterWorldMatrixUpdateObservable.clear();
  20944. this.onCollideObservable.clear();
  20945. this.onCollisionPositionChangeObservable.clear();
  20946. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20947. };
  20948. /**
  20949. * Adds the passed mesh as a child to the current mesh
  20950. * @param mesh defines the child mesh
  20951. * @returns the current mesh
  20952. */
  20953. AbstractMesh.prototype.addChild = function (mesh) {
  20954. mesh.setParent(this);
  20955. return this;
  20956. };
  20957. /**
  20958. * Removes the passed mesh from the current mesh children list
  20959. * @param mesh defines the child mesh
  20960. * @returns the current mesh
  20961. */
  20962. AbstractMesh.prototype.removeChild = function (mesh) {
  20963. mesh.setParent(null);
  20964. return this;
  20965. };
  20966. // Facet data
  20967. /** @hidden */
  20968. AbstractMesh.prototype._initFacetData = function () {
  20969. if (!this._facetNormals) {
  20970. this._facetNormals = new Array();
  20971. }
  20972. if (!this._facetPositions) {
  20973. this._facetPositions = new Array();
  20974. }
  20975. if (!this._facetPartitioning) {
  20976. this._facetPartitioning = new Array();
  20977. }
  20978. this._facetNb = (this.getIndices().length / 3) | 0;
  20979. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20980. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20981. for (var f = 0; f < this._facetNb; f++) {
  20982. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20983. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20984. }
  20985. this._facetDataEnabled = true;
  20986. return this;
  20987. };
  20988. /**
  20989. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20990. * This method can be called within the render loop.
  20991. * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation
  20992. * @returns the current mesh
  20993. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20994. */
  20995. AbstractMesh.prototype.updateFacetData = function () {
  20996. if (!this._facetDataEnabled) {
  20997. this._initFacetData();
  20998. }
  20999. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21000. var indices = this.getIndices();
  21001. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21002. var bInfo = this.getBoundingInfo();
  21003. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21004. // init arrays, matrix and sort function on first call
  21005. this._facetDepthSortEnabled = true;
  21006. if (indices instanceof Uint16Array) {
  21007. this._depthSortedIndices = new Uint16Array(indices);
  21008. }
  21009. else if (indices instanceof Uint32Array) {
  21010. this._depthSortedIndices = new Uint32Array(indices);
  21011. }
  21012. else {
  21013. var needs32bits = false;
  21014. for (var i = 0; i < indices.length; i++) {
  21015. if (indices[i] > 65535) {
  21016. needs32bits = true;
  21017. break;
  21018. }
  21019. }
  21020. if (needs32bits) {
  21021. this._depthSortedIndices = new Uint32Array(indices);
  21022. }
  21023. else {
  21024. this._depthSortedIndices = new Uint16Array(indices);
  21025. }
  21026. }
  21027. this._facetDepthSortFunction = function (f1, f2) {
  21028. return (f2.sqDistance - f1.sqDistance);
  21029. };
  21030. if (!this._facetDepthSortFrom) {
  21031. var camera = this.getScene().activeCamera;
  21032. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21033. }
  21034. this._depthSortedFacets = [];
  21035. for (var f = 0; f < this._facetNb; f++) {
  21036. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21037. this._depthSortedFacets.push(depthSortedFacet);
  21038. }
  21039. this._invertedMatrix = BABYLON.Matrix.Identity();
  21040. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21041. }
  21042. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21043. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21044. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21045. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21046. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21047. this._subDiv.max = this._partitioningSubdivisions;
  21048. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21049. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21050. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21051. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21052. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21053. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21054. // set the parameters for ComputeNormals()
  21055. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21056. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21057. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21058. this._facetParameters.bInfo = bInfo;
  21059. this._facetParameters.bbSize = this._bbSize;
  21060. this._facetParameters.subDiv = this._subDiv;
  21061. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21062. this._facetParameters.depthSort = this._facetDepthSort;
  21063. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21064. this.computeWorldMatrix(true);
  21065. this._worldMatrix.invertToRef(this._invertedMatrix);
  21066. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21067. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21068. }
  21069. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21070. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21071. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21072. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21073. var l = (this._depthSortedIndices.length / 3) | 0;
  21074. for (var f = 0; f < l; f++) {
  21075. var sind = this._depthSortedFacets[f].ind;
  21076. this._depthSortedIndices[f * 3] = indices[sind];
  21077. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21078. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21079. }
  21080. this.updateIndices(this._depthSortedIndices);
  21081. }
  21082. return this;
  21083. };
  21084. /**
  21085. * Returns the facetLocalNormals array.
  21086. * The normals are expressed in the mesh local spac
  21087. * @returns an array of Vector3
  21088. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21089. */
  21090. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21091. if (!this._facetNormals) {
  21092. this.updateFacetData();
  21093. }
  21094. return this._facetNormals;
  21095. };
  21096. /**
  21097. * Returns the facetLocalPositions array.
  21098. * The facet positions are expressed in the mesh local space
  21099. * @returns an array of Vector3
  21100. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21101. */
  21102. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21103. if (!this._facetPositions) {
  21104. this.updateFacetData();
  21105. }
  21106. return this._facetPositions;
  21107. };
  21108. /**
  21109. * Returns the facetLocalPartioning array
  21110. * @returns an array of array of numbers
  21111. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21112. */
  21113. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21114. if (!this._facetPartitioning) {
  21115. this.updateFacetData();
  21116. }
  21117. return this._facetPartitioning;
  21118. };
  21119. /**
  21120. * Returns the i-th facet position in the world system.
  21121. * This method allocates a new Vector3 per call
  21122. * @param i defines the facet index
  21123. * @returns a new Vector3
  21124. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21125. */
  21126. AbstractMesh.prototype.getFacetPosition = function (i) {
  21127. var pos = BABYLON.Vector3.Zero();
  21128. this.getFacetPositionToRef(i, pos);
  21129. return pos;
  21130. };
  21131. /**
  21132. * Sets the reference Vector3 with the i-th facet position in the world system
  21133. * @param i defines the facet index
  21134. * @param ref defines the target vector
  21135. * @returns the current mesh
  21136. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21137. */
  21138. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21139. var localPos = (this.getFacetLocalPositions())[i];
  21140. var world = this.getWorldMatrix();
  21141. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21142. return this;
  21143. };
  21144. /**
  21145. * Returns the i-th facet normal in the world system.
  21146. * This method allocates a new Vector3 per call
  21147. * @param i defines the facet index
  21148. * @returns a new Vector3
  21149. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21150. */
  21151. AbstractMesh.prototype.getFacetNormal = function (i) {
  21152. var norm = BABYLON.Vector3.Zero();
  21153. this.getFacetNormalToRef(i, norm);
  21154. return norm;
  21155. };
  21156. /**
  21157. * Sets the reference Vector3 with the i-th facet normal in the world system
  21158. * @param i defines the facet index
  21159. * @param ref defines the target vector
  21160. * @returns the current mesh
  21161. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21162. */
  21163. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21164. var localNorm = (this.getFacetLocalNormals())[i];
  21165. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21166. return this;
  21167. };
  21168. /**
  21169. * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system)
  21170. * @param x defines x coordinate
  21171. * @param y defines y coordinate
  21172. * @param z defines z coordinate
  21173. * @returns the array of facet indexes
  21174. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21175. */
  21176. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21177. var bInfo = this.getBoundingInfo();
  21178. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21179. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21180. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21181. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21182. return null;
  21183. }
  21184. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21185. };
  21186. /**
  21187. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21188. * @param projected sets as the (x,y,z) world projection on the facet
  21189. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  21190. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  21191. * @param x defines x coordinate
  21192. * @param y defines y coordinate
  21193. * @param z defines z coordinate
  21194. * @returns the face index if found (or null instead)
  21195. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21196. */
  21197. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21198. if (checkFace === void 0) { checkFace = false; }
  21199. if (facing === void 0) { facing = true; }
  21200. var world = this.getWorldMatrix();
  21201. var invMat = BABYLON.Tmp.Matrix[5];
  21202. world.invertToRef(invMat);
  21203. var invVect = BABYLON.Tmp.Vector3[8];
  21204. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21205. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21206. if (projected) {
  21207. // tranform the local computed projected vector to world coordinates
  21208. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21209. }
  21210. return closest;
  21211. };
  21212. /**
  21213. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21214. * @param projected sets as the (x,y,z) local projection on the facet
  21215. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  21216. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  21217. * @param x defines x coordinate
  21218. * @param y defines y coordinate
  21219. * @param z defines z coordinate
  21220. * @returns the face index if found (or null instead)
  21221. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21222. */
  21223. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21224. if (checkFace === void 0) { checkFace = false; }
  21225. if (facing === void 0) { facing = true; }
  21226. var closest = null;
  21227. var tmpx = 0.0;
  21228. var tmpy = 0.0;
  21229. var tmpz = 0.0;
  21230. var d = 0.0; // tmp dot facet normal * facet position
  21231. var t0 = 0.0;
  21232. var projx = 0.0;
  21233. var projy = 0.0;
  21234. var projz = 0.0;
  21235. // Get all the facets in the same partitioning block than (x, y, z)
  21236. var facetPositions = this.getFacetLocalPositions();
  21237. var facetNormals = this.getFacetLocalNormals();
  21238. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21239. if (!facetsInBlock) {
  21240. return null;
  21241. }
  21242. // Get the closest facet to (x, y, z)
  21243. var shortest = Number.MAX_VALUE; // init distance vars
  21244. var tmpDistance = shortest;
  21245. var fib; // current facet in the block
  21246. var norm; // current facet normal
  21247. var p0; // current facet barycenter position
  21248. // loop on all the facets in the current partitioning block
  21249. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21250. fib = facetsInBlock[idx];
  21251. norm = facetNormals[fib];
  21252. p0 = facetPositions[fib];
  21253. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21254. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21255. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21256. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21257. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21258. projx = x + norm.x * t0;
  21259. projy = y + norm.y * t0;
  21260. projz = z + norm.z * t0;
  21261. tmpx = projx - x;
  21262. tmpy = projy - y;
  21263. tmpz = projz - z;
  21264. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21265. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21266. shortest = tmpDistance;
  21267. closest = fib;
  21268. if (projected) {
  21269. projected.x = projx;
  21270. projected.y = projy;
  21271. projected.z = projz;
  21272. }
  21273. }
  21274. }
  21275. }
  21276. return closest;
  21277. };
  21278. /**
  21279. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21280. * @returns the parameters
  21281. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21282. */
  21283. AbstractMesh.prototype.getFacetDataParameters = function () {
  21284. return this._facetParameters;
  21285. };
  21286. /**
  21287. * Disables the feature FacetData and frees the related memory
  21288. * @returns the current mesh
  21289. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21290. */
  21291. AbstractMesh.prototype.disableFacetData = function () {
  21292. if (this._facetDataEnabled) {
  21293. this._facetDataEnabled = false;
  21294. this._facetPositions = new Array();
  21295. this._facetNormals = new Array();
  21296. this._facetPartitioning = new Array();
  21297. this._facetParameters = null;
  21298. this._depthSortedIndices = new Uint32Array(0);
  21299. }
  21300. return this;
  21301. };
  21302. /**
  21303. * Updates the AbstractMesh indices array
  21304. * @param indices defines the data source
  21305. * @returns the current mesh
  21306. */
  21307. AbstractMesh.prototype.updateIndices = function (indices) {
  21308. return this;
  21309. };
  21310. /**
  21311. * Creates new normals data for the mesh
  21312. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21313. * @returns the current mesh
  21314. */
  21315. AbstractMesh.prototype.createNormals = function (updatable) {
  21316. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21317. var indices = this.getIndices();
  21318. var normals;
  21319. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21320. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21321. }
  21322. else {
  21323. normals = [];
  21324. }
  21325. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21326. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21327. return this;
  21328. };
  21329. /**
  21330. * Align the mesh with a normal
  21331. * @param normal defines the normal to use
  21332. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21333. * @returns the current mesh
  21334. */
  21335. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21336. if (!upDirection) {
  21337. upDirection = BABYLON.Axis.Y;
  21338. }
  21339. var axisX = BABYLON.Tmp.Vector3[0];
  21340. var axisZ = BABYLON.Tmp.Vector3[1];
  21341. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21342. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21343. if (this.rotationQuaternion) {
  21344. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21345. }
  21346. else {
  21347. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21348. }
  21349. return this;
  21350. };
  21351. /** @hidden */
  21352. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21353. var engine = this.getEngine();
  21354. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21355. this._isOccluded = false;
  21356. return;
  21357. }
  21358. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21359. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21360. if (isOcclusionQueryAvailable) {
  21361. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21362. this._isOcclusionQueryInProgress = false;
  21363. this._occlusionInternalRetryCounter = 0;
  21364. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21365. }
  21366. else {
  21367. this._occlusionInternalRetryCounter++;
  21368. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21369. this._isOcclusionQueryInProgress = false;
  21370. this._occlusionInternalRetryCounter = 0;
  21371. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21372. // if strict continue the last state of the object.
  21373. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21374. }
  21375. else {
  21376. return;
  21377. }
  21378. }
  21379. }
  21380. var scene = this.getScene();
  21381. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21382. if (!this._occlusionQuery) {
  21383. this._occlusionQuery = engine.createQuery();
  21384. }
  21385. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21386. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21387. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21388. this._isOcclusionQueryInProgress = true;
  21389. };
  21390. /** No occlusion */
  21391. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21392. /** Occlusion set to optimisitic */
  21393. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21394. /** Occlusion set to strict */
  21395. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21396. /** Use an accurante occlusion algorithm */
  21397. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21398. /** Use a conservative occlusion algorithm */
  21399. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21400. return AbstractMesh;
  21401. }(BABYLON.TransformNode));
  21402. BABYLON.AbstractMesh = AbstractMesh;
  21403. })(BABYLON || (BABYLON = {}));
  21404. //# sourceMappingURL=babylon.abstractMesh.js.map
  21405. var BABYLON;
  21406. (function (BABYLON) {
  21407. /**
  21408. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21409. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21410. * All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased.
  21411. */
  21412. var Light = /** @class */ (function (_super) {
  21413. __extends(Light, _super);
  21414. /**
  21415. * Creates a Light object in the scene.
  21416. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21417. * @param name The firendly name of the light
  21418. * @param scene The scene the light belongs too
  21419. */
  21420. function Light(name, scene) {
  21421. var _this = _super.call(this, name, scene) || this;
  21422. /**
  21423. * Diffuse gives the basic color to an object.
  21424. */
  21425. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21426. /**
  21427. * Specular produces a highlight color on an object.
  21428. * Note: This is note affecting PBR materials.
  21429. */
  21430. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21431. /**
  21432. * Strength of the light.
  21433. * Note: By default it is define in the framework own unit.
  21434. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21435. */
  21436. _this.intensity = 1.0;
  21437. /**
  21438. * Defines how far from the source the light is impacting in scene units.
  21439. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21440. */
  21441. _this.range = Number.MAX_VALUE;
  21442. /**
  21443. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21444. * of light.
  21445. */
  21446. _this._photometricScale = 1.0;
  21447. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21448. _this._radius = 0.00001;
  21449. /**
  21450. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21451. * exceeding the number allowed of the materials.
  21452. */
  21453. _this.renderPriority = 0;
  21454. _this._shadowEnabled = true;
  21455. _this._excludeWithLayerMask = 0;
  21456. _this._includeOnlyWithLayerMask = 0;
  21457. _this._lightmapMode = 0;
  21458. /**
  21459. * @hidden Internal use only.
  21460. */
  21461. _this._excludedMeshesIds = new Array();
  21462. /**
  21463. * @hidden Internal use only.
  21464. */
  21465. _this._includedOnlyMeshesIds = new Array();
  21466. _this.getScene().addLight(_this);
  21467. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21468. _this._buildUniformLayout();
  21469. _this.includedOnlyMeshes = new Array();
  21470. _this.excludedMeshes = new Array();
  21471. _this._resyncMeshes();
  21472. return _this;
  21473. }
  21474. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21475. /**
  21476. * If every light affecting the material is in this lightmapMode,
  21477. * material.lightmapTexture adds or multiplies
  21478. * (depends on material.useLightmapAsShadowmap)
  21479. * after every other light calculations.
  21480. */
  21481. get: function () {
  21482. return Light._LIGHTMAP_DEFAULT;
  21483. },
  21484. enumerable: true,
  21485. configurable: true
  21486. });
  21487. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21488. /**
  21489. * material.lightmapTexture as only diffuse lighting from this light
  21490. * adds only specular lighting from this light
  21491. * adds dynamic shadows
  21492. */
  21493. get: function () {
  21494. return Light._LIGHTMAP_SPECULAR;
  21495. },
  21496. enumerable: true,
  21497. configurable: true
  21498. });
  21499. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21500. /**
  21501. * material.lightmapTexture as only lighting
  21502. * no light calculation from this light
  21503. * only adds dynamic shadows from this light
  21504. */
  21505. get: function () {
  21506. return Light._LIGHTMAP_SHADOWSONLY;
  21507. },
  21508. enumerable: true,
  21509. configurable: true
  21510. });
  21511. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21512. /**
  21513. * Each light type uses the default quantity according to its type:
  21514. * point/spot lights use luminous intensity
  21515. * directional lights use illuminance
  21516. */
  21517. get: function () {
  21518. return Light._INTENSITYMODE_AUTOMATIC;
  21519. },
  21520. enumerable: true,
  21521. configurable: true
  21522. });
  21523. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21524. /**
  21525. * lumen (lm)
  21526. */
  21527. get: function () {
  21528. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21529. },
  21530. enumerable: true,
  21531. configurable: true
  21532. });
  21533. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21534. /**
  21535. * candela (lm/sr)
  21536. */
  21537. get: function () {
  21538. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21539. },
  21540. enumerable: true,
  21541. configurable: true
  21542. });
  21543. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21544. /**
  21545. * lux (lm/m^2)
  21546. */
  21547. get: function () {
  21548. return Light._INTENSITYMODE_ILLUMINANCE;
  21549. },
  21550. enumerable: true,
  21551. configurable: true
  21552. });
  21553. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21554. /**
  21555. * nit (cd/m^2)
  21556. */
  21557. get: function () {
  21558. return Light._INTENSITYMODE_LUMINANCE;
  21559. },
  21560. enumerable: true,
  21561. configurable: true
  21562. });
  21563. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21564. /**
  21565. * Light type const id of the point light.
  21566. */
  21567. get: function () {
  21568. return Light._LIGHTTYPEID_POINTLIGHT;
  21569. },
  21570. enumerable: true,
  21571. configurable: true
  21572. });
  21573. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21574. /**
  21575. * Light type const id of the directional light.
  21576. */
  21577. get: function () {
  21578. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21579. },
  21580. enumerable: true,
  21581. configurable: true
  21582. });
  21583. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21584. /**
  21585. * Light type const id of the spot light.
  21586. */
  21587. get: function () {
  21588. return Light._LIGHTTYPEID_SPOTLIGHT;
  21589. },
  21590. enumerable: true,
  21591. configurable: true
  21592. });
  21593. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21594. /**
  21595. * Light type const id of the hemispheric light.
  21596. */
  21597. get: function () {
  21598. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21599. },
  21600. enumerable: true,
  21601. configurable: true
  21602. });
  21603. Object.defineProperty(Light.prototype, "intensityMode", {
  21604. /**
  21605. * Gets the photometric scale used to interpret the intensity.
  21606. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21607. */
  21608. get: function () {
  21609. return this._intensityMode;
  21610. },
  21611. /**
  21612. * Sets the photometric scale used to interpret the intensity.
  21613. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21614. */
  21615. set: function (value) {
  21616. this._intensityMode = value;
  21617. this._computePhotometricScale();
  21618. },
  21619. enumerable: true,
  21620. configurable: true
  21621. });
  21622. ;
  21623. ;
  21624. Object.defineProperty(Light.prototype, "radius", {
  21625. /**
  21626. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21627. */
  21628. get: function () {
  21629. return this._radius;
  21630. },
  21631. /**
  21632. * sets the light radius used by PBR Materials to simulate soft area lights.
  21633. */
  21634. set: function (value) {
  21635. this._radius = value;
  21636. this._computePhotometricScale();
  21637. },
  21638. enumerable: true,
  21639. configurable: true
  21640. });
  21641. ;
  21642. ;
  21643. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21644. /**
  21645. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21646. * the current shadow generator.
  21647. */
  21648. get: function () {
  21649. return this._shadowEnabled;
  21650. },
  21651. /**
  21652. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21653. * the current shadow generator.
  21654. */
  21655. set: function (value) {
  21656. if (this._shadowEnabled === value) {
  21657. return;
  21658. }
  21659. this._shadowEnabled = value;
  21660. this._markMeshesAsLightDirty();
  21661. },
  21662. enumerable: true,
  21663. configurable: true
  21664. });
  21665. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21666. /**
  21667. * Gets the only meshes impacted by this light.
  21668. */
  21669. get: function () {
  21670. return this._includedOnlyMeshes;
  21671. },
  21672. /**
  21673. * Sets the only meshes impacted by this light.
  21674. */
  21675. set: function (value) {
  21676. this._includedOnlyMeshes = value;
  21677. this._hookArrayForIncludedOnly(value);
  21678. },
  21679. enumerable: true,
  21680. configurable: true
  21681. });
  21682. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21683. /**
  21684. * Gets the meshes not impacted by this light.
  21685. */
  21686. get: function () {
  21687. return this._excludedMeshes;
  21688. },
  21689. /**
  21690. * Sets the meshes not impacted by this light.
  21691. */
  21692. set: function (value) {
  21693. this._excludedMeshes = value;
  21694. this._hookArrayForExcluded(value);
  21695. },
  21696. enumerable: true,
  21697. configurable: true
  21698. });
  21699. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21700. /**
  21701. * Gets the layer id use to find what meshes are not impacted by the light.
  21702. * Inactive if 0
  21703. */
  21704. get: function () {
  21705. return this._excludeWithLayerMask;
  21706. },
  21707. /**
  21708. * Sets the layer id use to find what meshes are not impacted by the light.
  21709. * Inactive if 0
  21710. */
  21711. set: function (value) {
  21712. this._excludeWithLayerMask = value;
  21713. this._resyncMeshes();
  21714. },
  21715. enumerable: true,
  21716. configurable: true
  21717. });
  21718. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21719. /**
  21720. * Gets the layer id use to find what meshes are impacted by the light.
  21721. * Inactive if 0
  21722. */
  21723. get: function () {
  21724. return this._includeOnlyWithLayerMask;
  21725. },
  21726. /**
  21727. * Sets the layer id use to find what meshes are impacted by the light.
  21728. * Inactive if 0
  21729. */
  21730. set: function (value) {
  21731. this._includeOnlyWithLayerMask = value;
  21732. this._resyncMeshes();
  21733. },
  21734. enumerable: true,
  21735. configurable: true
  21736. });
  21737. Object.defineProperty(Light.prototype, "lightmapMode", {
  21738. /**
  21739. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21740. */
  21741. get: function () {
  21742. return this._lightmapMode;
  21743. },
  21744. /**
  21745. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21746. */
  21747. set: function (value) {
  21748. if (this._lightmapMode === value) {
  21749. return;
  21750. }
  21751. this._lightmapMode = value;
  21752. this._markMeshesAsLightDirty();
  21753. },
  21754. enumerable: true,
  21755. configurable: true
  21756. });
  21757. /**
  21758. * Returns the string "Light".
  21759. * @returns the class name
  21760. */
  21761. Light.prototype.getClassName = function () {
  21762. return "Light";
  21763. };
  21764. /**
  21765. * Converts the light information to a readable string for debug purpose.
  21766. * @param fullDetails Supports for multiple levels of logging within scene loading
  21767. * @returns the human readable light info
  21768. */
  21769. Light.prototype.toString = function (fullDetails) {
  21770. var ret = "Name: " + this.name;
  21771. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21772. if (this.animations) {
  21773. for (var i = 0; i < this.animations.length; i++) {
  21774. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21775. }
  21776. }
  21777. if (fullDetails) {
  21778. }
  21779. return ret;
  21780. };
  21781. /**
  21782. * Set the enabled state of this node.
  21783. * @param value - the new enabled state
  21784. */
  21785. Light.prototype.setEnabled = function (value) {
  21786. _super.prototype.setEnabled.call(this, value);
  21787. this._resyncMeshes();
  21788. };
  21789. /**
  21790. * Returns the Light associated shadow generator if any.
  21791. * @return the associated shadow generator.
  21792. */
  21793. Light.prototype.getShadowGenerator = function () {
  21794. return this._shadowGenerator;
  21795. };
  21796. /**
  21797. * Returns a Vector3, the absolute light position in the World.
  21798. * @returns the world space position of the light
  21799. */
  21800. Light.prototype.getAbsolutePosition = function () {
  21801. return BABYLON.Vector3.Zero();
  21802. };
  21803. /**
  21804. * Specifies if the light will affect the passed mesh.
  21805. * @param mesh The mesh to test against the light
  21806. * @return true the mesh is affected otherwise, false.
  21807. */
  21808. Light.prototype.canAffectMesh = function (mesh) {
  21809. if (!mesh) {
  21810. return true;
  21811. }
  21812. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21813. return false;
  21814. }
  21815. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21816. return false;
  21817. }
  21818. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21819. return false;
  21820. }
  21821. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21822. return false;
  21823. }
  21824. return true;
  21825. };
  21826. /**
  21827. * Computes and Returns the light World matrix.
  21828. * @returns the world matrix
  21829. */
  21830. Light.prototype.getWorldMatrix = function () {
  21831. this._currentRenderId = this.getScene().getRenderId();
  21832. this._childRenderId = this._currentRenderId;
  21833. var worldMatrix = this._getWorldMatrix();
  21834. if (this.parent && this.parent.getWorldMatrix) {
  21835. if (!this._parentedWorldMatrix) {
  21836. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21837. }
  21838. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21839. this._markSyncedWithParent();
  21840. return this._parentedWorldMatrix;
  21841. }
  21842. return worldMatrix;
  21843. };
  21844. /**
  21845. * Sort function to order lights for rendering.
  21846. * @param a First Light object to compare to second.
  21847. * @param b Second Light object to compare first.
  21848. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21849. */
  21850. Light.CompareLightsPriority = function (a, b) {
  21851. //shadow-casting lights have priority over non-shadow-casting lights
  21852. //the renderPrioirty is a secondary sort criterion
  21853. if (a.shadowEnabled !== b.shadowEnabled) {
  21854. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21855. }
  21856. return b.renderPriority - a.renderPriority;
  21857. };
  21858. /**
  21859. * Releases resources associated with this node.
  21860. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21861. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21862. */
  21863. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21864. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21865. if (this._shadowGenerator) {
  21866. this._shadowGenerator.dispose();
  21867. this._shadowGenerator = null;
  21868. }
  21869. // Animations
  21870. this.getScene().stopAnimation(this);
  21871. // Remove from meshes
  21872. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21873. var mesh = _a[_i];
  21874. mesh._removeLightSource(this);
  21875. }
  21876. this._uniformBuffer.dispose();
  21877. // Remove from scene
  21878. this.getScene().removeLight(this);
  21879. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21880. };
  21881. /**
  21882. * Returns the light type ID (integer).
  21883. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21884. */
  21885. Light.prototype.getTypeID = function () {
  21886. return 0;
  21887. };
  21888. /**
  21889. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21890. * @returns the scaled intensity in intensity mode unit
  21891. */
  21892. Light.prototype.getScaledIntensity = function () {
  21893. return this._photometricScale * this.intensity;
  21894. };
  21895. /**
  21896. * Returns a new Light object, named "name", from the current one.
  21897. * @param name The name of the cloned light
  21898. * @returns the new created light
  21899. */
  21900. Light.prototype.clone = function (name) {
  21901. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21902. if (!constructor) {
  21903. return null;
  21904. }
  21905. return BABYLON.SerializationHelper.Clone(constructor, this);
  21906. };
  21907. /**
  21908. * Serializes the current light into a Serialization object.
  21909. * @returns the serialized object.
  21910. */
  21911. Light.prototype.serialize = function () {
  21912. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21913. // Type
  21914. serializationObject.type = this.getTypeID();
  21915. // Parent
  21916. if (this.parent) {
  21917. serializationObject.parentId = this.parent.id;
  21918. }
  21919. // Inclusion / exclusions
  21920. if (this.excludedMeshes.length > 0) {
  21921. serializationObject.excludedMeshesIds = [];
  21922. this.excludedMeshes.forEach(function (mesh) {
  21923. serializationObject.excludedMeshesIds.push(mesh.id);
  21924. });
  21925. }
  21926. if (this.includedOnlyMeshes.length > 0) {
  21927. serializationObject.includedOnlyMeshesIds = [];
  21928. this.includedOnlyMeshes.forEach(function (mesh) {
  21929. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21930. });
  21931. }
  21932. // Animations
  21933. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21934. serializationObject.ranges = this.serializeAnimationRanges();
  21935. return serializationObject;
  21936. };
  21937. /**
  21938. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21939. * This new light is named "name" and added to the passed scene.
  21940. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21941. * @param name The friendly name of the light
  21942. * @param scene The scene the new light will belong to
  21943. * @returns the constructor function
  21944. */
  21945. Light.GetConstructorFromName = function (type, name, scene) {
  21946. switch (type) {
  21947. case 0:
  21948. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21949. case 1:
  21950. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21951. case 2:
  21952. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21953. case 3:
  21954. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21955. }
  21956. return null;
  21957. };
  21958. /**
  21959. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21960. * @param parsedLight The JSON representation of the light
  21961. * @param scene The scene to create the parsed light in
  21962. * @returns the created light after parsing
  21963. */
  21964. Light.Parse = function (parsedLight, scene) {
  21965. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21966. if (!constructor) {
  21967. return null;
  21968. }
  21969. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21970. // Inclusion / exclusions
  21971. if (parsedLight.excludedMeshesIds) {
  21972. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21973. }
  21974. if (parsedLight.includedOnlyMeshesIds) {
  21975. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21976. }
  21977. // Parent
  21978. if (parsedLight.parentId) {
  21979. light._waitingParentId = parsedLight.parentId;
  21980. }
  21981. // Animations
  21982. if (parsedLight.animations) {
  21983. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21984. var parsedAnimation = parsedLight.animations[animationIndex];
  21985. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21986. }
  21987. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21988. }
  21989. if (parsedLight.autoAnimate) {
  21990. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21991. }
  21992. return light;
  21993. };
  21994. Light.prototype._hookArrayForExcluded = function (array) {
  21995. var _this = this;
  21996. var oldPush = array.push;
  21997. array.push = function () {
  21998. var items = [];
  21999. for (var _i = 0; _i < arguments.length; _i++) {
  22000. items[_i] = arguments[_i];
  22001. }
  22002. var result = oldPush.apply(array, items);
  22003. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22004. var item = items_1[_a];
  22005. item._resyncLighSource(_this);
  22006. }
  22007. return result;
  22008. };
  22009. var oldSplice = array.splice;
  22010. array.splice = function (index, deleteCount) {
  22011. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22012. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22013. var item = deleted_1[_i];
  22014. item._resyncLighSource(_this);
  22015. }
  22016. return deleted;
  22017. };
  22018. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22019. var item = array_1[_i];
  22020. item._resyncLighSource(this);
  22021. }
  22022. };
  22023. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22024. var _this = this;
  22025. var oldPush = array.push;
  22026. array.push = function () {
  22027. var items = [];
  22028. for (var _i = 0; _i < arguments.length; _i++) {
  22029. items[_i] = arguments[_i];
  22030. }
  22031. var result = oldPush.apply(array, items);
  22032. _this._resyncMeshes();
  22033. return result;
  22034. };
  22035. var oldSplice = array.splice;
  22036. array.splice = function (index, deleteCount) {
  22037. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22038. _this._resyncMeshes();
  22039. return deleted;
  22040. };
  22041. this._resyncMeshes();
  22042. };
  22043. Light.prototype._resyncMeshes = function () {
  22044. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22045. var mesh = _a[_i];
  22046. mesh._resyncLighSource(this);
  22047. }
  22048. };
  22049. /**
  22050. * Forces the meshes to update their light related information in their rendering used effects
  22051. * @hidden Internal Use Only
  22052. */
  22053. Light.prototype._markMeshesAsLightDirty = function () {
  22054. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22055. var mesh = _a[_i];
  22056. if (mesh._lightSources.indexOf(this) !== -1) {
  22057. mesh._markSubMeshesAsLightDirty();
  22058. }
  22059. }
  22060. };
  22061. /**
  22062. * Recomputes the cached photometric scale if needed.
  22063. */
  22064. Light.prototype._computePhotometricScale = function () {
  22065. this._photometricScale = this._getPhotometricScale();
  22066. this.getScene().resetCachedMaterial();
  22067. };
  22068. /**
  22069. * Returns the Photometric Scale according to the light type and intensity mode.
  22070. */
  22071. Light.prototype._getPhotometricScale = function () {
  22072. var photometricScale = 0.0;
  22073. var lightTypeID = this.getTypeID();
  22074. //get photometric mode
  22075. var photometricMode = this.intensityMode;
  22076. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22077. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22078. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22079. }
  22080. else {
  22081. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22082. }
  22083. }
  22084. //compute photometric scale
  22085. switch (lightTypeID) {
  22086. case Light.LIGHTTYPEID_POINTLIGHT:
  22087. case Light.LIGHTTYPEID_SPOTLIGHT:
  22088. switch (photometricMode) {
  22089. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22090. photometricScale = 1.0 / (4.0 * Math.PI);
  22091. break;
  22092. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22093. photometricScale = 1.0;
  22094. break;
  22095. case Light.INTENSITYMODE_LUMINANCE:
  22096. photometricScale = this.radius * this.radius;
  22097. break;
  22098. }
  22099. break;
  22100. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22101. switch (photometricMode) {
  22102. case Light.INTENSITYMODE_ILLUMINANCE:
  22103. photometricScale = 1.0;
  22104. break;
  22105. case Light.INTENSITYMODE_LUMINANCE:
  22106. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22107. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22108. var apexAngleRadians = this.radius;
  22109. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22110. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22111. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22112. photometricScale = solidAngle;
  22113. break;
  22114. }
  22115. break;
  22116. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22117. // No fall off in hemisperic light.
  22118. photometricScale = 1.0;
  22119. break;
  22120. }
  22121. return photometricScale;
  22122. };
  22123. /**
  22124. * Reorder the light in the scene according to their defined priority.
  22125. * @hidden Internal Use Only
  22126. */
  22127. Light.prototype._reorderLightsInScene = function () {
  22128. var scene = this.getScene();
  22129. if (this._renderPriority != 0) {
  22130. scene.requireLightSorting = true;
  22131. }
  22132. this.getScene().sortLightsByPriority();
  22133. };
  22134. //lightmapMode Consts
  22135. Light._LIGHTMAP_DEFAULT = 0;
  22136. Light._LIGHTMAP_SPECULAR = 1;
  22137. Light._LIGHTMAP_SHADOWSONLY = 2;
  22138. // Intensity Mode Consts
  22139. Light._INTENSITYMODE_AUTOMATIC = 0;
  22140. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22141. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22142. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22143. Light._INTENSITYMODE_LUMINANCE = 4;
  22144. // Light types ids const.
  22145. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22146. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22147. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22148. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22149. __decorate([
  22150. BABYLON.serializeAsColor3()
  22151. ], Light.prototype, "diffuse", void 0);
  22152. __decorate([
  22153. BABYLON.serializeAsColor3()
  22154. ], Light.prototype, "specular", void 0);
  22155. __decorate([
  22156. BABYLON.serialize()
  22157. ], Light.prototype, "intensity", void 0);
  22158. __decorate([
  22159. BABYLON.serialize()
  22160. ], Light.prototype, "range", void 0);
  22161. __decorate([
  22162. BABYLON.serialize()
  22163. ], Light.prototype, "intensityMode", null);
  22164. __decorate([
  22165. BABYLON.serialize()
  22166. ], Light.prototype, "radius", null);
  22167. __decorate([
  22168. BABYLON.serialize()
  22169. ], Light.prototype, "_renderPriority", void 0);
  22170. __decorate([
  22171. BABYLON.expandToProperty("_reorderLightsInScene")
  22172. ], Light.prototype, "renderPriority", void 0);
  22173. __decorate([
  22174. BABYLON.serialize("shadowEnabled")
  22175. ], Light.prototype, "_shadowEnabled", void 0);
  22176. __decorate([
  22177. BABYLON.serialize("excludeWithLayerMask")
  22178. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22179. __decorate([
  22180. BABYLON.serialize("includeOnlyWithLayerMask")
  22181. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22182. __decorate([
  22183. BABYLON.serialize("lightmapMode")
  22184. ], Light.prototype, "_lightmapMode", void 0);
  22185. return Light;
  22186. }(BABYLON.Node));
  22187. BABYLON.Light = Light;
  22188. })(BABYLON || (BABYLON = {}));
  22189. //# sourceMappingURL=babylon.light.js.map
  22190. var BABYLON;
  22191. (function (BABYLON) {
  22192. var Camera = /** @class */ (function (_super) {
  22193. __extends(Camera, _super);
  22194. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22195. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22196. var _this = _super.call(this, name, scene) || this;
  22197. /**
  22198. * The vector the camera should consider as up.
  22199. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22200. */
  22201. _this.upVector = BABYLON.Vector3.Up();
  22202. _this.orthoLeft = null;
  22203. _this.orthoRight = null;
  22204. _this.orthoBottom = null;
  22205. _this.orthoTop = null;
  22206. /**
  22207. * FOV is set in Radians. (default is 0.8)
  22208. */
  22209. _this.fov = 0.8;
  22210. _this.minZ = 1;
  22211. _this.maxZ = 10000.0;
  22212. _this.inertia = 0.9;
  22213. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22214. _this.isIntermediate = false;
  22215. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22216. /**
  22217. * Restricts the camera to viewing objects with the same layerMask.
  22218. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22219. */
  22220. _this.layerMask = 0x0FFFFFFF;
  22221. /**
  22222. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22223. */
  22224. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22225. // Camera rig members
  22226. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22227. _this._rigCameras = new Array();
  22228. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22229. _this._skipRendering = false;
  22230. _this.customRenderTargets = new Array();
  22231. // Observables
  22232. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22233. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22234. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22235. _this.onRestoreStateObservable = new BABYLON.Observable();
  22236. // Cache
  22237. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22238. _this._projectionMatrix = new BABYLON.Matrix();
  22239. _this._doNotComputeProjectionMatrix = false;
  22240. _this._worldMatrix = BABYLON.Matrix.Identity();
  22241. _this._postProcesses = new Array();
  22242. _this._transformMatrix = BABYLON.Matrix.Zero();
  22243. _this._activeMeshes = new BABYLON.SmartArray(256);
  22244. _this._globalPosition = BABYLON.Vector3.Zero();
  22245. _this._refreshFrustumPlanes = true;
  22246. _this.getScene().addCamera(_this);
  22247. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22248. _this.getScene().activeCamera = _this;
  22249. }
  22250. _this.position = position;
  22251. return _this;
  22252. }
  22253. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22254. get: function () {
  22255. return Camera._PERSPECTIVE_CAMERA;
  22256. },
  22257. enumerable: true,
  22258. configurable: true
  22259. });
  22260. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22261. get: function () {
  22262. return Camera._ORTHOGRAPHIC_CAMERA;
  22263. },
  22264. enumerable: true,
  22265. configurable: true
  22266. });
  22267. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22268. /**
  22269. * This is the default FOV mode for perspective cameras.
  22270. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22271. *
  22272. */
  22273. get: function () {
  22274. return Camera._FOVMODE_VERTICAL_FIXED;
  22275. },
  22276. enumerable: true,
  22277. configurable: true
  22278. });
  22279. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22280. /**
  22281. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22282. *
  22283. */
  22284. get: function () {
  22285. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22286. },
  22287. enumerable: true,
  22288. configurable: true
  22289. });
  22290. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22291. get: function () {
  22292. return Camera._RIG_MODE_NONE;
  22293. },
  22294. enumerable: true,
  22295. configurable: true
  22296. });
  22297. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22298. get: function () {
  22299. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22300. },
  22301. enumerable: true,
  22302. configurable: true
  22303. });
  22304. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22305. get: function () {
  22306. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22307. },
  22308. enumerable: true,
  22309. configurable: true
  22310. });
  22311. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22312. get: function () {
  22313. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22314. },
  22315. enumerable: true,
  22316. configurable: true
  22317. });
  22318. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22319. get: function () {
  22320. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22321. },
  22322. enumerable: true,
  22323. configurable: true
  22324. });
  22325. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22326. get: function () {
  22327. return Camera._RIG_MODE_VR;
  22328. },
  22329. enumerable: true,
  22330. configurable: true
  22331. });
  22332. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22333. get: function () {
  22334. return Camera._RIG_MODE_WEBVR;
  22335. },
  22336. enumerable: true,
  22337. configurable: true
  22338. });
  22339. /**
  22340. * Store current camera state (fov, position, etc..)
  22341. */
  22342. Camera.prototype.storeState = function () {
  22343. this._stateStored = true;
  22344. this._storedFov = this.fov;
  22345. return this;
  22346. };
  22347. /**
  22348. * Restores the camera state values if it has been stored. You must call storeState() first
  22349. */
  22350. Camera.prototype._restoreStateValues = function () {
  22351. if (!this._stateStored) {
  22352. return false;
  22353. }
  22354. this.fov = this._storedFov;
  22355. return true;
  22356. };
  22357. /**
  22358. * Restored camera state. You must call storeState() first
  22359. */
  22360. Camera.prototype.restoreState = function () {
  22361. if (this._restoreStateValues()) {
  22362. this.onRestoreStateObservable.notifyObservers(this);
  22363. return true;
  22364. }
  22365. return false;
  22366. };
  22367. Camera.prototype.getClassName = function () {
  22368. return "Camera";
  22369. };
  22370. /**
  22371. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22372. */
  22373. Camera.prototype.toString = function (fullDetails) {
  22374. var ret = "Name: " + this.name;
  22375. ret += ", type: " + this.getClassName();
  22376. if (this.animations) {
  22377. for (var i = 0; i < this.animations.length; i++) {
  22378. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22379. }
  22380. }
  22381. if (fullDetails) {
  22382. }
  22383. return ret;
  22384. };
  22385. Object.defineProperty(Camera.prototype, "globalPosition", {
  22386. get: function () {
  22387. return this._globalPosition;
  22388. },
  22389. enumerable: true,
  22390. configurable: true
  22391. });
  22392. Camera.prototype.getActiveMeshes = function () {
  22393. return this._activeMeshes;
  22394. };
  22395. Camera.prototype.isActiveMesh = function (mesh) {
  22396. return (this._activeMeshes.indexOf(mesh) !== -1);
  22397. };
  22398. /**
  22399. * Is this camera ready to be used/rendered
  22400. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22401. * @return true if the camera is ready
  22402. */
  22403. Camera.prototype.isReady = function (completeCheck) {
  22404. if (completeCheck === void 0) { completeCheck = false; }
  22405. if (completeCheck) {
  22406. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22407. var pp = _a[_i];
  22408. if (pp && !pp.isReady()) {
  22409. return false;
  22410. }
  22411. }
  22412. }
  22413. return _super.prototype.isReady.call(this, completeCheck);
  22414. };
  22415. //Cache
  22416. Camera.prototype._initCache = function () {
  22417. _super.prototype._initCache.call(this);
  22418. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22419. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22420. this._cache.mode = undefined;
  22421. this._cache.minZ = undefined;
  22422. this._cache.maxZ = undefined;
  22423. this._cache.fov = undefined;
  22424. this._cache.fovMode = undefined;
  22425. this._cache.aspectRatio = undefined;
  22426. this._cache.orthoLeft = undefined;
  22427. this._cache.orthoRight = undefined;
  22428. this._cache.orthoBottom = undefined;
  22429. this._cache.orthoTop = undefined;
  22430. this._cache.renderWidth = undefined;
  22431. this._cache.renderHeight = undefined;
  22432. };
  22433. Camera.prototype._updateCache = function (ignoreParentClass) {
  22434. if (!ignoreParentClass) {
  22435. _super.prototype._updateCache.call(this);
  22436. }
  22437. this._cache.position.copyFrom(this.position);
  22438. this._cache.upVector.copyFrom(this.upVector);
  22439. };
  22440. // Synchronized
  22441. Camera.prototype._isSynchronized = function () {
  22442. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22443. };
  22444. Camera.prototype._isSynchronizedViewMatrix = function () {
  22445. if (!_super.prototype._isSynchronized.call(this))
  22446. return false;
  22447. return this._cache.position.equals(this.position)
  22448. && this._cache.upVector.equals(this.upVector)
  22449. && this.isSynchronizedWithParent();
  22450. };
  22451. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22452. var check = this._cache.mode === this.mode
  22453. && this._cache.minZ === this.minZ
  22454. && this._cache.maxZ === this.maxZ;
  22455. if (!check) {
  22456. return false;
  22457. }
  22458. var engine = this.getEngine();
  22459. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22460. check = this._cache.fov === this.fov
  22461. && this._cache.fovMode === this.fovMode
  22462. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22463. }
  22464. else {
  22465. check = this._cache.orthoLeft === this.orthoLeft
  22466. && this._cache.orthoRight === this.orthoRight
  22467. && this._cache.orthoBottom === this.orthoBottom
  22468. && this._cache.orthoTop === this.orthoTop
  22469. && this._cache.renderWidth === engine.getRenderWidth()
  22470. && this._cache.renderHeight === engine.getRenderHeight();
  22471. }
  22472. return check;
  22473. };
  22474. // Controls
  22475. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22476. };
  22477. Camera.prototype.detachControl = function (element) {
  22478. };
  22479. Camera.prototype.update = function () {
  22480. this._checkInputs();
  22481. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22482. this._updateRigCameras();
  22483. }
  22484. };
  22485. Camera.prototype._checkInputs = function () {
  22486. this.onAfterCheckInputsObservable.notifyObservers(this);
  22487. };
  22488. Object.defineProperty(Camera.prototype, "rigCameras", {
  22489. get: function () {
  22490. return this._rigCameras;
  22491. },
  22492. enumerable: true,
  22493. configurable: true
  22494. });
  22495. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22496. get: function () {
  22497. return this._rigPostProcess;
  22498. },
  22499. enumerable: true,
  22500. configurable: true
  22501. });
  22502. /**
  22503. * Internal, gets the first post proces.
  22504. * @returns the first post process to be run on this camera.
  22505. */
  22506. Camera.prototype._getFirstPostProcess = function () {
  22507. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22508. if (this._postProcesses[ppIndex] !== null) {
  22509. return this._postProcesses[ppIndex];
  22510. }
  22511. }
  22512. return null;
  22513. };
  22514. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22515. // invalidate framebuffer
  22516. var firstPostProcess = this._getFirstPostProcess();
  22517. if (firstPostProcess) {
  22518. firstPostProcess.markTextureDirty();
  22519. }
  22520. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22521. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22522. var cam = this._rigCameras[i];
  22523. var rigPostProcess = cam._rigPostProcess;
  22524. // for VR rig, there does not have to be a post process
  22525. if (rigPostProcess) {
  22526. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22527. if (isPass) {
  22528. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22529. cam.isIntermediate = this._postProcesses.length === 0;
  22530. }
  22531. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22532. rigPostProcess.markTextureDirty();
  22533. }
  22534. else {
  22535. cam._postProcesses = this._postProcesses.slice(0);
  22536. }
  22537. }
  22538. };
  22539. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22540. if (insertAt === void 0) { insertAt = null; }
  22541. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22542. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22543. return 0;
  22544. }
  22545. if (insertAt == null || insertAt < 0) {
  22546. this._postProcesses.push(postProcess);
  22547. }
  22548. else if (this._postProcesses[insertAt] === null) {
  22549. this._postProcesses[insertAt] = postProcess;
  22550. }
  22551. else {
  22552. this._postProcesses.splice(insertAt, 0, postProcess);
  22553. }
  22554. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22555. return this._postProcesses.indexOf(postProcess);
  22556. };
  22557. Camera.prototype.detachPostProcess = function (postProcess) {
  22558. var idx = this._postProcesses.indexOf(postProcess);
  22559. if (idx !== -1) {
  22560. this._postProcesses[idx] = null;
  22561. }
  22562. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22563. };
  22564. Camera.prototype.getWorldMatrix = function () {
  22565. if (this._isSynchronizedViewMatrix()) {
  22566. return this._worldMatrix;
  22567. }
  22568. // Getting the the view matrix will also compute the world matrix.
  22569. this.getViewMatrix();
  22570. return this._worldMatrix;
  22571. };
  22572. Camera.prototype._getViewMatrix = function () {
  22573. return BABYLON.Matrix.Identity();
  22574. };
  22575. Camera.prototype.getViewMatrix = function (force) {
  22576. if (!force && this._isSynchronizedViewMatrix()) {
  22577. return this._computedViewMatrix;
  22578. }
  22579. this.updateCache();
  22580. this._computedViewMatrix = this._getViewMatrix();
  22581. this._currentRenderId = this.getScene().getRenderId();
  22582. this._childRenderId = this._currentRenderId;
  22583. this._refreshFrustumPlanes = true;
  22584. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22585. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22586. }
  22587. this.onViewMatrixChangedObservable.notifyObservers(this);
  22588. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22589. return this._computedViewMatrix;
  22590. };
  22591. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22592. this._doNotComputeProjectionMatrix = true;
  22593. if (projection !== undefined) {
  22594. this._projectionMatrix = projection;
  22595. }
  22596. };
  22597. ;
  22598. Camera.prototype.unfreezeProjectionMatrix = function () {
  22599. this._doNotComputeProjectionMatrix = false;
  22600. };
  22601. ;
  22602. Camera.prototype.getProjectionMatrix = function (force) {
  22603. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22604. return this._projectionMatrix;
  22605. }
  22606. // Cache
  22607. this._cache.mode = this.mode;
  22608. this._cache.minZ = this.minZ;
  22609. this._cache.maxZ = this.maxZ;
  22610. // Matrix
  22611. this._refreshFrustumPlanes = true;
  22612. var engine = this.getEngine();
  22613. var scene = this.getScene();
  22614. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22615. this._cache.fov = this.fov;
  22616. this._cache.fovMode = this.fovMode;
  22617. this._cache.aspectRatio = engine.getAspectRatio(this);
  22618. if (this.minZ <= 0) {
  22619. this.minZ = 0.1;
  22620. }
  22621. if (scene.useRightHandedSystem) {
  22622. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22623. }
  22624. else {
  22625. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22626. }
  22627. }
  22628. else {
  22629. var halfWidth = engine.getRenderWidth() / 2.0;
  22630. var halfHeight = engine.getRenderHeight() / 2.0;
  22631. if (scene.useRightHandedSystem) {
  22632. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22633. }
  22634. else {
  22635. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22636. }
  22637. this._cache.orthoLeft = this.orthoLeft;
  22638. this._cache.orthoRight = this.orthoRight;
  22639. this._cache.orthoBottom = this.orthoBottom;
  22640. this._cache.orthoTop = this.orthoTop;
  22641. this._cache.renderWidth = engine.getRenderWidth();
  22642. this._cache.renderHeight = engine.getRenderHeight();
  22643. }
  22644. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22645. return this._projectionMatrix;
  22646. };
  22647. Camera.prototype.getTranformationMatrix = function () {
  22648. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22649. return this._transformMatrix;
  22650. };
  22651. Camera.prototype.updateFrustumPlanes = function () {
  22652. if (!this._refreshFrustumPlanes) {
  22653. return;
  22654. }
  22655. this.getTranformationMatrix();
  22656. if (!this._frustumPlanes) {
  22657. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22658. }
  22659. else {
  22660. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22661. }
  22662. this._refreshFrustumPlanes = false;
  22663. };
  22664. Camera.prototype.isInFrustum = function (target) {
  22665. this.updateFrustumPlanes();
  22666. return target.isInFrustum(this._frustumPlanes);
  22667. };
  22668. Camera.prototype.isCompletelyInFrustum = function (target) {
  22669. this.updateFrustumPlanes();
  22670. return target.isCompletelyInFrustum(this._frustumPlanes);
  22671. };
  22672. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22673. if (length === void 0) { length = 100; }
  22674. if (!transform) {
  22675. transform = this.getWorldMatrix();
  22676. }
  22677. if (!origin) {
  22678. origin = this.position;
  22679. }
  22680. var forward = new BABYLON.Vector3(0, 0, 1);
  22681. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22682. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22683. return new BABYLON.Ray(origin, direction, length);
  22684. };
  22685. /**
  22686. * Releases resources associated with this node.
  22687. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22688. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22689. */
  22690. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22691. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22692. // Observables
  22693. this.onViewMatrixChangedObservable.clear();
  22694. this.onProjectionMatrixChangedObservable.clear();
  22695. this.onAfterCheckInputsObservable.clear();
  22696. this.onRestoreStateObservable.clear();
  22697. // Inputs
  22698. if (this.inputs) {
  22699. this.inputs.clear();
  22700. }
  22701. // Animations
  22702. this.getScene().stopAnimation(this);
  22703. // Remove from scene
  22704. this.getScene().removeCamera(this);
  22705. while (this._rigCameras.length > 0) {
  22706. var camera = this._rigCameras.pop();
  22707. if (camera) {
  22708. camera.dispose();
  22709. }
  22710. }
  22711. // Postprocesses
  22712. if (this._rigPostProcess) {
  22713. this._rigPostProcess.dispose(this);
  22714. this._rigPostProcess = null;
  22715. this._postProcesses = [];
  22716. }
  22717. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22718. this._rigPostProcess = null;
  22719. this._postProcesses = [];
  22720. }
  22721. else {
  22722. var i = this._postProcesses.length;
  22723. while (--i >= 0) {
  22724. var postProcess = this._postProcesses[i];
  22725. if (postProcess) {
  22726. postProcess.dispose(this);
  22727. }
  22728. }
  22729. }
  22730. // Render targets
  22731. var i = this.customRenderTargets.length;
  22732. while (--i >= 0) {
  22733. this.customRenderTargets[i].dispose();
  22734. }
  22735. this.customRenderTargets = [];
  22736. // Active Meshes
  22737. this._activeMeshes.dispose();
  22738. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22739. };
  22740. Object.defineProperty(Camera.prototype, "leftCamera", {
  22741. // ---- Camera rigs section ----
  22742. get: function () {
  22743. if (this._rigCameras.length < 1) {
  22744. return null;
  22745. }
  22746. return this._rigCameras[0];
  22747. },
  22748. enumerable: true,
  22749. configurable: true
  22750. });
  22751. Object.defineProperty(Camera.prototype, "rightCamera", {
  22752. get: function () {
  22753. if (this._rigCameras.length < 2) {
  22754. return null;
  22755. }
  22756. return this._rigCameras[1];
  22757. },
  22758. enumerable: true,
  22759. configurable: true
  22760. });
  22761. Camera.prototype.getLeftTarget = function () {
  22762. if (this._rigCameras.length < 1) {
  22763. return null;
  22764. }
  22765. return this._rigCameras[0].getTarget();
  22766. };
  22767. Camera.prototype.getRightTarget = function () {
  22768. if (this._rigCameras.length < 2) {
  22769. return null;
  22770. }
  22771. return this._rigCameras[1].getTarget();
  22772. };
  22773. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22774. if (this.cameraRigMode === mode) {
  22775. return;
  22776. }
  22777. while (this._rigCameras.length > 0) {
  22778. var camera = this._rigCameras.pop();
  22779. if (camera) {
  22780. camera.dispose();
  22781. }
  22782. }
  22783. this.cameraRigMode = mode;
  22784. this._cameraRigParams = {};
  22785. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22786. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22787. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22788. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22789. // create the rig cameras, unless none
  22790. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22791. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22792. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22793. if (leftCamera && rightCamera) {
  22794. this._rigCameras.push(leftCamera);
  22795. this._rigCameras.push(rightCamera);
  22796. }
  22797. }
  22798. switch (this.cameraRigMode) {
  22799. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22800. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22801. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22802. break;
  22803. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22804. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22805. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22806. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22807. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22808. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22809. break;
  22810. case Camera.RIG_MODE_VR:
  22811. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22812. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22813. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22814. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22815. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22816. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22817. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22818. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22819. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22820. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22821. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22822. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22823. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22824. if (metrics.compensateDistortion) {
  22825. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22826. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22827. }
  22828. break;
  22829. case Camera.RIG_MODE_WEBVR:
  22830. if (rigParams.vrDisplay) {
  22831. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22832. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22833. //Left eye
  22834. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22835. this._rigCameras[0].setCameraRigParameter("left", true);
  22836. //leaving this for future reference
  22837. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22838. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22839. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22840. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22841. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22842. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22843. this._rigCameras[0].parent = this;
  22844. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22845. //Right eye
  22846. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22847. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22848. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22849. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22850. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22851. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22852. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22853. this._rigCameras[1].parent = this;
  22854. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22855. if (Camera.UseAlternateWebVRRendering) {
  22856. this._rigCameras[1]._skipRendering = true;
  22857. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22858. }
  22859. }
  22860. break;
  22861. }
  22862. this._cascadePostProcessesToRigCams();
  22863. this.update();
  22864. };
  22865. Camera.prototype._getVRProjectionMatrix = function () {
  22866. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22867. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22868. return this._projectionMatrix;
  22869. };
  22870. Camera.prototype._updateCameraRotationMatrix = function () {
  22871. //Here for WebVR
  22872. };
  22873. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22874. //Here for WebVR
  22875. };
  22876. /**
  22877. * This function MUST be overwritten by the different WebVR cameras available.
  22878. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22879. */
  22880. Camera.prototype._getWebVRProjectionMatrix = function () {
  22881. return BABYLON.Matrix.Identity();
  22882. };
  22883. /**
  22884. * This function MUST be overwritten by the different WebVR cameras available.
  22885. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22886. */
  22887. Camera.prototype._getWebVRViewMatrix = function () {
  22888. return BABYLON.Matrix.Identity();
  22889. };
  22890. Camera.prototype.setCameraRigParameter = function (name, value) {
  22891. if (!this._cameraRigParams) {
  22892. this._cameraRigParams = {};
  22893. }
  22894. this._cameraRigParams[name] = value;
  22895. //provisionnally:
  22896. if (name === "interaxialDistance") {
  22897. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22898. }
  22899. };
  22900. /**
  22901. * needs to be overridden by children so sub has required properties to be copied
  22902. */
  22903. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22904. return null;
  22905. };
  22906. /**
  22907. * May need to be overridden by children
  22908. */
  22909. Camera.prototype._updateRigCameras = function () {
  22910. for (var i = 0; i < this._rigCameras.length; i++) {
  22911. this._rigCameras[i].minZ = this.minZ;
  22912. this._rigCameras[i].maxZ = this.maxZ;
  22913. this._rigCameras[i].fov = this.fov;
  22914. }
  22915. // only update viewport when ANAGLYPH
  22916. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22917. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22918. }
  22919. };
  22920. Camera.prototype._setupInputs = function () {
  22921. };
  22922. Camera.prototype.serialize = function () {
  22923. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22924. // Type
  22925. serializationObject.type = this.getClassName();
  22926. // Parent
  22927. if (this.parent) {
  22928. serializationObject.parentId = this.parent.id;
  22929. }
  22930. if (this.inputs) {
  22931. this.inputs.serialize(serializationObject);
  22932. }
  22933. // Animations
  22934. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22935. serializationObject.ranges = this.serializeAnimationRanges();
  22936. return serializationObject;
  22937. };
  22938. Camera.prototype.clone = function (name) {
  22939. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22940. };
  22941. Camera.prototype.getDirection = function (localAxis) {
  22942. var result = BABYLON.Vector3.Zero();
  22943. this.getDirectionToRef(localAxis, result);
  22944. return result;
  22945. };
  22946. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22947. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22948. };
  22949. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22950. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22951. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22952. switch (type) {
  22953. case "ArcRotateCamera":
  22954. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22955. case "DeviceOrientationCamera":
  22956. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22957. case "FollowCamera":
  22958. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22959. case "ArcFollowCamera":
  22960. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22961. case "GamepadCamera":
  22962. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22963. case "TouchCamera":
  22964. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22965. case "VirtualJoysticksCamera":
  22966. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22967. case "WebVRFreeCamera":
  22968. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22969. case "WebVRGamepadCamera":
  22970. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22971. case "VRDeviceOrientationFreeCamera":
  22972. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22973. case "VRDeviceOrientationGamepadCamera":
  22974. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22975. case "AnaglyphArcRotateCamera":
  22976. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22977. case "AnaglyphFreeCamera":
  22978. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22979. case "AnaglyphGamepadCamera":
  22980. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22981. case "AnaglyphUniversalCamera":
  22982. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22983. case "StereoscopicArcRotateCamera":
  22984. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22985. case "StereoscopicFreeCamera":
  22986. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22987. case "StereoscopicGamepadCamera":
  22988. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22989. case "StereoscopicUniversalCamera":
  22990. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22991. case "FreeCamera": // Forcing Universal here
  22992. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22993. default: // Universal Camera is the default value
  22994. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22995. }
  22996. };
  22997. Camera.prototype.computeWorldMatrix = function () {
  22998. return this.getWorldMatrix();
  22999. };
  23000. Camera.Parse = function (parsedCamera, scene) {
  23001. var type = parsedCamera.type;
  23002. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23003. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23004. // Parent
  23005. if (parsedCamera.parentId) {
  23006. camera._waitingParentId = parsedCamera.parentId;
  23007. }
  23008. //If camera has an input manager, let it parse inputs settings
  23009. if (camera.inputs) {
  23010. camera.inputs.parse(parsedCamera);
  23011. camera._setupInputs();
  23012. }
  23013. if (camera.setPosition) { // need to force position
  23014. camera.position.copyFromFloats(0, 0, 0);
  23015. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23016. }
  23017. // Target
  23018. if (parsedCamera.target) {
  23019. if (camera.setTarget) {
  23020. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23021. }
  23022. }
  23023. // Apply 3d rig, when found
  23024. if (parsedCamera.cameraRigMode) {
  23025. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23026. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23027. }
  23028. // Animations
  23029. if (parsedCamera.animations) {
  23030. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23031. var parsedAnimation = parsedCamera.animations[animationIndex];
  23032. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23033. }
  23034. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23035. }
  23036. if (parsedCamera.autoAnimate) {
  23037. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23038. }
  23039. return camera;
  23040. };
  23041. // Statics
  23042. Camera._PERSPECTIVE_CAMERA = 0;
  23043. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23044. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23045. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23046. Camera._RIG_MODE_NONE = 0;
  23047. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23048. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23049. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23050. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23051. Camera._RIG_MODE_VR = 20;
  23052. Camera._RIG_MODE_WEBVR = 21;
  23053. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23054. Camera.UseAlternateWebVRRendering = false;
  23055. __decorate([
  23056. BABYLON.serializeAsVector3()
  23057. ], Camera.prototype, "position", void 0);
  23058. __decorate([
  23059. BABYLON.serializeAsVector3()
  23060. ], Camera.prototype, "upVector", void 0);
  23061. __decorate([
  23062. BABYLON.serialize()
  23063. ], Camera.prototype, "orthoLeft", void 0);
  23064. __decorate([
  23065. BABYLON.serialize()
  23066. ], Camera.prototype, "orthoRight", void 0);
  23067. __decorate([
  23068. BABYLON.serialize()
  23069. ], Camera.prototype, "orthoBottom", void 0);
  23070. __decorate([
  23071. BABYLON.serialize()
  23072. ], Camera.prototype, "orthoTop", void 0);
  23073. __decorate([
  23074. BABYLON.serialize()
  23075. ], Camera.prototype, "fov", void 0);
  23076. __decorate([
  23077. BABYLON.serialize()
  23078. ], Camera.prototype, "minZ", void 0);
  23079. __decorate([
  23080. BABYLON.serialize()
  23081. ], Camera.prototype, "maxZ", void 0);
  23082. __decorate([
  23083. BABYLON.serialize()
  23084. ], Camera.prototype, "inertia", void 0);
  23085. __decorate([
  23086. BABYLON.serialize()
  23087. ], Camera.prototype, "mode", void 0);
  23088. __decorate([
  23089. BABYLON.serialize()
  23090. ], Camera.prototype, "layerMask", void 0);
  23091. __decorate([
  23092. BABYLON.serialize()
  23093. ], Camera.prototype, "fovMode", void 0);
  23094. __decorate([
  23095. BABYLON.serialize()
  23096. ], Camera.prototype, "cameraRigMode", void 0);
  23097. __decorate([
  23098. BABYLON.serialize()
  23099. ], Camera.prototype, "interaxialDistance", void 0);
  23100. __decorate([
  23101. BABYLON.serialize()
  23102. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23103. return Camera;
  23104. }(BABYLON.Node));
  23105. BABYLON.Camera = Camera;
  23106. })(BABYLON || (BABYLON = {}));
  23107. //# sourceMappingURL=babylon.camera.js.map
  23108. var BABYLON;
  23109. (function (BABYLON) {
  23110. var RenderingManager = /** @class */ (function () {
  23111. function RenderingManager(scene) {
  23112. this._renderingGroups = new Array();
  23113. this._autoClearDepthStencil = {};
  23114. this._customOpaqueSortCompareFn = {};
  23115. this._customAlphaTestSortCompareFn = {};
  23116. this._customTransparentSortCompareFn = {};
  23117. this._renderinGroupInfo = null;
  23118. this._scene = scene;
  23119. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23120. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23121. }
  23122. }
  23123. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23124. if (depth === void 0) { depth = true; }
  23125. if (stencil === void 0) { stencil = true; }
  23126. if (this._depthStencilBufferAlreadyCleaned) {
  23127. return;
  23128. }
  23129. this._scene.getEngine().clear(null, false, depth, stencil);
  23130. this._depthStencilBufferAlreadyCleaned = true;
  23131. };
  23132. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23133. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23134. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23135. var info = null;
  23136. if (observable) {
  23137. if (!this._renderinGroupInfo) {
  23138. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23139. }
  23140. info = this._renderinGroupInfo;
  23141. info.scene = this._scene;
  23142. info.camera = this._scene.activeCamera;
  23143. }
  23144. // Dispatch sprites
  23145. if (renderSprites) {
  23146. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23147. var manager = this._scene.spriteManagers[index];
  23148. this.dispatchSprites(manager);
  23149. }
  23150. }
  23151. // Render
  23152. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23153. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23154. var renderingGroup = this._renderingGroups[index];
  23155. if (!renderingGroup && !observable)
  23156. continue;
  23157. var renderingGroupMask = 0;
  23158. // Fire PRECLEAR stage
  23159. if (observable && info) {
  23160. renderingGroupMask = Math.pow(2, index);
  23161. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23162. info.renderingGroupId = index;
  23163. observable.notifyObservers(info, renderingGroupMask);
  23164. }
  23165. // Clear depth/stencil if needed
  23166. if (RenderingManager.AUTOCLEAR) {
  23167. var autoClear = this._autoClearDepthStencil[index];
  23168. if (autoClear && autoClear.autoClear) {
  23169. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23170. }
  23171. }
  23172. if (observable && info) {
  23173. // Fire PREOPAQUE stage
  23174. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23175. observable.notifyObservers(info, renderingGroupMask);
  23176. // Fire PRETRANSPARENT stage
  23177. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23178. observable.notifyObservers(info, renderingGroupMask);
  23179. }
  23180. if (renderingGroup)
  23181. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23182. // Fire POSTTRANSPARENT stage
  23183. if (observable && info) {
  23184. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23185. observable.notifyObservers(info, renderingGroupMask);
  23186. }
  23187. }
  23188. };
  23189. RenderingManager.prototype.reset = function () {
  23190. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23191. var renderingGroup = this._renderingGroups[index];
  23192. if (renderingGroup) {
  23193. renderingGroup.prepare();
  23194. }
  23195. }
  23196. };
  23197. RenderingManager.prototype.dispose = function () {
  23198. this.freeRenderingGroups();
  23199. this._renderingGroups.length = 0;
  23200. };
  23201. /**
  23202. * Clear the info related to rendering groups preventing retention points during dispose.
  23203. */
  23204. RenderingManager.prototype.freeRenderingGroups = function () {
  23205. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23206. var renderingGroup = this._renderingGroups[index];
  23207. if (renderingGroup) {
  23208. renderingGroup.dispose();
  23209. }
  23210. }
  23211. };
  23212. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23213. if (this._renderingGroups[renderingGroupId] === undefined) {
  23214. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23215. }
  23216. };
  23217. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23218. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23219. this._prepareRenderingGroup(renderingGroupId);
  23220. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23221. };
  23222. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23223. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23224. this._prepareRenderingGroup(renderingGroupId);
  23225. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23226. };
  23227. /**
  23228. * @param subMesh The submesh to dispatch
  23229. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23230. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23231. */
  23232. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23233. if (mesh === undefined) {
  23234. mesh = subMesh.getMesh();
  23235. }
  23236. var renderingGroupId = mesh.renderingGroupId || 0;
  23237. this._prepareRenderingGroup(renderingGroupId);
  23238. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23239. };
  23240. /**
  23241. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23242. * This allowed control for front to back rendering or reversly depending of the special needs.
  23243. *
  23244. * @param renderingGroupId The rendering group id corresponding to its index
  23245. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23246. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23247. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23248. */
  23249. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23250. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23251. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23252. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23253. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23254. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23255. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23256. if (this._renderingGroups[renderingGroupId]) {
  23257. var group = this._renderingGroups[renderingGroupId];
  23258. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23259. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23260. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23261. }
  23262. };
  23263. /**
  23264. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23265. *
  23266. * @param renderingGroupId The rendering group id corresponding to its index
  23267. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23268. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23269. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23270. */
  23271. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23272. if (depth === void 0) { depth = true; }
  23273. if (stencil === void 0) { stencil = true; }
  23274. this._autoClearDepthStencil[renderingGroupId] = {
  23275. autoClear: autoClearDepthStencil,
  23276. depth: depth,
  23277. stencil: stencil
  23278. };
  23279. };
  23280. /**
  23281. * The max id used for rendering groups (not included)
  23282. */
  23283. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23284. /**
  23285. * The min id used for rendering groups (included)
  23286. */
  23287. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23288. /**
  23289. * Used to globally prevent autoclearing scenes.
  23290. */
  23291. RenderingManager.AUTOCLEAR = true;
  23292. return RenderingManager;
  23293. }());
  23294. BABYLON.RenderingManager = RenderingManager;
  23295. })(BABYLON || (BABYLON = {}));
  23296. //# sourceMappingURL=babylon.renderingManager.js.map
  23297. var BABYLON;
  23298. (function (BABYLON) {
  23299. var RenderingGroup = /** @class */ (function () {
  23300. /**
  23301. * Creates a new rendering group.
  23302. * @param index The rendering group index
  23303. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23304. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23305. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23306. */
  23307. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23308. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23309. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23310. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23311. this.index = index;
  23312. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23313. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23314. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23315. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23316. this._particleSystems = new BABYLON.SmartArray(256);
  23317. this._spriteManagers = new BABYLON.SmartArray(256);
  23318. this._edgesRenderers = new BABYLON.SmartArray(16);
  23319. this._scene = scene;
  23320. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23321. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23322. this.transparentSortCompareFn = transparentSortCompareFn;
  23323. }
  23324. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23325. /**
  23326. * Set the opaque sort comparison function.
  23327. * If null the sub meshes will be render in the order they were created
  23328. */
  23329. set: function (value) {
  23330. this._opaqueSortCompareFn = value;
  23331. if (value) {
  23332. this._renderOpaque = this.renderOpaqueSorted;
  23333. }
  23334. else {
  23335. this._renderOpaque = RenderingGroup.renderUnsorted;
  23336. }
  23337. },
  23338. enumerable: true,
  23339. configurable: true
  23340. });
  23341. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23342. /**
  23343. * Set the alpha test sort comparison function.
  23344. * If null the sub meshes will be render in the order they were created
  23345. */
  23346. set: function (value) {
  23347. this._alphaTestSortCompareFn = value;
  23348. if (value) {
  23349. this._renderAlphaTest = this.renderAlphaTestSorted;
  23350. }
  23351. else {
  23352. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23353. }
  23354. },
  23355. enumerable: true,
  23356. configurable: true
  23357. });
  23358. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23359. /**
  23360. * Set the transparent sort comparison function.
  23361. * If null the sub meshes will be render in the order they were created
  23362. */
  23363. set: function (value) {
  23364. if (value) {
  23365. this._transparentSortCompareFn = value;
  23366. }
  23367. else {
  23368. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23369. }
  23370. this._renderTransparent = this.renderTransparentSorted;
  23371. },
  23372. enumerable: true,
  23373. configurable: true
  23374. });
  23375. /**
  23376. * Render all the sub meshes contained in the group.
  23377. * @param customRenderFunction Used to override the default render behaviour of the group.
  23378. * @returns true if rendered some submeshes.
  23379. */
  23380. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23381. if (customRenderFunction) {
  23382. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23383. return;
  23384. }
  23385. var engine = this._scene.getEngine();
  23386. // Depth only
  23387. if (this._depthOnlySubMeshes.length !== 0) {
  23388. engine.setColorWrite(false);
  23389. this._renderAlphaTest(this._depthOnlySubMeshes);
  23390. engine.setColorWrite(true);
  23391. }
  23392. // Opaque
  23393. if (this._opaqueSubMeshes.length !== 0) {
  23394. this._renderOpaque(this._opaqueSubMeshes);
  23395. }
  23396. // Alpha test
  23397. if (this._alphaTestSubMeshes.length !== 0) {
  23398. this._renderAlphaTest(this._alphaTestSubMeshes);
  23399. }
  23400. var stencilState = engine.getStencilBuffer();
  23401. engine.setStencilBuffer(false);
  23402. // Sprites
  23403. if (renderSprites) {
  23404. this._renderSprites();
  23405. }
  23406. // Particles
  23407. if (renderParticles) {
  23408. this._renderParticles(activeMeshes);
  23409. }
  23410. if (this.onBeforeTransparentRendering) {
  23411. this.onBeforeTransparentRendering();
  23412. }
  23413. // Transparent
  23414. if (this._transparentSubMeshes.length !== 0) {
  23415. this._renderTransparent(this._transparentSubMeshes);
  23416. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23417. }
  23418. // Set back stencil to false in case it changes before the edge renderer.
  23419. engine.setStencilBuffer(false);
  23420. // Edges
  23421. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23422. this._edgesRenderers.data[edgesRendererIndex].render();
  23423. }
  23424. // Restore Stencil state.
  23425. engine.setStencilBuffer(stencilState);
  23426. };
  23427. /**
  23428. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23429. * @param subMeshes The submeshes to render
  23430. */
  23431. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23432. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23433. };
  23434. /**
  23435. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23436. * @param subMeshes The submeshes to render
  23437. */
  23438. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23439. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23440. };
  23441. /**
  23442. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23443. * @param subMeshes The submeshes to render
  23444. */
  23445. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23446. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23447. };
  23448. /**
  23449. * Renders the submeshes in a specified order.
  23450. * @param subMeshes The submeshes to sort before render
  23451. * @param sortCompareFn The comparison function use to sort
  23452. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23453. * @param transparent Specifies to activate blending if true
  23454. */
  23455. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23456. var subIndex = 0;
  23457. var subMesh;
  23458. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23459. for (; subIndex < subMeshes.length; subIndex++) {
  23460. subMesh = subMeshes.data[subIndex];
  23461. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23462. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23463. }
  23464. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23465. if (sortCompareFn) {
  23466. sortedArray.sort(sortCompareFn);
  23467. }
  23468. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23469. subMesh = sortedArray[subIndex];
  23470. if (transparent) {
  23471. var material = subMesh.getMaterial();
  23472. if (material && material.needDepthPrePass) {
  23473. var engine = material.getScene().getEngine();
  23474. engine.setColorWrite(false);
  23475. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23476. subMesh.render(false);
  23477. engine.setColorWrite(true);
  23478. }
  23479. }
  23480. subMesh.render(transparent);
  23481. }
  23482. };
  23483. /**
  23484. * Renders the submeshes in the order they were dispatched (no sort applied).
  23485. * @param subMeshes The submeshes to render
  23486. */
  23487. RenderingGroup.renderUnsorted = function (subMeshes) {
  23488. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23489. var submesh = subMeshes.data[subIndex];
  23490. submesh.render(false);
  23491. }
  23492. };
  23493. /**
  23494. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23495. * are rendered back to front if in the same alpha index.
  23496. *
  23497. * @param a The first submesh
  23498. * @param b The second submesh
  23499. * @returns The result of the comparison
  23500. */
  23501. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23502. // Alpha index first
  23503. if (a._alphaIndex > b._alphaIndex) {
  23504. return 1;
  23505. }
  23506. if (a._alphaIndex < b._alphaIndex) {
  23507. return -1;
  23508. }
  23509. // Then distance to camera
  23510. return RenderingGroup.backToFrontSortCompare(a, b);
  23511. };
  23512. /**
  23513. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23514. * are rendered back to front.
  23515. *
  23516. * @param a The first submesh
  23517. * @param b The second submesh
  23518. * @returns The result of the comparison
  23519. */
  23520. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23521. // Then distance to camera
  23522. if (a._distanceToCamera < b._distanceToCamera) {
  23523. return 1;
  23524. }
  23525. if (a._distanceToCamera > b._distanceToCamera) {
  23526. return -1;
  23527. }
  23528. return 0;
  23529. };
  23530. /**
  23531. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23532. * are rendered front to back (prevent overdraw).
  23533. *
  23534. * @param a The first submesh
  23535. * @param b The second submesh
  23536. * @returns The result of the comparison
  23537. */
  23538. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23539. // Then distance to camera
  23540. if (a._distanceToCamera < b._distanceToCamera) {
  23541. return -1;
  23542. }
  23543. if (a._distanceToCamera > b._distanceToCamera) {
  23544. return 1;
  23545. }
  23546. return 0;
  23547. };
  23548. /**
  23549. * Resets the different lists of submeshes to prepare a new frame.
  23550. */
  23551. RenderingGroup.prototype.prepare = function () {
  23552. this._opaqueSubMeshes.reset();
  23553. this._transparentSubMeshes.reset();
  23554. this._alphaTestSubMeshes.reset();
  23555. this._depthOnlySubMeshes.reset();
  23556. this._particleSystems.reset();
  23557. this._spriteManagers.reset();
  23558. this._edgesRenderers.reset();
  23559. };
  23560. RenderingGroup.prototype.dispose = function () {
  23561. this._opaqueSubMeshes.dispose();
  23562. this._transparentSubMeshes.dispose();
  23563. this._alphaTestSubMeshes.dispose();
  23564. this._depthOnlySubMeshes.dispose();
  23565. this._particleSystems.dispose();
  23566. this._spriteManagers.dispose();
  23567. this._edgesRenderers.dispose();
  23568. };
  23569. /**
  23570. * Inserts the submesh in its correct queue depending on its material.
  23571. * @param subMesh The submesh to dispatch
  23572. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23573. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23574. */
  23575. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23576. // Get mesh and materials if not provided
  23577. if (mesh === undefined) {
  23578. mesh = subMesh.getMesh();
  23579. }
  23580. if (material === undefined) {
  23581. material = subMesh.getMaterial();
  23582. }
  23583. if (material === null || material === undefined) {
  23584. return;
  23585. }
  23586. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23587. this._transparentSubMeshes.push(subMesh);
  23588. }
  23589. else if (material.needAlphaTesting()) { // Alpha test
  23590. if (material.needDepthPrePass) {
  23591. this._depthOnlySubMeshes.push(subMesh);
  23592. }
  23593. this._alphaTestSubMeshes.push(subMesh);
  23594. }
  23595. else {
  23596. if (material.needDepthPrePass) {
  23597. this._depthOnlySubMeshes.push(subMesh);
  23598. }
  23599. this._opaqueSubMeshes.push(subMesh); // Opaque
  23600. }
  23601. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23602. this._edgesRenderers.push(mesh._edgesRenderer);
  23603. }
  23604. };
  23605. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23606. this._spriteManagers.push(spriteManager);
  23607. };
  23608. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23609. this._particleSystems.push(particleSystem);
  23610. };
  23611. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23612. if (this._particleSystems.length === 0) {
  23613. return;
  23614. }
  23615. // Particles
  23616. var activeCamera = this._scene.activeCamera;
  23617. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23618. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23619. var particleSystem = this._particleSystems.data[particleIndex];
  23620. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23621. continue;
  23622. }
  23623. var emitter = particleSystem.emitter;
  23624. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23625. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23626. }
  23627. }
  23628. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23629. };
  23630. RenderingGroup.prototype._renderSprites = function () {
  23631. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23632. return;
  23633. }
  23634. // Sprites
  23635. var activeCamera = this._scene.activeCamera;
  23636. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23637. for (var id = 0; id < this._spriteManagers.length; id++) {
  23638. var spriteManager = this._spriteManagers.data[id];
  23639. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23640. spriteManager.render();
  23641. }
  23642. }
  23643. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23644. };
  23645. return RenderingGroup;
  23646. }());
  23647. BABYLON.RenderingGroup = RenderingGroup;
  23648. })(BABYLON || (BABYLON = {}));
  23649. //# sourceMappingURL=babylon.renderingGroup.js.map
  23650. var BABYLON;
  23651. (function (BABYLON) {
  23652. /** @hidden */
  23653. var ClickInfo = /** @class */ (function () {
  23654. function ClickInfo() {
  23655. this._singleClick = false;
  23656. this._doubleClick = false;
  23657. this._hasSwiped = false;
  23658. this._ignore = false;
  23659. }
  23660. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23661. get: function () {
  23662. return this._singleClick;
  23663. },
  23664. set: function (b) {
  23665. this._singleClick = b;
  23666. },
  23667. enumerable: true,
  23668. configurable: true
  23669. });
  23670. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23671. get: function () {
  23672. return this._doubleClick;
  23673. },
  23674. set: function (b) {
  23675. this._doubleClick = b;
  23676. },
  23677. enumerable: true,
  23678. configurable: true
  23679. });
  23680. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23681. get: function () {
  23682. return this._hasSwiped;
  23683. },
  23684. set: function (b) {
  23685. this._hasSwiped = b;
  23686. },
  23687. enumerable: true,
  23688. configurable: true
  23689. });
  23690. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23691. get: function () {
  23692. return this._ignore;
  23693. },
  23694. set: function (b) {
  23695. this._ignore = b;
  23696. },
  23697. enumerable: true,
  23698. configurable: true
  23699. });
  23700. return ClickInfo;
  23701. }());
  23702. /**
  23703. * This class is used by the onRenderingGroupObservable
  23704. */
  23705. var RenderingGroupInfo = /** @class */ (function () {
  23706. function RenderingGroupInfo() {
  23707. }
  23708. /**
  23709. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23710. * This stage will be fired no matter what
  23711. */
  23712. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23713. /**
  23714. * Called before opaque object are rendered.
  23715. * This stage will be fired only if there's 3D Opaque content to render
  23716. */
  23717. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23718. /**
  23719. * Called after the opaque objects are rendered and before the transparent ones
  23720. * This stage will be fired only if there's 3D transparent content to render
  23721. */
  23722. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23723. /**
  23724. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23725. * This stage will be fired no matter what
  23726. */
  23727. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23728. return RenderingGroupInfo;
  23729. }());
  23730. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23731. /**
  23732. * Represents a scene to be rendered by the engine.
  23733. * @see http://doc.babylonjs.com/features/scene
  23734. */
  23735. var Scene = /** @class */ (function () {
  23736. /**
  23737. * Creates a new Scene
  23738. * @param engine defines the engine to use to render this scene
  23739. */
  23740. function Scene(engine) {
  23741. // Members
  23742. /**
  23743. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23744. */
  23745. this.autoClear = true;
  23746. /**
  23747. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23748. */
  23749. this.autoClearDepthAndStencil = true;
  23750. /**
  23751. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23752. */
  23753. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23754. /**
  23755. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23756. */
  23757. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23758. this._forceWireframe = false;
  23759. this._forcePointsCloud = false;
  23760. /**
  23761. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23762. */
  23763. this.forceShowBoundingBoxes = false;
  23764. /**
  23765. * Gets or sets a boolean indicating if animations are enabled
  23766. */
  23767. this.animationsEnabled = true;
  23768. this._animationPropertiesOverride = null;
  23769. /**
  23770. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23771. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23772. */
  23773. this.useConstantAnimationDeltaTime = false;
  23774. /**
  23775. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23776. * Please note that it requires to run a ray cast through the scene on every frame
  23777. */
  23778. this.constantlyUpdateMeshUnderPointer = false;
  23779. /**
  23780. * Defines the HTML cursor to use when hovering over interactive elements
  23781. */
  23782. this.hoverCursor = "pointer";
  23783. /**
  23784. * Defines the HTML default cursor to use (empty by default)
  23785. */
  23786. this.defaultCursor = "";
  23787. /**
  23788. * This is used to call preventDefault() on pointer down
  23789. * in order to block unwanted artifacts like system double clicks
  23790. */
  23791. this.preventDefaultOnPointerDown = true;
  23792. // Metadata
  23793. /**
  23794. * Gets or sets user defined metadata
  23795. */
  23796. this.metadata = null;
  23797. /**
  23798. * Use this array to add regular expressions used to disable offline support for specific urls
  23799. */
  23800. this.disableOfflineSupportExceptionRules = new Array();
  23801. /**
  23802. * An event triggered when the scene is disposed.
  23803. */
  23804. this.onDisposeObservable = new BABYLON.Observable();
  23805. this._onDisposeObserver = null;
  23806. /**
  23807. * An event triggered before rendering the scene (right after animations and physics)
  23808. */
  23809. this.onBeforeRenderObservable = new BABYLON.Observable();
  23810. this._onBeforeRenderObserver = null;
  23811. /**
  23812. * An event triggered after rendering the scene
  23813. */
  23814. this.onAfterRenderObservable = new BABYLON.Observable();
  23815. this._onAfterRenderObserver = null;
  23816. /**
  23817. * An event triggered before animating the scene
  23818. */
  23819. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23820. /**
  23821. * An event triggered after animations processing
  23822. */
  23823. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23824. /**
  23825. * An event triggered before draw calls are ready to be sent
  23826. */
  23827. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23828. /**
  23829. * An event triggered after draw calls have been sent
  23830. */
  23831. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23832. /**
  23833. * An event triggered when physic simulation is about to be run
  23834. */
  23835. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23836. /**
  23837. * An event triggered when physic simulation has been done
  23838. */
  23839. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23840. /**
  23841. * An event triggered when the scene is ready
  23842. */
  23843. this.onReadyObservable = new BABYLON.Observable();
  23844. /**
  23845. * An event triggered before rendering a camera
  23846. */
  23847. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23848. this._onBeforeCameraRenderObserver = null;
  23849. /**
  23850. * An event triggered after rendering a camera
  23851. */
  23852. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23853. this._onAfterCameraRenderObserver = null;
  23854. /**
  23855. * An event triggered when active meshes evaluation is about to start
  23856. */
  23857. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23858. /**
  23859. * An event triggered when active meshes evaluation is done
  23860. */
  23861. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23862. /**
  23863. * An event triggered when particles rendering is about to start
  23864. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23865. */
  23866. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23867. /**
  23868. * An event triggered when particles rendering is done
  23869. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23870. */
  23871. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23872. /**
  23873. * An event triggered when sprites rendering is about to start
  23874. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23875. */
  23876. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23877. /**
  23878. * An event triggered when sprites rendering is done
  23879. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23880. */
  23881. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23882. /**
  23883. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23884. */
  23885. this.onDataLoadedObservable = new BABYLON.Observable();
  23886. /**
  23887. * An event triggered when a camera is created
  23888. */
  23889. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23890. /**
  23891. * An event triggered when a camera is removed
  23892. */
  23893. this.onCameraRemovedObservable = new BABYLON.Observable();
  23894. /**
  23895. * An event triggered when a light is created
  23896. */
  23897. this.onNewLightAddedObservable = new BABYLON.Observable();
  23898. /**
  23899. * An event triggered when a light is removed
  23900. */
  23901. this.onLightRemovedObservable = new BABYLON.Observable();
  23902. /**
  23903. * An event triggered when a geometry is created
  23904. */
  23905. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23906. /**
  23907. * An event triggered when a geometry is removed
  23908. */
  23909. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23910. /**
  23911. * An event triggered when a transform node is created
  23912. */
  23913. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23914. /**
  23915. * An event triggered when a transform node is removed
  23916. */
  23917. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23918. /**
  23919. * An event triggered when a mesh is created
  23920. */
  23921. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23922. /**
  23923. * An event triggered when a mesh is removed
  23924. */
  23925. this.onMeshRemovedObservable = new BABYLON.Observable();
  23926. /**
  23927. * An event triggered when render targets are about to be rendered
  23928. * Can happen multiple times per frame.
  23929. */
  23930. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23931. /**
  23932. * An event triggered when render targets were rendered.
  23933. * Can happen multiple times per frame.
  23934. */
  23935. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23936. /**
  23937. * An event triggered before calculating deterministic simulation step
  23938. */
  23939. this.onBeforeStepObservable = new BABYLON.Observable();
  23940. /**
  23941. * An event triggered after calculating deterministic simulation step
  23942. */
  23943. this.onAfterStepObservable = new BABYLON.Observable();
  23944. /**
  23945. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23946. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23947. * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)
  23948. */
  23949. this.onRenderingGroupObservable = new BABYLON.Observable();
  23950. // Animations
  23951. /**
  23952. * Gets a list of Animations associated with the scene
  23953. */
  23954. this.animations = [];
  23955. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23956. /**
  23957. * This observable event is triggered when any ponter event is triggered. It is registered during Scene.attachControl() and it is called BEFORE the 3D engine process anything (mesh/sprite picking for instance).
  23958. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23959. */
  23960. this.onPrePointerObservable = new BABYLON.Observable();
  23961. /**
  23962. * Observable event triggered each time an input event is received from the rendering canvas
  23963. */
  23964. this.onPointerObservable = new BABYLON.Observable();
  23965. this._meshPickProceed = false;
  23966. this._currentPickResult = null;
  23967. this._previousPickResult = null;
  23968. this._totalPointersPressed = 0;
  23969. this._doubleClickOccured = false;
  23970. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23971. this.cameraToUseForPointers = null;
  23972. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23973. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23974. this._startingPointerTime = 0;
  23975. this._previousStartingPointerTime = 0;
  23976. this._pointerCaptures = {};
  23977. // Deterministic lockstep
  23978. this._timeAccumulator = 0;
  23979. this._currentStepId = 0;
  23980. this._currentInternalStep = 0;
  23981. // Keyboard
  23982. /**
  23983. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23984. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23985. */
  23986. this.onPreKeyboardObservable = new BABYLON.Observable();
  23987. /**
  23988. * Observable event triggered each time an keyboard event is received from the hosting window
  23989. */
  23990. this.onKeyboardObservable = new BABYLON.Observable();
  23991. // Coordinates system
  23992. this._useRightHandedSystem = false;
  23993. // Fog
  23994. this._fogEnabled = true;
  23995. this._fogMode = Scene.FOGMODE_NONE;
  23996. /**
  23997. * Gets or sets the fog color to use
  23998. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23999. */
  24000. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24001. /**
  24002. * Gets or sets the fog density to use
  24003. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24004. */
  24005. this.fogDensity = 0.1;
  24006. /**
  24007. * Gets or sets the fog start distance to use
  24008. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24009. */
  24010. this.fogStart = 0;
  24011. /**
  24012. * Gets or sets the fog end distance to use
  24013. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24014. */
  24015. this.fogEnd = 1000.0;
  24016. // Lights
  24017. this._shadowsEnabled = true;
  24018. this._lightsEnabled = true;
  24019. /**
  24020. * All of the lights added to this scene
  24021. * @see http://doc.babylonjs.com/babylon101/lights
  24022. */
  24023. this.lights = new Array();
  24024. // Cameras
  24025. /** All of the cameras added to this scene.
  24026. * @see http://doc.babylonjs.com/babylon101/cameras
  24027. */
  24028. this.cameras = new Array();
  24029. /** All of the active cameras added to this scene. */
  24030. this.activeCameras = new Array();
  24031. // Meshes
  24032. /**
  24033. * All of the tranform nodes added to this scene
  24034. * @see http://doc.babylonjs.com/how_to/transformnode
  24035. */
  24036. this.transformNodes = new Array();
  24037. /**
  24038. * All of the (abstract) meshes added to this scene
  24039. */
  24040. this.meshes = new Array();
  24041. /**
  24042. * All of the animation groups added to this scene
  24043. * @see http://doc.babylonjs.com/how_to/group
  24044. */
  24045. this.animationGroups = new Array();
  24046. // Geometries
  24047. this._geometries = new Array();
  24048. /**
  24049. * All of the materials added to this scene
  24050. * @see http://doc.babylonjs.com/babylon101/materials
  24051. */
  24052. this.materials = new Array();
  24053. /**
  24054. * All of the multi-materials added to this scene
  24055. * @see http://doc.babylonjs.com/how_to/multi_materials
  24056. */
  24057. this.multiMaterials = new Array();
  24058. // Textures
  24059. this._texturesEnabled = true;
  24060. /**
  24061. * All of the textures added to this scene
  24062. */
  24063. this.textures = new Array();
  24064. // Particles
  24065. /**
  24066. * Gets or sets a boolean indicating if particles are enabled on this scene
  24067. */
  24068. this.particlesEnabled = true;
  24069. /**
  24070. * All of the particle systems added to this scene
  24071. * @see http://doc.babylonjs.com/babylon101/particles
  24072. */
  24073. this.particleSystems = new Array();
  24074. // Sprites
  24075. /**
  24076. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24077. */
  24078. this.spritesEnabled = true;
  24079. /**
  24080. * All of the sprite managers added to this scene
  24081. * @see http://doc.babylonjs.com/babylon101/sprites
  24082. */
  24083. this.spriteManagers = new Array();
  24084. /**
  24085. * The list of layers (background and foreground) of the scene
  24086. */
  24087. this.layers = new Array();
  24088. /**
  24089. * The list of effect layers (highlights/glow) added to the scene
  24090. * @see http://doc.babylonjs.com/how_to/highlight_layer
  24091. * @see http://doc.babylonjs.com/how_to/glow_layer
  24092. */
  24093. this.effectLayers = new Array();
  24094. // Skeletons
  24095. this._skeletonsEnabled = true;
  24096. /**
  24097. * The list of skeletons added to the scene
  24098. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24099. */
  24100. this.skeletons = new Array();
  24101. // Morph targets
  24102. /**
  24103. * The list of morph target managers added to the scene
  24104. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24105. */
  24106. this.morphTargetManagers = new Array();
  24107. // Lens flares
  24108. /**
  24109. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24110. */
  24111. this.lensFlaresEnabled = true;
  24112. /**
  24113. * The list of lens flare system added to the scene
  24114. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24115. */
  24116. this.lensFlareSystems = new Array();
  24117. // Collisions
  24118. /**
  24119. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24120. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24121. */
  24122. this.collisionsEnabled = true;
  24123. /**
  24124. * Defines the gravity applied to this scene (used only for collisions)
  24125. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24126. */
  24127. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24128. // Postprocesses
  24129. /**
  24130. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24131. */
  24132. this.postProcessesEnabled = true;
  24133. /**
  24134. * The list of postprocesses added to the scene
  24135. */
  24136. this.postProcesses = new Array();
  24137. // Customs render targets
  24138. /**
  24139. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24140. */
  24141. this.renderTargetsEnabled = true;
  24142. /**
  24143. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24144. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24145. */
  24146. this.dumpNextRenderTargets = false;
  24147. /**
  24148. * The list of user defined render targets added to the scene
  24149. */
  24150. this.customRenderTargets = new Array();
  24151. /**
  24152. * Gets the list of meshes imported to the scene through SceneLoader
  24153. */
  24154. this.importedMeshesFiles = new Array();
  24155. // Probes
  24156. /**
  24157. * Gets or sets a boolean indicating if probes are enabled on this scene
  24158. */
  24159. this.probesEnabled = true;
  24160. /**
  24161. * The list of reflection probes added to the scene
  24162. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24163. */
  24164. this.reflectionProbes = new Array();
  24165. /** @hidden */
  24166. this._actionManagers = new Array();
  24167. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24168. // Procedural textures
  24169. /**
  24170. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24171. */
  24172. this.proceduralTexturesEnabled = true;
  24173. /**
  24174. * The list of procedural textures added to the scene
  24175. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24176. */
  24177. this.proceduralTextures = new Array();
  24178. /**
  24179. * The list of sound tracks added to the scene
  24180. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24181. */
  24182. this.soundTracks = new Array();
  24183. this._audioEnabled = true;
  24184. this._headphone = false;
  24185. // Performance counters
  24186. this._totalVertices = new BABYLON.PerfCounter();
  24187. /** @hidden */
  24188. this._activeIndices = new BABYLON.PerfCounter();
  24189. /** @hidden */
  24190. this._activeParticles = new BABYLON.PerfCounter();
  24191. /** @hidden */
  24192. this._activeBones = new BABYLON.PerfCounter();
  24193. this._animationTime = 0;
  24194. /**
  24195. * Gets or sets a general scale for animation speed
  24196. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24197. */
  24198. this.animationTimeScale = 1;
  24199. this._renderId = 0;
  24200. this._executeWhenReadyTimeoutId = -1;
  24201. this._intermediateRendering = false;
  24202. this._viewUpdateFlag = -1;
  24203. this._projectionUpdateFlag = -1;
  24204. this._alternateViewUpdateFlag = -1;
  24205. this._alternateProjectionUpdateFlag = -1;
  24206. /** @hidden */
  24207. this._toBeDisposed = new BABYLON.SmartArray(256);
  24208. this._activeRequests = new Array();
  24209. this._pendingData = new Array();
  24210. this._isDisposed = false;
  24211. /**
  24212. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24213. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24214. */
  24215. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24216. this._activeMeshes = new BABYLON.SmartArray(256);
  24217. this._processedMaterials = new BABYLON.SmartArray(256);
  24218. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24219. /** @hidden */
  24220. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24221. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24222. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24223. /** @hidden */
  24224. this._activeAnimatables = new Array();
  24225. this._transformMatrix = BABYLON.Matrix.Zero();
  24226. this._useAlternateCameraConfiguration = false;
  24227. this._alternateRendering = false;
  24228. /**
  24229. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24230. * This is useful if there are more lights that the maximum simulteanous authorized
  24231. */
  24232. this.requireLightSorting = false;
  24233. this._depthRenderer = {};
  24234. this._activeMeshesFrozen = false;
  24235. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24236. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24237. this._engine.scenes.push(this);
  24238. this._uid = null;
  24239. this._renderingManager = new BABYLON.RenderingManager(this);
  24240. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24241. if (BABYLON.OutlineRenderer) {
  24242. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24243. }
  24244. if (BABYLON.Tools.IsWindowObjectExist()) {
  24245. this.attachControl();
  24246. }
  24247. //simplification queue
  24248. if (BABYLON.SimplificationQueue) {
  24249. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24250. }
  24251. //collision coordinator initialization. For now legacy per default.
  24252. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24253. // Uniform Buffer
  24254. this._createUbo();
  24255. // Default Image processing definition.
  24256. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24257. }
  24258. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24259. /** The fog is deactivated */
  24260. get: function () {
  24261. return Scene._FOGMODE_NONE;
  24262. },
  24263. enumerable: true,
  24264. configurable: true
  24265. });
  24266. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24267. /** The fog density is following an exponential function */
  24268. get: function () {
  24269. return Scene._FOGMODE_EXP;
  24270. },
  24271. enumerable: true,
  24272. configurable: true
  24273. });
  24274. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24275. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24276. get: function () {
  24277. return Scene._FOGMODE_EXP2;
  24278. },
  24279. enumerable: true,
  24280. configurable: true
  24281. });
  24282. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24283. /** The fog density is following a linear function. */
  24284. get: function () {
  24285. return Scene._FOGMODE_LINEAR;
  24286. },
  24287. enumerable: true,
  24288. configurable: true
  24289. });
  24290. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24291. /**
  24292. * Texture used in all pbr material as the reflection texture.
  24293. * As in the majority of the scene they are the same (exception for multi room and so on),
  24294. * this is easier to reference from here than from all the materials.
  24295. */
  24296. get: function () {
  24297. return this._environmentTexture;
  24298. },
  24299. /**
  24300. * Texture used in all pbr material as the reflection texture.
  24301. * As in the majority of the scene they are the same (exception for multi room and so on),
  24302. * this is easier to set here than in all the materials.
  24303. */
  24304. set: function (value) {
  24305. if (this._environmentTexture === value) {
  24306. return;
  24307. }
  24308. this._environmentTexture = value;
  24309. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24310. },
  24311. enumerable: true,
  24312. configurable: true
  24313. });
  24314. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24315. /**
  24316. * Default image processing configuration used either in the rendering
  24317. * Forward main pass or through the imageProcessingPostProcess if present.
  24318. * As in the majority of the scene they are the same (exception for multi camera),
  24319. * this is easier to reference from here than from all the materials and post process.
  24320. *
  24321. * No setter as we it is a shared configuration, you can set the values instead.
  24322. */
  24323. get: function () {
  24324. return this._imageProcessingConfiguration;
  24325. },
  24326. enumerable: true,
  24327. configurable: true
  24328. });
  24329. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24330. get: function () {
  24331. return this._forceWireframe;
  24332. },
  24333. /**
  24334. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24335. */
  24336. set: function (value) {
  24337. if (this._forceWireframe === value) {
  24338. return;
  24339. }
  24340. this._forceWireframe = value;
  24341. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24342. },
  24343. enumerable: true,
  24344. configurable: true
  24345. });
  24346. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24347. get: function () {
  24348. return this._forcePointsCloud;
  24349. },
  24350. /**
  24351. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24352. */
  24353. set: function (value) {
  24354. if (this._forcePointsCloud === value) {
  24355. return;
  24356. }
  24357. this._forcePointsCloud = value;
  24358. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24359. },
  24360. enumerable: true,
  24361. configurable: true
  24362. });
  24363. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24364. /**
  24365. * Gets or sets the animation properties override
  24366. */
  24367. get: function () {
  24368. return this._animationPropertiesOverride;
  24369. },
  24370. set: function (value) {
  24371. this._animationPropertiesOverride = value;
  24372. },
  24373. enumerable: true,
  24374. configurable: true
  24375. });
  24376. Object.defineProperty(Scene.prototype, "onDispose", {
  24377. /** Sets a function to be executed when this scene is disposed. */
  24378. set: function (callback) {
  24379. if (this._onDisposeObserver) {
  24380. this.onDisposeObservable.remove(this._onDisposeObserver);
  24381. }
  24382. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24383. },
  24384. enumerable: true,
  24385. configurable: true
  24386. });
  24387. Object.defineProperty(Scene.prototype, "beforeRender", {
  24388. /** Sets a function to be executed before rendering this scene */
  24389. set: function (callback) {
  24390. if (this._onBeforeRenderObserver) {
  24391. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24392. }
  24393. if (callback) {
  24394. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24395. }
  24396. },
  24397. enumerable: true,
  24398. configurable: true
  24399. });
  24400. Object.defineProperty(Scene.prototype, "afterRender", {
  24401. /** Sets a function to be executed after rendering this scene */
  24402. set: function (callback) {
  24403. if (this._onAfterRenderObserver) {
  24404. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24405. }
  24406. if (callback) {
  24407. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24408. }
  24409. },
  24410. enumerable: true,
  24411. configurable: true
  24412. });
  24413. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24414. /** Sets a function to be executed before rendering a camera*/
  24415. set: function (callback) {
  24416. if (this._onBeforeCameraRenderObserver) {
  24417. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24418. }
  24419. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24420. },
  24421. enumerable: true,
  24422. configurable: true
  24423. });
  24424. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24425. /** Sets a function to be executed after rendering a camera*/
  24426. set: function (callback) {
  24427. if (this._onAfterCameraRenderObserver) {
  24428. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24429. }
  24430. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24431. },
  24432. enumerable: true,
  24433. configurable: true
  24434. });
  24435. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24436. /**
  24437. * Gets the gamepad manager associated with the scene
  24438. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24439. */
  24440. get: function () {
  24441. if (!this._gamepadManager) {
  24442. this._gamepadManager = new BABYLON.GamepadManager(this);
  24443. }
  24444. return this._gamepadManager;
  24445. },
  24446. enumerable: true,
  24447. configurable: true
  24448. });
  24449. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24450. /**
  24451. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24452. */
  24453. get: function () {
  24454. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24455. },
  24456. enumerable: true,
  24457. configurable: true
  24458. });
  24459. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24460. get: function () {
  24461. return this._useRightHandedSystem;
  24462. },
  24463. /**
  24464. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24465. */
  24466. set: function (value) {
  24467. if (this._useRightHandedSystem === value) {
  24468. return;
  24469. }
  24470. this._useRightHandedSystem = value;
  24471. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24472. },
  24473. enumerable: true,
  24474. configurable: true
  24475. });
  24476. /**
  24477. * Sets the step Id used by deterministic lock step
  24478. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24479. * @param newStepId defines the step Id
  24480. */
  24481. Scene.prototype.setStepId = function (newStepId) {
  24482. this._currentStepId = newStepId;
  24483. };
  24484. ;
  24485. /**
  24486. * Gets the step Id used by deterministic lock step
  24487. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24488. * @returns the step Id
  24489. */
  24490. Scene.prototype.getStepId = function () {
  24491. return this._currentStepId;
  24492. };
  24493. ;
  24494. /**
  24495. * Gets the internal step used by deterministic lock step
  24496. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24497. * @returns the internal step
  24498. */
  24499. Scene.prototype.getInternalStep = function () {
  24500. return this._currentInternalStep;
  24501. };
  24502. ;
  24503. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24504. get: function () {
  24505. return this._fogEnabled;
  24506. },
  24507. /**
  24508. * Gets or sets a boolean indicating if fog is enabled on this scene
  24509. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24510. */
  24511. set: function (value) {
  24512. if (this._fogEnabled === value) {
  24513. return;
  24514. }
  24515. this._fogEnabled = value;
  24516. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24517. },
  24518. enumerable: true,
  24519. configurable: true
  24520. });
  24521. Object.defineProperty(Scene.prototype, "fogMode", {
  24522. get: function () {
  24523. return this._fogMode;
  24524. },
  24525. /**
  24526. * Gets or sets the fog mode to use
  24527. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24528. */
  24529. set: function (value) {
  24530. if (this._fogMode === value) {
  24531. return;
  24532. }
  24533. this._fogMode = value;
  24534. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24535. },
  24536. enumerable: true,
  24537. configurable: true
  24538. });
  24539. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24540. get: function () {
  24541. return this._shadowsEnabled;
  24542. },
  24543. /**
  24544. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24545. */
  24546. set: function (value) {
  24547. if (this._shadowsEnabled === value) {
  24548. return;
  24549. }
  24550. this._shadowsEnabled = value;
  24551. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24552. },
  24553. enumerable: true,
  24554. configurable: true
  24555. });
  24556. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24557. get: function () {
  24558. return this._lightsEnabled;
  24559. },
  24560. /**
  24561. * Gets or sets a boolean indicating if lights are enabled on this scene
  24562. */
  24563. set: function (value) {
  24564. if (this._lightsEnabled === value) {
  24565. return;
  24566. }
  24567. this._lightsEnabled = value;
  24568. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24569. },
  24570. enumerable: true,
  24571. configurable: true
  24572. });
  24573. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24574. /** The default material used on meshes when no material is affected */
  24575. get: function () {
  24576. if (!this._defaultMaterial) {
  24577. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24578. }
  24579. return this._defaultMaterial;
  24580. },
  24581. /** The default material used on meshes when no material is affected */
  24582. set: function (value) {
  24583. this._defaultMaterial = value;
  24584. },
  24585. enumerable: true,
  24586. configurable: true
  24587. });
  24588. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24589. get: function () {
  24590. return this._texturesEnabled;
  24591. },
  24592. /**
  24593. * Gets or sets a boolean indicating if textures are enabled on this scene
  24594. */
  24595. set: function (value) {
  24596. if (this._texturesEnabled === value) {
  24597. return;
  24598. }
  24599. this._texturesEnabled = value;
  24600. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24601. },
  24602. enumerable: true,
  24603. configurable: true
  24604. });
  24605. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24606. get: function () {
  24607. return this._skeletonsEnabled;
  24608. },
  24609. /**
  24610. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24611. */
  24612. set: function (value) {
  24613. if (this._skeletonsEnabled === value) {
  24614. return;
  24615. }
  24616. this._skeletonsEnabled = value;
  24617. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24618. },
  24619. enumerable: true,
  24620. configurable: true
  24621. });
  24622. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24623. /**
  24624. * Gets the postprocess render pipeline manager
  24625. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24626. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24627. */
  24628. get: function () {
  24629. if (!this._postProcessRenderPipelineManager) {
  24630. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24631. }
  24632. return this._postProcessRenderPipelineManager;
  24633. },
  24634. enumerable: true,
  24635. configurable: true
  24636. });
  24637. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24638. /**
  24639. * Gets the main soundtrack associated with the scene
  24640. */
  24641. get: function () {
  24642. if (!this._mainSoundTrack) {
  24643. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24644. }
  24645. return this._mainSoundTrack;
  24646. },
  24647. enumerable: true,
  24648. configurable: true
  24649. });
  24650. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24651. /** @hidden */
  24652. get: function () {
  24653. return this._alternateRendering;
  24654. },
  24655. enumerable: true,
  24656. configurable: true
  24657. });
  24658. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24659. /**
  24660. * Gets the list of frustum planes (built from the active camera)
  24661. */
  24662. get: function () {
  24663. return this._frustumPlanes;
  24664. },
  24665. enumerable: true,
  24666. configurable: true
  24667. });
  24668. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24669. /**
  24670. * Gets the current geometry buffer associated to the scene.
  24671. */
  24672. get: function () {
  24673. return this._geometryBufferRenderer;
  24674. },
  24675. /**
  24676. * Sets the current geometry buffer for the scene.
  24677. */
  24678. set: function (geometryBufferRenderer) {
  24679. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24680. this._geometryBufferRenderer = geometryBufferRenderer;
  24681. }
  24682. },
  24683. enumerable: true,
  24684. configurable: true
  24685. });
  24686. Object.defineProperty(Scene.prototype, "debugLayer", {
  24687. /**
  24688. * Gets the debug layer associated with the scene
  24689. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24690. */
  24691. get: function () {
  24692. if (!this._debugLayer) {
  24693. this._debugLayer = new BABYLON.DebugLayer(this);
  24694. }
  24695. return this._debugLayer;
  24696. },
  24697. enumerable: true,
  24698. configurable: true
  24699. });
  24700. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24701. /**
  24702. * Gets a boolean indicating if collisions are processed on a web worker
  24703. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24704. */
  24705. get: function () {
  24706. return this._workerCollisions;
  24707. },
  24708. set: function (enabled) {
  24709. if (!BABYLON.CollisionCoordinatorLegacy) {
  24710. return;
  24711. }
  24712. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24713. this._workerCollisions = enabled;
  24714. if (this.collisionCoordinator) {
  24715. this.collisionCoordinator.destroy();
  24716. }
  24717. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24718. this.collisionCoordinator.init(this);
  24719. },
  24720. enumerable: true,
  24721. configurable: true
  24722. });
  24723. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24724. /**
  24725. * Gets the octree used to boost mesh selection (picking)
  24726. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24727. */
  24728. get: function () {
  24729. return this._selectionOctree;
  24730. },
  24731. enumerable: true,
  24732. configurable: true
  24733. });
  24734. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24735. /**
  24736. * Gets the mesh that is currently under the pointer
  24737. */
  24738. get: function () {
  24739. return this._pointerOverMesh;
  24740. },
  24741. enumerable: true,
  24742. configurable: true
  24743. });
  24744. Object.defineProperty(Scene.prototype, "pointerX", {
  24745. /**
  24746. * Gets the current on-screen X position of the pointer
  24747. */
  24748. get: function () {
  24749. return this._pointerX;
  24750. },
  24751. enumerable: true,
  24752. configurable: true
  24753. });
  24754. Object.defineProperty(Scene.prototype, "pointerY", {
  24755. /**
  24756. * Gets the current on-screen Y position of the pointer
  24757. */
  24758. get: function () {
  24759. return this._pointerY;
  24760. },
  24761. enumerable: true,
  24762. configurable: true
  24763. });
  24764. /**
  24765. * Gets the cached material (ie. the latest rendered one)
  24766. * @returns the cached material
  24767. */
  24768. Scene.prototype.getCachedMaterial = function () {
  24769. return this._cachedMaterial;
  24770. };
  24771. /**
  24772. * Gets the cached effect (ie. the latest rendered one)
  24773. * @returns the cached effect
  24774. */
  24775. Scene.prototype.getCachedEffect = function () {
  24776. return this._cachedEffect;
  24777. };
  24778. /**
  24779. * Gets the cached visibility state (ie. the latest rendered one)
  24780. * @returns the cached visibility state
  24781. */
  24782. Scene.prototype.getCachedVisibility = function () {
  24783. return this._cachedVisibility;
  24784. };
  24785. /**
  24786. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24787. * @param material defines the current material
  24788. * @param effect defines the current effect
  24789. * @param visibility defines the current visibility state
  24790. * @returns true if one parameter is not cached
  24791. */
  24792. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24793. if (visibility === void 0) { visibility = 1; }
  24794. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24795. };
  24796. /**
  24797. * Gets the bounding box renderer associated with the scene
  24798. * @returns a BoundingBoxRenderer
  24799. */
  24800. Scene.prototype.getBoundingBoxRenderer = function () {
  24801. if (!this._boundingBoxRenderer) {
  24802. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24803. }
  24804. return this._boundingBoxRenderer;
  24805. };
  24806. /**
  24807. * Gets the outline renderer associated with the scene
  24808. * @returns a OutlineRenderer
  24809. */
  24810. Scene.prototype.getOutlineRenderer = function () {
  24811. return this._outlineRenderer;
  24812. };
  24813. /**
  24814. * Gets the engine associated with the scene
  24815. * @returns an Engine
  24816. */
  24817. Scene.prototype.getEngine = function () {
  24818. return this._engine;
  24819. };
  24820. /**
  24821. * Gets the total number of vertices rendered per frame
  24822. * @returns the total number of vertices rendered per frame
  24823. */
  24824. Scene.prototype.getTotalVertices = function () {
  24825. return this._totalVertices.current;
  24826. };
  24827. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24828. /**
  24829. * Gets the performance counter for total vertices
  24830. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24831. */
  24832. get: function () {
  24833. return this._totalVertices;
  24834. },
  24835. enumerable: true,
  24836. configurable: true
  24837. });
  24838. /**
  24839. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24840. * @returns the total number of active indices rendered per frame
  24841. */
  24842. Scene.prototype.getActiveIndices = function () {
  24843. return this._activeIndices.current;
  24844. };
  24845. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24846. /**
  24847. * Gets the performance counter for active indices
  24848. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24849. */
  24850. get: function () {
  24851. return this._activeIndices;
  24852. },
  24853. enumerable: true,
  24854. configurable: true
  24855. });
  24856. /**
  24857. * Gets the total number of active particles rendered per frame
  24858. * @returns the total number of active particles rendered per frame
  24859. */
  24860. Scene.prototype.getActiveParticles = function () {
  24861. return this._activeParticles.current;
  24862. };
  24863. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24864. /**
  24865. * Gets the performance counter for active particles
  24866. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24867. */
  24868. get: function () {
  24869. return this._activeParticles;
  24870. },
  24871. enumerable: true,
  24872. configurable: true
  24873. });
  24874. /**
  24875. * Gets the total number of active bones rendered per frame
  24876. * @returns the total number of active bones rendered per frame
  24877. */
  24878. Scene.prototype.getActiveBones = function () {
  24879. return this._activeBones.current;
  24880. };
  24881. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24882. /**
  24883. * Gets the performance counter for active bones
  24884. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24885. */
  24886. get: function () {
  24887. return this._activeBones;
  24888. },
  24889. enumerable: true,
  24890. configurable: true
  24891. });
  24892. /** @hidden */
  24893. Scene.prototype.getInterFramePerfCounter = function () {
  24894. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24895. return 0;
  24896. };
  24897. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24898. /** @hidden */
  24899. get: function () {
  24900. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24901. return null;
  24902. },
  24903. enumerable: true,
  24904. configurable: true
  24905. });
  24906. /** @hidden */
  24907. Scene.prototype.getLastFrameDuration = function () {
  24908. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24909. return 0;
  24910. };
  24911. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24912. /** @hidden */
  24913. get: function () {
  24914. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24915. return null;
  24916. },
  24917. enumerable: true,
  24918. configurable: true
  24919. });
  24920. /** @hidden */
  24921. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24922. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24923. return 0;
  24924. };
  24925. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24926. /** @hidden */
  24927. get: function () {
  24928. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24929. return null;
  24930. },
  24931. enumerable: true,
  24932. configurable: true
  24933. });
  24934. /**
  24935. * Gets the array of active meshes
  24936. * @returns an array of AbstractMesh
  24937. */
  24938. Scene.prototype.getActiveMeshes = function () {
  24939. return this._activeMeshes;
  24940. };
  24941. /** @hidden */
  24942. Scene.prototype.getRenderTargetsDuration = function () {
  24943. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24944. return 0;
  24945. };
  24946. /** @hidden */
  24947. Scene.prototype.getRenderDuration = function () {
  24948. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24949. return 0;
  24950. };
  24951. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24952. /** @hidden */
  24953. get: function () {
  24954. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24955. return null;
  24956. },
  24957. enumerable: true,
  24958. configurable: true
  24959. });
  24960. /** @hidden */
  24961. Scene.prototype.getParticlesDuration = function () {
  24962. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24963. return 0;
  24964. };
  24965. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24966. /** @hidden */
  24967. get: function () {
  24968. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24969. return null;
  24970. },
  24971. enumerable: true,
  24972. configurable: true
  24973. });
  24974. /** @hidden */
  24975. Scene.prototype.getSpritesDuration = function () {
  24976. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24977. return 0;
  24978. };
  24979. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24980. /** @hidden */
  24981. get: function () {
  24982. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24983. return null;
  24984. },
  24985. enumerable: true,
  24986. configurable: true
  24987. });
  24988. /**
  24989. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24990. * @returns a number
  24991. */
  24992. Scene.prototype.getAnimationRatio = function () {
  24993. return this._animationRatio;
  24994. };
  24995. /**
  24996. * Gets an unique Id for the current frame
  24997. * @returns a number
  24998. */
  24999. Scene.prototype.getRenderId = function () {
  25000. return this._renderId;
  25001. };
  25002. /** Call this function if you want to manually increment the render Id*/
  25003. Scene.prototype.incrementRenderId = function () {
  25004. this._renderId++;
  25005. };
  25006. Scene.prototype._updatePointerPosition = function (evt) {
  25007. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25008. if (!canvasRect) {
  25009. return;
  25010. }
  25011. this._pointerX = evt.clientX - canvasRect.left;
  25012. this._pointerY = evt.clientY - canvasRect.top;
  25013. this._unTranslatedPointerX = this._pointerX;
  25014. this._unTranslatedPointerY = this._pointerY;
  25015. };
  25016. Scene.prototype._createUbo = function () {
  25017. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25018. this._sceneUbo.addUniform("viewProjection", 16);
  25019. this._sceneUbo.addUniform("view", 16);
  25020. };
  25021. Scene.prototype._createAlternateUbo = function () {
  25022. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25023. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25024. this._alternateSceneUbo.addUniform("view", 16);
  25025. };
  25026. // Pointers handling
  25027. /**
  25028. * Use this method to simulate a pointer move on a mesh
  25029. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25030. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25031. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25032. * @returns the current scene
  25033. */
  25034. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25035. var evt = new PointerEvent("pointermove", pointerEventInit);
  25036. return this._processPointerMove(pickResult, evt);
  25037. };
  25038. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25039. var canvas = this._engine.getRenderingCanvas();
  25040. if (!canvas) {
  25041. return this;
  25042. }
  25043. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25044. this.setPointerOverSprite(null);
  25045. this.setPointerOverMesh(pickResult.pickedMesh);
  25046. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25047. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25048. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25049. }
  25050. else {
  25051. canvas.style.cursor = this.hoverCursor;
  25052. }
  25053. }
  25054. else {
  25055. canvas.style.cursor = this.defaultCursor;
  25056. }
  25057. }
  25058. else {
  25059. this.setPointerOverMesh(null);
  25060. // Sprites
  25061. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25062. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25063. this.setPointerOverSprite(pickResult.pickedSprite);
  25064. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25065. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25066. }
  25067. else {
  25068. canvas.style.cursor = this.hoverCursor;
  25069. }
  25070. }
  25071. else {
  25072. this.setPointerOverSprite(null);
  25073. // Restore pointer
  25074. canvas.style.cursor = this.defaultCursor;
  25075. }
  25076. }
  25077. if (pickResult) {
  25078. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25079. if (this.onPointerMove) {
  25080. this.onPointerMove(evt, pickResult, type);
  25081. }
  25082. if (this.onPointerObservable.hasObservers()) {
  25083. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25084. this.onPointerObservable.notifyObservers(pi, type);
  25085. }
  25086. }
  25087. return this;
  25088. };
  25089. /**
  25090. * Use this method to simulate a pointer down on a mesh
  25091. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25092. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25093. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25094. * @returns the current scene
  25095. */
  25096. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25097. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25098. return this._processPointerDown(pickResult, evt);
  25099. };
  25100. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25101. var _this = this;
  25102. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25103. this._pickedDownMesh = pickResult.pickedMesh;
  25104. var actionManager = pickResult.pickedMesh.actionManager;
  25105. if (actionManager) {
  25106. if (actionManager.hasPickTriggers) {
  25107. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25108. switch (evt.button) {
  25109. case 0:
  25110. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25111. break;
  25112. case 1:
  25113. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25114. break;
  25115. case 2:
  25116. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25117. break;
  25118. }
  25119. }
  25120. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25121. window.setTimeout(function () {
  25122. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, function (mesh) { return (mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger) && mesh == _this._pickedDownMesh); }, false, _this.cameraToUseForPointers);
  25123. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25124. if (_this._totalPointersPressed !== 0 &&
  25125. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25126. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25127. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25128. _this._startingPointerTime = 0;
  25129. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25130. }
  25131. }
  25132. }, Scene.LongPressDelay);
  25133. }
  25134. }
  25135. }
  25136. if (pickResult) {
  25137. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25138. if (this.onPointerDown) {
  25139. this.onPointerDown(evt, pickResult, type);
  25140. }
  25141. if (this.onPointerObservable.hasObservers()) {
  25142. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25143. this.onPointerObservable.notifyObservers(pi, type);
  25144. }
  25145. }
  25146. return this;
  25147. };
  25148. /**
  25149. * Use this method to simulate a pointer up on a mesh
  25150. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25151. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25152. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25153. * @returns the current scene
  25154. */
  25155. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25156. var evt = new PointerEvent("pointerup", pointerEventInit);
  25157. var clickInfo = new ClickInfo();
  25158. clickInfo.singleClick = true;
  25159. clickInfo.ignore = true;
  25160. return this._processPointerUp(pickResult, evt, clickInfo);
  25161. };
  25162. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25163. if (pickResult && pickResult && pickResult.pickedMesh) {
  25164. this._pickedUpMesh = pickResult.pickedMesh;
  25165. if (this._pickedDownMesh === this._pickedUpMesh) {
  25166. if (this.onPointerPick) {
  25167. this.onPointerPick(evt, pickResult);
  25168. }
  25169. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25170. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25171. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25172. this.onPointerObservable.notifyObservers(pi, type_1);
  25173. }
  25174. }
  25175. if (pickResult.pickedMesh.actionManager) {
  25176. if (clickInfo.ignore) {
  25177. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25178. }
  25179. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25180. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25181. }
  25182. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25183. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25184. }
  25185. }
  25186. }
  25187. if (this._pickedDownMesh &&
  25188. this._pickedDownMesh.actionManager &&
  25189. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25190. this._pickedDownMesh !== this._pickedUpMesh) {
  25191. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25192. }
  25193. var type = BABYLON.PointerEventTypes.POINTERUP;
  25194. if (this.onPointerObservable.hasObservers()) {
  25195. if (!clickInfo.ignore) {
  25196. if (!clickInfo.hasSwiped) {
  25197. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25198. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25199. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25200. this.onPointerObservable.notifyObservers(pi, type_2);
  25201. }
  25202. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25203. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25204. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25205. this.onPointerObservable.notifyObservers(pi, type_3);
  25206. }
  25207. }
  25208. }
  25209. else {
  25210. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25211. this.onPointerObservable.notifyObservers(pi, type);
  25212. }
  25213. }
  25214. if (this.onPointerUp) {
  25215. this.onPointerUp(evt, pickResult, type);
  25216. }
  25217. return this;
  25218. };
  25219. /**
  25220. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25221. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25222. * @returns true if the pointer was captured
  25223. */
  25224. Scene.prototype.isPointerCaptured = function (pointerId) {
  25225. if (pointerId === void 0) { pointerId = 0; }
  25226. return this._pointerCaptures[pointerId];
  25227. };
  25228. /**
  25229. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25230. * @param attachUp defines if you want to attach events to pointerup
  25231. * @param attachDown defines if you want to attach events to pointerdown
  25232. * @param attachMove defines if you want to attach events to pointermove
  25233. */
  25234. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25235. var _this = this;
  25236. if (attachUp === void 0) { attachUp = true; }
  25237. if (attachDown === void 0) { attachDown = true; }
  25238. if (attachMove === void 0) { attachMove = true; }
  25239. this._initActionManager = function (act, clickInfo) {
  25240. if (!_this._meshPickProceed) {
  25241. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25242. _this._currentPickResult = pickResult;
  25243. if (pickResult) {
  25244. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25245. }
  25246. _this._meshPickProceed = true;
  25247. }
  25248. return act;
  25249. };
  25250. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25251. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25252. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25253. btn !== _this._previousButtonPressed) {
  25254. _this._doubleClickOccured = false;
  25255. clickInfo.singleClick = true;
  25256. clickInfo.ignore = false;
  25257. cb(clickInfo, _this._currentPickResult);
  25258. }
  25259. };
  25260. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25261. var clickInfo = new ClickInfo();
  25262. _this._currentPickResult = null;
  25263. var act = null;
  25264. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25265. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25266. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25267. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25268. act = _this._initActionManager(act, clickInfo);
  25269. if (act)
  25270. checkPicking = act.hasPickTriggers;
  25271. }
  25272. if (checkPicking) {
  25273. var btn = evt.button;
  25274. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25275. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25276. if (!clickInfo.hasSwiped) {
  25277. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25278. if (!checkSingleClickImmediately) {
  25279. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25280. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25281. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25282. act = _this._initActionManager(act, clickInfo);
  25283. if (act)
  25284. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25285. }
  25286. }
  25287. if (checkSingleClickImmediately) {
  25288. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25289. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25290. btn !== _this._previousButtonPressed) {
  25291. clickInfo.singleClick = true;
  25292. cb(clickInfo, _this._currentPickResult);
  25293. }
  25294. }
  25295. // at least one double click is required to be check and exclusive double click is enabled
  25296. else {
  25297. // wait that no double click has been raised during the double click delay
  25298. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25299. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25300. }
  25301. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25302. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25303. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25304. act = _this._initActionManager(act, clickInfo);
  25305. if (act)
  25306. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25307. }
  25308. if (checkDoubleClick) {
  25309. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25310. if (btn === _this._previousButtonPressed &&
  25311. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25312. !_this._doubleClickOccured) {
  25313. // pointer has not moved for 2 clicks, it's a double click
  25314. if (!clickInfo.hasSwiped &&
  25315. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25316. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25317. _this._previousStartingPointerTime = 0;
  25318. _this._doubleClickOccured = true;
  25319. clickInfo.doubleClick = true;
  25320. clickInfo.ignore = false;
  25321. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25322. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25323. }
  25324. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25325. cb(clickInfo, _this._currentPickResult);
  25326. }
  25327. // if the two successive clicks are too far, it's just two simple clicks
  25328. else {
  25329. _this._doubleClickOccured = false;
  25330. _this._previousStartingPointerTime = _this._startingPointerTime;
  25331. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25332. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25333. _this._previousButtonPressed = btn;
  25334. if (Scene.ExclusiveDoubleClickMode) {
  25335. if (_this._previousDelayedSimpleClickTimeout) {
  25336. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25337. }
  25338. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25339. cb(clickInfo, _this._previousPickResult);
  25340. }
  25341. else {
  25342. cb(clickInfo, _this._currentPickResult);
  25343. }
  25344. }
  25345. }
  25346. // just the first click of the double has been raised
  25347. else {
  25348. _this._doubleClickOccured = false;
  25349. _this._previousStartingPointerTime = _this._startingPointerTime;
  25350. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25351. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25352. _this._previousButtonPressed = btn;
  25353. }
  25354. }
  25355. }
  25356. }
  25357. clickInfo.ignore = true;
  25358. cb(clickInfo, _this._currentPickResult);
  25359. };
  25360. this._spritePredicate = function (sprite) {
  25361. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25362. };
  25363. this._onPointerMove = function (evt) {
  25364. _this._updatePointerPosition(evt);
  25365. // PreObservable support
  25366. if (_this.onPrePointerObservable.hasObservers() && !_this._pointerCaptures[evt.pointerId]) {
  25367. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25368. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25369. _this.onPrePointerObservable.notifyObservers(pi, type);
  25370. if (pi.skipOnPointerObservable) {
  25371. return;
  25372. }
  25373. }
  25374. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25375. return;
  25376. }
  25377. if (!_this.pointerMovePredicate) {
  25378. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25379. }
  25380. // Meshes
  25381. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25382. _this._processPointerMove(pickResult, evt);
  25383. };
  25384. this._onPointerDown = function (evt) {
  25385. _this._totalPointersPressed++;
  25386. _this._pickedDownMesh = null;
  25387. _this._meshPickProceed = false;
  25388. _this._updatePointerPosition(evt);
  25389. if (_this.preventDefaultOnPointerDown && canvas) {
  25390. evt.preventDefault();
  25391. canvas.focus();
  25392. }
  25393. // PreObservable support
  25394. if (_this.onPrePointerObservable.hasObservers()) {
  25395. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25396. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25397. _this.onPrePointerObservable.notifyObservers(pi, type);
  25398. if (pi.skipOnPointerObservable) {
  25399. return;
  25400. }
  25401. }
  25402. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25403. return;
  25404. }
  25405. _this._pointerCaptures[evt.pointerId] = true;
  25406. _this._startingPointerPosition.x = _this._pointerX;
  25407. _this._startingPointerPosition.y = _this._pointerY;
  25408. _this._startingPointerTime = Date.now();
  25409. if (!_this.pointerDownPredicate) {
  25410. _this.pointerDownPredicate = function (mesh) {
  25411. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25412. };
  25413. }
  25414. // Meshes
  25415. _this._pickedDownMesh = null;
  25416. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25417. _this._processPointerDown(pickResult, evt);
  25418. // Sprites
  25419. _this._pickedDownSprite = null;
  25420. if (_this.spriteManagers.length > 0) {
  25421. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25422. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25423. if (pickResult.pickedSprite.actionManager) {
  25424. _this._pickedDownSprite = pickResult.pickedSprite;
  25425. switch (evt.button) {
  25426. case 0:
  25427. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25428. break;
  25429. case 1:
  25430. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25431. break;
  25432. case 2:
  25433. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25434. break;
  25435. }
  25436. if (pickResult.pickedSprite.actionManager) {
  25437. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25438. }
  25439. }
  25440. }
  25441. }
  25442. };
  25443. this._onPointerUp = function (evt) {
  25444. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25445. return; // So we need to test it the pointer down was pressed before.
  25446. }
  25447. _this._totalPointersPressed--;
  25448. _this._pickedUpMesh = null;
  25449. _this._meshPickProceed = false;
  25450. _this._updatePointerPosition(evt);
  25451. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25452. // PreObservable support
  25453. if (_this.onPrePointerObservable.hasObservers()) {
  25454. if (!clickInfo.ignore) {
  25455. if (!clickInfo.hasSwiped) {
  25456. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25457. var type = BABYLON.PointerEventTypes.POINTERTAP;
  25458. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25459. _this.onPrePointerObservable.notifyObservers(pi, type);
  25460. if (pi.skipOnPointerObservable) {
  25461. return;
  25462. }
  25463. }
  25464. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25465. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25466. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25467. _this.onPrePointerObservable.notifyObservers(pi, type);
  25468. if (pi.skipOnPointerObservable) {
  25469. return;
  25470. }
  25471. }
  25472. }
  25473. }
  25474. else {
  25475. var type = BABYLON.PointerEventTypes.POINTERUP;
  25476. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25477. _this.onPrePointerObservable.notifyObservers(pi, type);
  25478. if (pi.skipOnPointerObservable) {
  25479. return;
  25480. }
  25481. }
  25482. }
  25483. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25484. return;
  25485. }
  25486. _this._pointerCaptures[evt.pointerId] = false;
  25487. if (!_this.pointerUpPredicate) {
  25488. _this.pointerUpPredicate = function (mesh) {
  25489. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25490. };
  25491. }
  25492. // Meshes
  25493. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25494. _this._initActionManager(null, clickInfo);
  25495. }
  25496. if (!pickResult) {
  25497. pickResult = _this._currentPickResult;
  25498. }
  25499. _this._processPointerUp(pickResult, evt, clickInfo);
  25500. // Sprites
  25501. if (!clickInfo.ignore) {
  25502. if (_this.spriteManagers.length > 0) {
  25503. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25504. if (spritePickResult) {
  25505. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25506. if (spritePickResult.pickedSprite.actionManager) {
  25507. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25508. if (spritePickResult.pickedSprite.actionManager) {
  25509. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25510. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25511. }
  25512. }
  25513. }
  25514. }
  25515. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25516. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25517. }
  25518. }
  25519. }
  25520. }
  25521. _this._previousPickResult = _this._currentPickResult;
  25522. });
  25523. };
  25524. this._onKeyDown = function (evt) {
  25525. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25526. if (_this.onPreKeyboardObservable.hasObservers()) {
  25527. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25528. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25529. if (pi.skipOnPointerObservable) {
  25530. return;
  25531. }
  25532. }
  25533. if (_this.onKeyboardObservable.hasObservers()) {
  25534. var pi = new BABYLON.KeyboardInfo(type, evt);
  25535. _this.onKeyboardObservable.notifyObservers(pi, type);
  25536. }
  25537. if (_this.actionManager) {
  25538. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25539. }
  25540. };
  25541. this._onKeyUp = function (evt) {
  25542. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25543. if (_this.onPreKeyboardObservable.hasObservers()) {
  25544. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25545. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25546. if (pi.skipOnPointerObservable) {
  25547. return;
  25548. }
  25549. }
  25550. if (_this.onKeyboardObservable.hasObservers()) {
  25551. var pi = new BABYLON.KeyboardInfo(type, evt);
  25552. _this.onKeyboardObservable.notifyObservers(pi, type);
  25553. }
  25554. if (_this.actionManager) {
  25555. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25556. }
  25557. };
  25558. var engine = this.getEngine();
  25559. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25560. if (!canvas) {
  25561. return;
  25562. }
  25563. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25564. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25565. });
  25566. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25567. if (!canvas) {
  25568. return;
  25569. }
  25570. canvas.removeEventListener("keydown", _this._onKeyDown);
  25571. canvas.removeEventListener("keyup", _this._onKeyUp);
  25572. });
  25573. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25574. var canvas = this._engine.getRenderingCanvas();
  25575. if (!canvas) {
  25576. return;
  25577. }
  25578. if (attachMove) {
  25579. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25580. // Wheel
  25581. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25582. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25583. }
  25584. if (attachDown) {
  25585. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25586. }
  25587. if (attachUp) {
  25588. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25589. }
  25590. canvas.tabIndex = 1;
  25591. };
  25592. /** Detaches all event handlers*/
  25593. Scene.prototype.detachControl = function () {
  25594. var engine = this.getEngine();
  25595. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25596. var canvas = engine.getRenderingCanvas();
  25597. if (!canvas) {
  25598. return;
  25599. }
  25600. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25601. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25602. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25603. if (this._onCanvasBlurObserver) {
  25604. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25605. }
  25606. if (this._onCanvasFocusObserver) {
  25607. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25608. }
  25609. // Wheel
  25610. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25611. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25612. // Keyboard
  25613. canvas.removeEventListener("keydown", this._onKeyDown);
  25614. canvas.removeEventListener("keyup", this._onKeyUp);
  25615. // Observables
  25616. this.onKeyboardObservable.clear();
  25617. this.onPreKeyboardObservable.clear();
  25618. this.onPointerObservable.clear();
  25619. this.onPrePointerObservable.clear();
  25620. };
  25621. /**
  25622. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25623. * Delay loaded resources are not taking in account
  25624. * @return true if all required resources are ready
  25625. */
  25626. Scene.prototype.isReady = function () {
  25627. if (this._isDisposed) {
  25628. return false;
  25629. }
  25630. if (this._pendingData.length > 0) {
  25631. return false;
  25632. }
  25633. var index;
  25634. var engine = this.getEngine();
  25635. // Geometries
  25636. for (index = 0; index < this._geometries.length; index++) {
  25637. var geometry = this._geometries[index];
  25638. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25639. return false;
  25640. }
  25641. }
  25642. // Meshes
  25643. for (index = 0; index < this.meshes.length; index++) {
  25644. var mesh = this.meshes[index];
  25645. if (!mesh.isEnabled()) {
  25646. continue;
  25647. }
  25648. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25649. continue;
  25650. }
  25651. if (!mesh.isReady(true)) {
  25652. return false;
  25653. }
  25654. // Effect layers
  25655. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25656. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25657. var layer = _a[_i];
  25658. if (!layer.hasMesh(mesh)) {
  25659. continue;
  25660. }
  25661. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25662. var subMesh = _c[_b];
  25663. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25664. return false;
  25665. }
  25666. }
  25667. }
  25668. }
  25669. // Post-processes
  25670. if (this.activeCameras && this.activeCameras.length > 0) {
  25671. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25672. var camera = _e[_d];
  25673. if (!camera.isReady(true)) {
  25674. return false;
  25675. }
  25676. }
  25677. }
  25678. else if (this.activeCamera) {
  25679. if (!this.activeCamera.isReady(true)) {
  25680. return false;
  25681. }
  25682. }
  25683. // Particles
  25684. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25685. var particleSystem = _g[_f];
  25686. if (!particleSystem.isReady()) {
  25687. return false;
  25688. }
  25689. }
  25690. return true;
  25691. };
  25692. /** Resets all cached information relative to material (including effect and visibility) */
  25693. Scene.prototype.resetCachedMaterial = function () {
  25694. this._cachedMaterial = null;
  25695. this._cachedEffect = null;
  25696. this._cachedVisibility = null;
  25697. };
  25698. /**
  25699. * Registers a function to be called before every frame render
  25700. * @param func defines the function to register
  25701. */
  25702. Scene.prototype.registerBeforeRender = function (func) {
  25703. this.onBeforeRenderObservable.add(func);
  25704. };
  25705. /**
  25706. * Unregisters a function called before every frame render
  25707. * @param func defines the function to unregister
  25708. */
  25709. Scene.prototype.unregisterBeforeRender = function (func) {
  25710. this.onBeforeRenderObservable.removeCallback(func);
  25711. };
  25712. /**
  25713. * Registers a function to be called after every frame render
  25714. * @param func defines the function to register
  25715. */
  25716. Scene.prototype.registerAfterRender = function (func) {
  25717. this.onAfterRenderObservable.add(func);
  25718. };
  25719. /**
  25720. * Unregisters a function called after every frame render
  25721. * @param func defines the function to unregister
  25722. */
  25723. Scene.prototype.unregisterAfterRender = function (func) {
  25724. this.onAfterRenderObservable.removeCallback(func);
  25725. };
  25726. Scene.prototype._executeOnceBeforeRender = function (func) {
  25727. var _this = this;
  25728. var execFunc = function () {
  25729. func();
  25730. setTimeout(function () {
  25731. _this.unregisterBeforeRender(execFunc);
  25732. });
  25733. };
  25734. this.registerBeforeRender(execFunc);
  25735. };
  25736. /**
  25737. * The provided function will run before render once and will be disposed afterwards.
  25738. * A timeout delay can be provided so that the function will be executed in N ms.
  25739. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25740. * @param func The function to be executed.
  25741. * @param timeout optional delay in ms
  25742. */
  25743. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25744. var _this = this;
  25745. if (timeout !== undefined) {
  25746. setTimeout(function () {
  25747. _this._executeOnceBeforeRender(func);
  25748. }, timeout);
  25749. }
  25750. else {
  25751. this._executeOnceBeforeRender(func);
  25752. }
  25753. };
  25754. /** @hidden */
  25755. Scene.prototype._addPendingData = function (data) {
  25756. this._pendingData.push(data);
  25757. };
  25758. /** @hidden */
  25759. Scene.prototype._removePendingData = function (data) {
  25760. var wasLoading = this.isLoading;
  25761. var index = this._pendingData.indexOf(data);
  25762. if (index !== -1) {
  25763. this._pendingData.splice(index, 1);
  25764. }
  25765. if (wasLoading && !this.isLoading) {
  25766. this.onDataLoadedObservable.notifyObservers(this);
  25767. }
  25768. };
  25769. /**
  25770. * Returns the number of items waiting to be loaded
  25771. * @returns the number of items waiting to be loaded
  25772. */
  25773. Scene.prototype.getWaitingItemsCount = function () {
  25774. return this._pendingData.length;
  25775. };
  25776. Object.defineProperty(Scene.prototype, "isLoading", {
  25777. /**
  25778. * Returns a boolean indicating if the scene is still loading data
  25779. */
  25780. get: function () {
  25781. return this._pendingData.length > 0;
  25782. },
  25783. enumerable: true,
  25784. configurable: true
  25785. });
  25786. /**
  25787. * Registers a function to be executed when the scene is ready
  25788. * @param {Function} func - the function to be executed
  25789. */
  25790. Scene.prototype.executeWhenReady = function (func) {
  25791. var _this = this;
  25792. this.onReadyObservable.add(func);
  25793. if (this._executeWhenReadyTimeoutId !== -1) {
  25794. return;
  25795. }
  25796. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25797. _this._checkIsReady();
  25798. }, 150);
  25799. };
  25800. /**
  25801. * Returns a promise that resolves when the scene is ready
  25802. * @returns A promise that resolves when the scene is ready
  25803. */
  25804. Scene.prototype.whenReadyAsync = function () {
  25805. var _this = this;
  25806. return new Promise(function (resolve) {
  25807. _this.executeWhenReady(function () {
  25808. resolve();
  25809. });
  25810. });
  25811. };
  25812. /** @hidden */
  25813. Scene.prototype._checkIsReady = function () {
  25814. var _this = this;
  25815. if (this.isReady()) {
  25816. this.onReadyObservable.notifyObservers(this);
  25817. this.onReadyObservable.clear();
  25818. this._executeWhenReadyTimeoutId = -1;
  25819. return;
  25820. }
  25821. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25822. _this._checkIsReady();
  25823. }, 150);
  25824. };
  25825. // Animations
  25826. /**
  25827. * Will start the animation sequence of a given target
  25828. * @param target defines the target
  25829. * @param from defines from which frame should animation start
  25830. * @param to defines until which frame should animation run.
  25831. * @param weight defines the weight to apply to the animation (1.0 by default)
  25832. * @param loop defines if the animation loops
  25833. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25834. * @param onAnimationEnd defines the function to be executed when the animation ends
  25835. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25836. * @returns the animatable object created for this animation
  25837. */
  25838. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25839. if (weight === void 0) { weight = 1.0; }
  25840. if (speedRatio === void 0) { speedRatio = 1.0; }
  25841. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25842. returnedAnimatable.weight = weight;
  25843. return returnedAnimatable;
  25844. };
  25845. /**
  25846. * Will start the animation sequence of a given target
  25847. * @param target defines the target
  25848. * @param from defines from which frame should animation start
  25849. * @param to defines until which frame should animation run.
  25850. * @param loop defines if the animation loops
  25851. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25852. * @param onAnimationEnd defines the function to be executed when the animation ends
  25853. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25854. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25855. * @returns the animatable object created for this animation
  25856. */
  25857. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25858. if (speedRatio === void 0) { speedRatio = 1.0; }
  25859. if (stopCurrent === void 0) { stopCurrent = true; }
  25860. if (from > to && speedRatio > 0) {
  25861. speedRatio *= -1;
  25862. }
  25863. if (stopCurrent) {
  25864. this.stopAnimation(target);
  25865. }
  25866. if (!animatable) {
  25867. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25868. }
  25869. // Local animations
  25870. if (target.animations) {
  25871. animatable.appendAnimations(target, target.animations);
  25872. }
  25873. // Children animations
  25874. if (target.getAnimatables) {
  25875. var animatables = target.getAnimatables();
  25876. for (var index = 0; index < animatables.length; index++) {
  25877. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25878. }
  25879. }
  25880. animatable.reset();
  25881. return animatable;
  25882. };
  25883. /**
  25884. * Begin a new animation on a given node
  25885. * @param target defines the target where the animation will take place
  25886. * @param animations defines the list of animations to start
  25887. * @param from defines the initial value
  25888. * @param to defines the final value
  25889. * @param loop defines if you want animation to loop (off by default)
  25890. * @param speedRatio defines the speed ratio to apply to all animations
  25891. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25892. * @returns the list of created animatables
  25893. */
  25894. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25895. if (speedRatio === undefined) {
  25896. speedRatio = 1.0;
  25897. }
  25898. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25899. return animatable;
  25900. };
  25901. /**
  25902. * Begin a new animation on a given node and its hierarchy
  25903. * @param target defines the root node where the animation will take place
  25904. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  25905. * @param animations defines the list of animations to start
  25906. * @param from defines the initial value
  25907. * @param to defines the final value
  25908. * @param loop defines if you want animation to loop (off by default)
  25909. * @param speedRatio defines the speed ratio to apply to all animations
  25910. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25911. * @returns the list of animatables created for all nodes
  25912. */
  25913. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25914. var children = target.getDescendants(directDescendantsOnly);
  25915. var result = [];
  25916. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25917. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25918. var child = children_1[_i];
  25919. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25920. }
  25921. return result;
  25922. };
  25923. /**
  25924. * Gets the animatable associated with a specific target
  25925. * @param target defines the target of the animatable
  25926. * @returns the required animatable if found
  25927. */
  25928. Scene.prototype.getAnimatableByTarget = function (target) {
  25929. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25930. if (this._activeAnimatables[index].target === target) {
  25931. return this._activeAnimatables[index];
  25932. }
  25933. }
  25934. return null;
  25935. };
  25936. /**
  25937. * Gets all animatables associated with a given target
  25938. * @param target defines the target to look animatables for
  25939. * @returns an array of Animatables
  25940. */
  25941. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25942. var result = [];
  25943. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25944. if (this._activeAnimatables[index].target === target) {
  25945. result.push(this._activeAnimatables[index]);
  25946. }
  25947. }
  25948. return result;
  25949. };
  25950. Object.defineProperty(Scene.prototype, "animatables", {
  25951. /**
  25952. * Gets all animatable attached to the scene
  25953. */
  25954. get: function () {
  25955. return this._activeAnimatables;
  25956. },
  25957. enumerable: true,
  25958. configurable: true
  25959. });
  25960. /**
  25961. * Will stop the animation of the given target
  25962. * @param target - the target
  25963. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25964. */
  25965. Scene.prototype.stopAnimation = function (target, animationName) {
  25966. var animatables = this.getAllAnimatablesByTarget(target);
  25967. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25968. var animatable = animatables_1[_i];
  25969. animatable.stop(animationName);
  25970. }
  25971. };
  25972. /**
  25973. * Stops and removes all animations that have been applied to the scene
  25974. */
  25975. Scene.prototype.stopAllAnimations = function () {
  25976. if (this._activeAnimatables) {
  25977. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25978. this._activeAnimatables[i].stop();
  25979. }
  25980. this._activeAnimatables = [];
  25981. }
  25982. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25983. var group = _a[_i];
  25984. group.stop();
  25985. }
  25986. };
  25987. Scene.prototype._animate = function () {
  25988. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25989. return;
  25990. }
  25991. // Getting time
  25992. var now = BABYLON.Tools.Now;
  25993. if (!this._animationTimeLast) {
  25994. if (this._pendingData.length > 0) {
  25995. return;
  25996. }
  25997. this._animationTimeLast = now;
  25998. }
  25999. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26000. this._animationTime += deltaTime;
  26001. this._animationTimeLast = now;
  26002. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26003. this._activeAnimatables[index]._animate(this._animationTime);
  26004. }
  26005. // Late animation bindings
  26006. this._processLateAnimationBindings();
  26007. };
  26008. /** @hidden */
  26009. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26010. var target = runtimeAnimation.target;
  26011. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26012. if (!target._lateAnimationHolders) {
  26013. target._lateAnimationHolders = {};
  26014. }
  26015. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26016. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26017. totalWeight: 0,
  26018. animations: [],
  26019. originalValue: originalValue
  26020. };
  26021. }
  26022. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26023. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26024. };
  26025. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26026. var normalizer = 1.0;
  26027. var finalPosition = BABYLON.Tmp.Vector3[0];
  26028. var finalScaling = BABYLON.Tmp.Vector3[1];
  26029. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26030. var startIndex = 0;
  26031. var originalAnimation = holder.animations[0];
  26032. var originalValue = holder.originalValue;
  26033. var scale = 1;
  26034. if (holder.totalWeight < 1.0) {
  26035. // We need to mix the original value in
  26036. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26037. scale = 1.0 - holder.totalWeight;
  26038. }
  26039. else {
  26040. startIndex = 1;
  26041. // We need to normalize the weights
  26042. normalizer = holder.totalWeight;
  26043. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26044. scale = originalAnimation.weight / normalizer;
  26045. if (scale == 1) {
  26046. return originalAnimation.currentValue;
  26047. }
  26048. }
  26049. finalScaling.scaleInPlace(scale);
  26050. finalPosition.scaleInPlace(scale);
  26051. finalQuaternion.scaleInPlace(scale);
  26052. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26053. var runtimeAnimation = holder.animations[animIndex];
  26054. var scale = runtimeAnimation.weight / normalizer;
  26055. var currentPosition = BABYLON.Tmp.Vector3[2];
  26056. var currentScaling = BABYLON.Tmp.Vector3[3];
  26057. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26058. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26059. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26060. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26061. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26062. }
  26063. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26064. return originalAnimation._workValue;
  26065. };
  26066. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26067. var originalAnimation = holder.animations[0];
  26068. var originalValue = holder.originalValue;
  26069. if (holder.animations.length === 1) {
  26070. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26071. }
  26072. var normalizer = 1.0;
  26073. var quaternions;
  26074. var weights;
  26075. if (holder.totalWeight < 1.0) {
  26076. var scale = 1.0 - holder.totalWeight;
  26077. quaternions = [];
  26078. weights = [];
  26079. quaternions.push(originalValue);
  26080. weights.push(scale);
  26081. }
  26082. else {
  26083. if (holder.animations.length === 2) { // Slerp as soon as we can
  26084. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26085. }
  26086. quaternions = [];
  26087. weights = [];
  26088. normalizer = holder.totalWeight;
  26089. }
  26090. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26091. var runtimeAnimation = holder.animations[animIndex];
  26092. quaternions.push(runtimeAnimation.currentValue);
  26093. weights.push(runtimeAnimation.weight / normalizer);
  26094. }
  26095. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26096. var cumulativeAmount = 0;
  26097. var cumulativeQuaternion = null;
  26098. for (var index = 0; index < quaternions.length;) {
  26099. if (!cumulativeQuaternion) {
  26100. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26101. cumulativeAmount = weights[index] + weights[index + 1];
  26102. index += 2;
  26103. continue;
  26104. }
  26105. cumulativeAmount += weights[index];
  26106. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26107. index++;
  26108. }
  26109. return cumulativeQuaternion;
  26110. };
  26111. Scene.prototype._processLateAnimationBindings = function () {
  26112. if (!this._registeredForLateAnimationBindings.length) {
  26113. return;
  26114. }
  26115. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26116. var target = this._registeredForLateAnimationBindings.data[index];
  26117. for (var path in target._lateAnimationHolders) {
  26118. var holder = target._lateAnimationHolders[path];
  26119. var originalAnimation = holder.animations[0];
  26120. var originalValue = holder.originalValue;
  26121. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26122. var finalValue = void 0;
  26123. if (matrixDecomposeMode) {
  26124. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26125. }
  26126. else {
  26127. var quaternionMode = originalValue.w !== undefined;
  26128. if (quaternionMode) {
  26129. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26130. }
  26131. else {
  26132. var startIndex = 0;
  26133. var normalizer = 1.0;
  26134. if (holder.totalWeight < 1.0) {
  26135. // We need to mix the original value in
  26136. if (originalValue.scale) {
  26137. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26138. }
  26139. else {
  26140. finalValue = originalValue * (1.0 - holder.totalWeight);
  26141. }
  26142. }
  26143. else {
  26144. // We need to normalize the weights
  26145. normalizer = holder.totalWeight;
  26146. var scale_1 = originalAnimation.weight / normalizer;
  26147. if (scale_1 !== 1) {
  26148. if (originalAnimation.currentValue.scale) {
  26149. finalValue = originalAnimation.currentValue.scale(scale_1);
  26150. }
  26151. else {
  26152. finalValue = originalAnimation.currentValue * scale_1;
  26153. }
  26154. }
  26155. else {
  26156. finalValue = originalAnimation.currentValue;
  26157. }
  26158. startIndex = 1;
  26159. }
  26160. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26161. var runtimeAnimation = holder.animations[animIndex];
  26162. var scale = runtimeAnimation.weight / normalizer;
  26163. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26164. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26165. }
  26166. else {
  26167. finalValue += runtimeAnimation.currentValue * scale;
  26168. }
  26169. }
  26170. }
  26171. }
  26172. target[path] = finalValue;
  26173. }
  26174. target._lateAnimationHolders = {};
  26175. }
  26176. this._registeredForLateAnimationBindings.reset();
  26177. };
  26178. // Matrix
  26179. /** @hidden */
  26180. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26181. this._useAlternateCameraConfiguration = active;
  26182. };
  26183. /**
  26184. * Gets the current view matrix
  26185. * @returns a Matrix
  26186. */
  26187. Scene.prototype.getViewMatrix = function () {
  26188. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26189. };
  26190. /**
  26191. * Gets the current projection matrix
  26192. * @returns a Matrix
  26193. */
  26194. Scene.prototype.getProjectionMatrix = function () {
  26195. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26196. };
  26197. /**
  26198. * Gets the current transform matrix
  26199. * @returns a Matrix made of View * Projection
  26200. */
  26201. Scene.prototype.getTransformMatrix = function () {
  26202. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26203. };
  26204. /**
  26205. * Sets the current transform matrix
  26206. * @param view defines the View matrix to use
  26207. * @param projection defines the Projection matrix to use
  26208. */
  26209. Scene.prototype.setTransformMatrix = function (view, projection) {
  26210. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26211. return;
  26212. }
  26213. this._viewUpdateFlag = view.updateFlag;
  26214. this._projectionUpdateFlag = projection.updateFlag;
  26215. this._viewMatrix = view;
  26216. this._projectionMatrix = projection;
  26217. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26218. // Update frustum
  26219. if (!this._frustumPlanes) {
  26220. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26221. }
  26222. else {
  26223. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26224. }
  26225. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26226. var otherCamera = this.activeCamera._alternateCamera;
  26227. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26228. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26229. }
  26230. if (this._sceneUbo.useUbo) {
  26231. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26232. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26233. this._sceneUbo.update();
  26234. }
  26235. };
  26236. /** @hidden */
  26237. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26238. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26239. return;
  26240. }
  26241. this._alternateViewUpdateFlag = view.updateFlag;
  26242. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26243. this._alternateViewMatrix = view;
  26244. this._alternateProjectionMatrix = projection;
  26245. if (!this._alternateTransformMatrix) {
  26246. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26247. }
  26248. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26249. if (!this._alternateSceneUbo) {
  26250. this._createAlternateUbo();
  26251. }
  26252. if (this._alternateSceneUbo.useUbo) {
  26253. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26254. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26255. this._alternateSceneUbo.update();
  26256. }
  26257. };
  26258. /**
  26259. * Gets the uniform buffer used to store scene data
  26260. * @returns a UniformBuffer
  26261. */
  26262. Scene.prototype.getSceneUniformBuffer = function () {
  26263. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26264. };
  26265. /**
  26266. * Gets an unique (relatively to the current scene) Id
  26267. * @returns an unique number for the scene
  26268. */
  26269. Scene.prototype.getUniqueId = function () {
  26270. var result = Scene._uniqueIdCounter;
  26271. Scene._uniqueIdCounter++;
  26272. return result;
  26273. };
  26274. /**
  26275. * Add a mesh to the list of scene's meshes
  26276. * @param newMesh defines the mesh to add
  26277. * @param recursive if all child meshes should also be added to the scene
  26278. */
  26279. Scene.prototype.addMesh = function (newMesh, recursive) {
  26280. var _this = this;
  26281. if (recursive === void 0) { recursive = false; }
  26282. this.meshes.push(newMesh);
  26283. //notify the collision coordinator
  26284. if (this.collisionCoordinator) {
  26285. this.collisionCoordinator.onMeshAdded(newMesh);
  26286. }
  26287. newMesh._resyncLightSources();
  26288. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26289. if (recursive) {
  26290. newMesh.getChildMeshes().forEach(function (m) {
  26291. _this.addMesh(m);
  26292. });
  26293. }
  26294. };
  26295. /**
  26296. * Remove a mesh for the list of scene's meshes
  26297. * @param toRemove defines the mesh to remove
  26298. * @param recursive if all child meshes should also be removed from the scene
  26299. * @returns the index where the mesh was in the mesh list
  26300. */
  26301. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26302. var _this = this;
  26303. if (recursive === void 0) { recursive = false; }
  26304. var index = this.meshes.indexOf(toRemove);
  26305. if (index !== -1) {
  26306. // Remove from the scene if mesh found
  26307. this.meshes.splice(index, 1);
  26308. }
  26309. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26310. if (recursive) {
  26311. toRemove.getChildMeshes().forEach(function (m) {
  26312. _this.removeMesh(m);
  26313. });
  26314. }
  26315. return index;
  26316. };
  26317. /**
  26318. * Add a transform node to the list of scene's transform nodes
  26319. * @param newTransformNode defines the transform node to add
  26320. */
  26321. Scene.prototype.addTransformNode = function (newTransformNode) {
  26322. this.transformNodes.push(newTransformNode);
  26323. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26324. };
  26325. /**
  26326. * Remove a transform node for the list of scene's transform nodes
  26327. * @param toRemove defines the transform node to remove
  26328. * @returns the index where the transform node was in the transform node list
  26329. */
  26330. Scene.prototype.removeTransformNode = function (toRemove) {
  26331. var index = this.transformNodes.indexOf(toRemove);
  26332. if (index !== -1) {
  26333. // Remove from the scene if found
  26334. this.transformNodes.splice(index, 1);
  26335. }
  26336. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26337. return index;
  26338. };
  26339. /**
  26340. * Remove a skeleton for the list of scene's skeletons
  26341. * @param toRemove defines the skeleton to remove
  26342. * @returns the index where the skeleton was in the skeleton list
  26343. */
  26344. Scene.prototype.removeSkeleton = function (toRemove) {
  26345. var index = this.skeletons.indexOf(toRemove);
  26346. if (index !== -1) {
  26347. // Remove from the scene if found
  26348. this.skeletons.splice(index, 1);
  26349. }
  26350. return index;
  26351. };
  26352. /**
  26353. * Remove a morph target for the list of scene's morph targets
  26354. * @param toRemove defines the morph target to remove
  26355. * @returns the index where the morph target was in the morph target list
  26356. */
  26357. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26358. var index = this.morphTargetManagers.indexOf(toRemove);
  26359. if (index !== -1) {
  26360. // Remove from the scene if found
  26361. this.morphTargetManagers.splice(index, 1);
  26362. }
  26363. return index;
  26364. };
  26365. /**
  26366. * Remove a light for the list of scene's lights
  26367. * @param toRemove defines the light to remove
  26368. * @returns the index where the light was in the light list
  26369. */
  26370. Scene.prototype.removeLight = function (toRemove) {
  26371. var index = this.lights.indexOf(toRemove);
  26372. if (index !== -1) {
  26373. // Remove from meshes
  26374. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26375. var mesh = _a[_i];
  26376. mesh._removeLightSource(toRemove);
  26377. }
  26378. // Remove from the scene if mesh found
  26379. this.lights.splice(index, 1);
  26380. this.sortLightsByPriority();
  26381. }
  26382. this.onLightRemovedObservable.notifyObservers(toRemove);
  26383. return index;
  26384. };
  26385. /**
  26386. * Remove a camera for the list of scene's cameras
  26387. * @param toRemove defines the camera to remove
  26388. * @returns the index where the camera was in the camera list
  26389. */
  26390. Scene.prototype.removeCamera = function (toRemove) {
  26391. var index = this.cameras.indexOf(toRemove);
  26392. if (index !== -1) {
  26393. // Remove from the scene if mesh found
  26394. this.cameras.splice(index, 1);
  26395. }
  26396. // Remove from activeCameras
  26397. var index2 = this.activeCameras.indexOf(toRemove);
  26398. if (index2 !== -1) {
  26399. // Remove from the scene if mesh found
  26400. this.activeCameras.splice(index2, 1);
  26401. }
  26402. // Reset the activeCamera
  26403. if (this.activeCamera === toRemove) {
  26404. if (this.cameras.length > 0) {
  26405. this.activeCamera = this.cameras[0];
  26406. }
  26407. else {
  26408. this.activeCamera = null;
  26409. }
  26410. }
  26411. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26412. return index;
  26413. };
  26414. /**
  26415. * Remove a particle system for the list of scene's particle systems
  26416. * @param toRemove defines the particle system to remove
  26417. * @returns the index where the particle system was in the particle system list
  26418. */
  26419. Scene.prototype.removeParticleSystem = function (toRemove) {
  26420. var index = this.particleSystems.indexOf(toRemove);
  26421. if (index !== -1) {
  26422. this.particleSystems.splice(index, 1);
  26423. }
  26424. return index;
  26425. };
  26426. /**
  26427. * Remove a animation for the list of scene's animations
  26428. * @param toRemove defines the animation to remove
  26429. * @returns the index where the animation was in the animation list
  26430. */
  26431. Scene.prototype.removeAnimation = function (toRemove) {
  26432. var index = this.animations.indexOf(toRemove);
  26433. if (index !== -1) {
  26434. this.animations.splice(index, 1);
  26435. }
  26436. return index;
  26437. };
  26438. /**
  26439. * Removes the given animation group from this scene.
  26440. * @param toRemove The animation group to remove
  26441. * @returns The index of the removed animation group
  26442. */
  26443. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26444. var index = this.animationGroups.indexOf(toRemove);
  26445. if (index !== -1) {
  26446. this.animationGroups.splice(index, 1);
  26447. }
  26448. return index;
  26449. };
  26450. /**
  26451. * Removes the given multi-material from this scene.
  26452. * @param toRemove The multi-material to remove
  26453. * @returns The index of the removed multi-material
  26454. */
  26455. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26456. var index = this.multiMaterials.indexOf(toRemove);
  26457. if (index !== -1) {
  26458. this.multiMaterials.splice(index, 1);
  26459. }
  26460. return index;
  26461. };
  26462. /**
  26463. * Removes the given material from this scene.
  26464. * @param toRemove The material to remove
  26465. * @returns The index of the removed material
  26466. */
  26467. Scene.prototype.removeMaterial = function (toRemove) {
  26468. var index = this.materials.indexOf(toRemove);
  26469. if (index !== -1) {
  26470. this.materials.splice(index, 1);
  26471. }
  26472. return index;
  26473. };
  26474. /**
  26475. * Removes the given lens flare system from this scene.
  26476. * @param toRemove The lens flare system to remove
  26477. * @returns The index of the removed lens flare system
  26478. */
  26479. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26480. var index = this.lensFlareSystems.indexOf(toRemove);
  26481. if (index !== -1) {
  26482. this.lensFlareSystems.splice(index, 1);
  26483. }
  26484. return index;
  26485. };
  26486. /**
  26487. * Removes the given action manager from this scene.
  26488. * @param toRemove The action manager to remove
  26489. * @returns The index of the removed action manager
  26490. */
  26491. Scene.prototype.removeActionManager = function (toRemove) {
  26492. var index = this._actionManagers.indexOf(toRemove);
  26493. if (index !== -1) {
  26494. this._actionManagers.splice(index, 1);
  26495. }
  26496. return index;
  26497. };
  26498. /**
  26499. * Removes the given effect layer from this scene.
  26500. * @param toRemove defines the effect layer to remove
  26501. * @returns the index of the removed effect layer
  26502. */
  26503. Scene.prototype.removeEffectLayer = function (toRemove) {
  26504. var index = this.effectLayers.indexOf(toRemove);
  26505. if (index !== -1) {
  26506. this.effectLayers.splice(index, 1);
  26507. }
  26508. return index;
  26509. };
  26510. /**
  26511. * Removes the given texture from this scene.
  26512. * @param toRemove The texture to remove
  26513. * @returns The index of the removed texture
  26514. */
  26515. Scene.prototype.removeTexture = function (toRemove) {
  26516. var index = this.textures.indexOf(toRemove);
  26517. if (index !== -1) {
  26518. this.textures.splice(index, 1);
  26519. }
  26520. return index;
  26521. };
  26522. /**
  26523. * Adds the given light to this scene
  26524. * @param newLight The light to add
  26525. */
  26526. Scene.prototype.addLight = function (newLight) {
  26527. this.lights.push(newLight);
  26528. this.sortLightsByPriority();
  26529. // Add light to all meshes (To support if the light is removed and then readded)
  26530. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26531. var mesh = _a[_i];
  26532. if (mesh._lightSources.indexOf(newLight) === -1) {
  26533. mesh._lightSources.push(newLight);
  26534. mesh._resyncLightSources();
  26535. }
  26536. }
  26537. this.onNewLightAddedObservable.notifyObservers(newLight);
  26538. };
  26539. /**
  26540. * Sorts the list list based on light priorities
  26541. */
  26542. Scene.prototype.sortLightsByPriority = function () {
  26543. if (this.requireLightSorting) {
  26544. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26545. }
  26546. };
  26547. /**
  26548. * Adds the given camera to this scene
  26549. * @param newCamera The camera to add
  26550. */
  26551. Scene.prototype.addCamera = function (newCamera) {
  26552. this.cameras.push(newCamera);
  26553. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26554. };
  26555. /**
  26556. * Adds the given skeleton to this scene
  26557. * @param newSkeleton The skeleton to add
  26558. */
  26559. Scene.prototype.addSkeleton = function (newSkeleton) {
  26560. this.skeletons.push(newSkeleton);
  26561. };
  26562. /**
  26563. * Adds the given particle system to this scene
  26564. * @param newParticleSystem The particle system to add
  26565. */
  26566. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26567. this.particleSystems.push(newParticleSystem);
  26568. };
  26569. /**
  26570. * Adds the given animation to this scene
  26571. * @param newAnimation The animation to add
  26572. */
  26573. Scene.prototype.addAnimation = function (newAnimation) {
  26574. this.animations.push(newAnimation);
  26575. };
  26576. /**
  26577. * Adds the given animation group to this scene.
  26578. * @param newAnimationGroup The animation group to add
  26579. */
  26580. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26581. this.animationGroups.push(newAnimationGroup);
  26582. };
  26583. /**
  26584. * Adds the given multi-material to this scene
  26585. * @param newMultiMaterial The multi-material to add
  26586. */
  26587. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26588. this.multiMaterials.push(newMultiMaterial);
  26589. };
  26590. /**
  26591. * Adds the given material to this scene
  26592. * @param newMaterial The material to add
  26593. */
  26594. Scene.prototype.addMaterial = function (newMaterial) {
  26595. this.materials.push(newMaterial);
  26596. };
  26597. /**
  26598. * Adds the given morph target to this scene
  26599. * @param newMorphTargetManager The morph target to add
  26600. */
  26601. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26602. this.morphTargetManagers.push(newMorphTargetManager);
  26603. };
  26604. /**
  26605. * Adds the given geometry to this scene
  26606. * @param newGeometry The geometry to add
  26607. */
  26608. Scene.prototype.addGeometry = function (newGeometry) {
  26609. this._geometries.push(newGeometry);
  26610. };
  26611. /**
  26612. * Adds the given lens flare system to this scene
  26613. * @param newLensFlareSystem The lens flare system to add
  26614. */
  26615. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26616. this.lensFlareSystems.push(newLensFlareSystem);
  26617. };
  26618. /**
  26619. * Adds the given effect layer to this scene
  26620. * @param newEffectLayer defines the effect layer to add
  26621. */
  26622. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26623. this.effectLayers.push(newEffectLayer);
  26624. };
  26625. /**
  26626. * Adds the given action manager to this scene
  26627. * @param newActionManager The action manager to add
  26628. */
  26629. Scene.prototype.addActionManager = function (newActionManager) {
  26630. this._actionManagers.push(newActionManager);
  26631. };
  26632. /**
  26633. * Adds the given texture to this scene.
  26634. * @param newTexture The texture to add
  26635. */
  26636. Scene.prototype.addTexture = function (newTexture) {
  26637. this.textures.push(newTexture);
  26638. };
  26639. /**
  26640. * Switch active camera
  26641. * @param newCamera defines the new active camera
  26642. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26643. */
  26644. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26645. if (attachControl === void 0) { attachControl = true; }
  26646. var canvas = this._engine.getRenderingCanvas();
  26647. if (!canvas) {
  26648. return;
  26649. }
  26650. if (this.activeCamera) {
  26651. this.activeCamera.detachControl(canvas);
  26652. }
  26653. this.activeCamera = newCamera;
  26654. if (attachControl) {
  26655. newCamera.attachControl(canvas);
  26656. }
  26657. };
  26658. /**
  26659. * sets the active camera of the scene using its ID
  26660. * @param id defines the camera's ID
  26661. * @return the new active camera or null if none found.
  26662. */
  26663. Scene.prototype.setActiveCameraByID = function (id) {
  26664. var camera = this.getCameraByID(id);
  26665. if (camera) {
  26666. this.activeCamera = camera;
  26667. return camera;
  26668. }
  26669. return null;
  26670. };
  26671. /**
  26672. * sets the active camera of the scene using its name
  26673. * @param name defines the camera's name
  26674. * @returns the new active camera or null if none found.
  26675. */
  26676. Scene.prototype.setActiveCameraByName = function (name) {
  26677. var camera = this.getCameraByName(name);
  26678. if (camera) {
  26679. this.activeCamera = camera;
  26680. return camera;
  26681. }
  26682. return null;
  26683. };
  26684. /**
  26685. * get an animation group using its name
  26686. * @param name defines the material's name
  26687. * @return the animation group or null if none found.
  26688. */
  26689. Scene.prototype.getAnimationGroupByName = function (name) {
  26690. for (var index = 0; index < this.animationGroups.length; index++) {
  26691. if (this.animationGroups[index].name === name) {
  26692. return this.animationGroups[index];
  26693. }
  26694. }
  26695. return null;
  26696. };
  26697. /**
  26698. * get a material using its id
  26699. * @param id defines the material's ID
  26700. * @return the material or null if none found.
  26701. */
  26702. Scene.prototype.getMaterialByID = function (id) {
  26703. for (var index = 0; index < this.materials.length; index++) {
  26704. if (this.materials[index].id === id) {
  26705. return this.materials[index];
  26706. }
  26707. }
  26708. return null;
  26709. };
  26710. /**
  26711. * Gets a material using its name
  26712. * @param name defines the material's name
  26713. * @return the material or null if none found.
  26714. */
  26715. Scene.prototype.getMaterialByName = function (name) {
  26716. for (var index = 0; index < this.materials.length; index++) {
  26717. if (this.materials[index].name === name) {
  26718. return this.materials[index];
  26719. }
  26720. }
  26721. return null;
  26722. };
  26723. /**
  26724. * Gets a lens flare system using its name
  26725. * @param name defines the name to look for
  26726. * @returns the lens flare system or null if not found
  26727. */
  26728. Scene.prototype.getLensFlareSystemByName = function (name) {
  26729. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26730. if (this.lensFlareSystems[index].name === name) {
  26731. return this.lensFlareSystems[index];
  26732. }
  26733. }
  26734. return null;
  26735. };
  26736. /**
  26737. * Gets a lens flare system using its id
  26738. * @param id defines the id to look for
  26739. * @returns the lens flare system or null if not found
  26740. */
  26741. Scene.prototype.getLensFlareSystemByID = function (id) {
  26742. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26743. if (this.lensFlareSystems[index].id === id) {
  26744. return this.lensFlareSystems[index];
  26745. }
  26746. }
  26747. return null;
  26748. };
  26749. /**
  26750. * Gets a camera using its id
  26751. * @param id defines the id to look for
  26752. * @returns the camera or null if not found
  26753. */
  26754. Scene.prototype.getCameraByID = function (id) {
  26755. for (var index = 0; index < this.cameras.length; index++) {
  26756. if (this.cameras[index].id === id) {
  26757. return this.cameras[index];
  26758. }
  26759. }
  26760. return null;
  26761. };
  26762. /**
  26763. * Gets a camera using its unique id
  26764. * @param uniqueId defines the unique id to look for
  26765. * @returns the camera or null if not found
  26766. */
  26767. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26768. for (var index = 0; index < this.cameras.length; index++) {
  26769. if (this.cameras[index].uniqueId === uniqueId) {
  26770. return this.cameras[index];
  26771. }
  26772. }
  26773. return null;
  26774. };
  26775. /**
  26776. * Gets a camera using its name
  26777. * @param name defines the camera's name
  26778. * @return the camera or null if none found.
  26779. */
  26780. Scene.prototype.getCameraByName = function (name) {
  26781. for (var index = 0; index < this.cameras.length; index++) {
  26782. if (this.cameras[index].name === name) {
  26783. return this.cameras[index];
  26784. }
  26785. }
  26786. return null;
  26787. };
  26788. /**
  26789. * Gets a bone using its id
  26790. * @param id defines the bone's id
  26791. * @return the bone or null if not found
  26792. */
  26793. Scene.prototype.getBoneByID = function (id) {
  26794. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26795. var skeleton = this.skeletons[skeletonIndex];
  26796. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26797. if (skeleton.bones[boneIndex].id === id) {
  26798. return skeleton.bones[boneIndex];
  26799. }
  26800. }
  26801. }
  26802. return null;
  26803. };
  26804. /**
  26805. * Gets a bone using its id
  26806. * @param name defines the bone's name
  26807. * @return the bone or null if not found
  26808. */
  26809. Scene.prototype.getBoneByName = function (name) {
  26810. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26811. var skeleton = this.skeletons[skeletonIndex];
  26812. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26813. if (skeleton.bones[boneIndex].name === name) {
  26814. return skeleton.bones[boneIndex];
  26815. }
  26816. }
  26817. }
  26818. return null;
  26819. };
  26820. /**
  26821. * Gets a light node using its name
  26822. * @param name defines the the light's name
  26823. * @return the light or null if none found.
  26824. */
  26825. Scene.prototype.getLightByName = function (name) {
  26826. for (var index = 0; index < this.lights.length; index++) {
  26827. if (this.lights[index].name === name) {
  26828. return this.lights[index];
  26829. }
  26830. }
  26831. return null;
  26832. };
  26833. /**
  26834. * Gets a light node using its id
  26835. * @param id defines the light's id
  26836. * @return the light or null if none found.
  26837. */
  26838. Scene.prototype.getLightByID = function (id) {
  26839. for (var index = 0; index < this.lights.length; index++) {
  26840. if (this.lights[index].id === id) {
  26841. return this.lights[index];
  26842. }
  26843. }
  26844. return null;
  26845. };
  26846. /**
  26847. * Gets a light node using its scene-generated unique ID
  26848. * @param uniqueId defines the light's unique id
  26849. * @return the light or null if none found.
  26850. */
  26851. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26852. for (var index = 0; index < this.lights.length; index++) {
  26853. if (this.lights[index].uniqueId === uniqueId) {
  26854. return this.lights[index];
  26855. }
  26856. }
  26857. return null;
  26858. };
  26859. /**
  26860. * Gets a particle system by id
  26861. * @param id defines the particle system id
  26862. * @return the corresponding system or null if none found
  26863. */
  26864. Scene.prototype.getParticleSystemByID = function (id) {
  26865. for (var index = 0; index < this.particleSystems.length; index++) {
  26866. if (this.particleSystems[index].id === id) {
  26867. return this.particleSystems[index];
  26868. }
  26869. }
  26870. return null;
  26871. };
  26872. /**
  26873. * Gets a geometry using its ID
  26874. * @param id defines the geometry's id
  26875. * @return the geometry or null if none found.
  26876. */
  26877. Scene.prototype.getGeometryByID = function (id) {
  26878. for (var index = 0; index < this._geometries.length; index++) {
  26879. if (this._geometries[index].id === id) {
  26880. return this._geometries[index];
  26881. }
  26882. }
  26883. return null;
  26884. };
  26885. /**
  26886. * Add a new geometry to this scene
  26887. * @param geometry defines the geometry to be added to the scene.
  26888. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26889. * @return a boolean defining if the geometry was added or not
  26890. */
  26891. Scene.prototype.pushGeometry = function (geometry, force) {
  26892. if (!force && this.getGeometryByID(geometry.id)) {
  26893. return false;
  26894. }
  26895. this._geometries.push(geometry);
  26896. //notify the collision coordinator
  26897. if (this.collisionCoordinator) {
  26898. this.collisionCoordinator.onGeometryAdded(geometry);
  26899. }
  26900. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26901. return true;
  26902. };
  26903. /**
  26904. * Removes an existing geometry
  26905. * @param geometry defines the geometry to be removed from the scene
  26906. * @return a boolean defining if the geometry was removed or not
  26907. */
  26908. Scene.prototype.removeGeometry = function (geometry) {
  26909. var index = this._geometries.indexOf(geometry);
  26910. if (index > -1) {
  26911. this._geometries.splice(index, 1);
  26912. //notify the collision coordinator
  26913. if (this.collisionCoordinator) {
  26914. this.collisionCoordinator.onGeometryDeleted(geometry);
  26915. }
  26916. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26917. return true;
  26918. }
  26919. return false;
  26920. };
  26921. /**
  26922. * Gets the list of geometries attached to the scene
  26923. * @returns an array of Geometry
  26924. */
  26925. Scene.prototype.getGeometries = function () {
  26926. return this._geometries;
  26927. };
  26928. /**
  26929. * Gets the first added mesh found of a given ID
  26930. * @param id defines the id to search for
  26931. * @return the mesh found or null if not found at all
  26932. */
  26933. Scene.prototype.getMeshByID = function (id) {
  26934. for (var index = 0; index < this.meshes.length; index++) {
  26935. if (this.meshes[index].id === id) {
  26936. return this.meshes[index];
  26937. }
  26938. }
  26939. return null;
  26940. };
  26941. /**
  26942. * Gets a list of meshes using their id
  26943. * @param id defines the id to search for
  26944. * @returns a list of meshes
  26945. */
  26946. Scene.prototype.getMeshesByID = function (id) {
  26947. return this.meshes.filter(function (m) {
  26948. return m.id === id;
  26949. });
  26950. };
  26951. /**
  26952. * Gets the first added transform node found of a given ID
  26953. * @param id defines the id to search for
  26954. * @return the found transform node or null if not found at all.
  26955. */
  26956. Scene.prototype.getTransformNodeByID = function (id) {
  26957. for (var index = 0; index < this.transformNodes.length; index++) {
  26958. if (this.transformNodes[index].id === id) {
  26959. return this.transformNodes[index];
  26960. }
  26961. }
  26962. return null;
  26963. };
  26964. /**
  26965. * Gets a list of transform nodes using their id
  26966. * @param id defines the id to search for
  26967. * @returns a list of transform nodes
  26968. */
  26969. Scene.prototype.getTransformNodesByID = function (id) {
  26970. return this.transformNodes.filter(function (m) {
  26971. return m.id === id;
  26972. });
  26973. };
  26974. /**
  26975. * Gets a mesh with its auto-generated unique id
  26976. * @param uniqueId defines the unique id to search for
  26977. * @return the found mesh or null if not found at all.
  26978. */
  26979. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26980. for (var index = 0; index < this.meshes.length; index++) {
  26981. if (this.meshes[index].uniqueId === uniqueId) {
  26982. return this.meshes[index];
  26983. }
  26984. }
  26985. return null;
  26986. };
  26987. /**
  26988. * Gets a the last added mesh using a given id
  26989. * @param id defines the id to search for
  26990. * @return the found mesh or null if not found at all.
  26991. */
  26992. Scene.prototype.getLastMeshByID = function (id) {
  26993. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26994. if (this.meshes[index].id === id) {
  26995. return this.meshes[index];
  26996. }
  26997. }
  26998. return null;
  26999. };
  27000. /**
  27001. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27002. * @param id defines the id to search for
  27003. * @return the found node or null if not found at all
  27004. */
  27005. Scene.prototype.getLastEntryByID = function (id) {
  27006. var index;
  27007. for (index = this.meshes.length - 1; index >= 0; index--) {
  27008. if (this.meshes[index].id === id) {
  27009. return this.meshes[index];
  27010. }
  27011. }
  27012. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27013. if (this.transformNodes[index].id === id) {
  27014. return this.transformNodes[index];
  27015. }
  27016. }
  27017. for (index = this.cameras.length - 1; index >= 0; index--) {
  27018. if (this.cameras[index].id === id) {
  27019. return this.cameras[index];
  27020. }
  27021. }
  27022. for (index = this.lights.length - 1; index >= 0; index--) {
  27023. if (this.lights[index].id === id) {
  27024. return this.lights[index];
  27025. }
  27026. }
  27027. return null;
  27028. };
  27029. /**
  27030. * Gets a node (Mesh, Camera, Light) using a given id
  27031. * @param id defines the id to search for
  27032. * @return the found node or null if not found at all
  27033. */
  27034. Scene.prototype.getNodeByID = function (id) {
  27035. var mesh = this.getMeshByID(id);
  27036. if (mesh) {
  27037. return mesh;
  27038. }
  27039. var light = this.getLightByID(id);
  27040. if (light) {
  27041. return light;
  27042. }
  27043. var camera = this.getCameraByID(id);
  27044. if (camera) {
  27045. return camera;
  27046. }
  27047. var bone = this.getBoneByID(id);
  27048. return bone;
  27049. };
  27050. /**
  27051. * Gets a node (Mesh, Camera, Light) using a given name
  27052. * @param name defines the name to search for
  27053. * @return the found node or null if not found at all.
  27054. */
  27055. Scene.prototype.getNodeByName = function (name) {
  27056. var mesh = this.getMeshByName(name);
  27057. if (mesh) {
  27058. return mesh;
  27059. }
  27060. var light = this.getLightByName(name);
  27061. if (light) {
  27062. return light;
  27063. }
  27064. var camera = this.getCameraByName(name);
  27065. if (camera) {
  27066. return camera;
  27067. }
  27068. var bone = this.getBoneByName(name);
  27069. return bone;
  27070. };
  27071. /**
  27072. * Gets a mesh using a given name
  27073. * @param name defines the name to search for
  27074. * @return the found mesh or null if not found at all.
  27075. */
  27076. Scene.prototype.getMeshByName = function (name) {
  27077. for (var index = 0; index < this.meshes.length; index++) {
  27078. if (this.meshes[index].name === name) {
  27079. return this.meshes[index];
  27080. }
  27081. }
  27082. return null;
  27083. };
  27084. /**
  27085. * Gets a transform node using a given name
  27086. * @param name defines the name to search for
  27087. * @return the found transform node or null if not found at all.
  27088. */
  27089. Scene.prototype.getTransformNodeByName = function (name) {
  27090. for (var index = 0; index < this.transformNodes.length; index++) {
  27091. if (this.transformNodes[index].name === name) {
  27092. return this.transformNodes[index];
  27093. }
  27094. }
  27095. return null;
  27096. };
  27097. /**
  27098. * Gets a sound using a given name
  27099. * @param name defines the name to search for
  27100. * @return the found sound or null if not found at all.
  27101. */
  27102. Scene.prototype.getSoundByName = function (name) {
  27103. var index;
  27104. if (BABYLON.AudioEngine) {
  27105. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27106. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27107. return this.mainSoundTrack.soundCollection[index];
  27108. }
  27109. }
  27110. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27111. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27112. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27113. return this.soundTracks[sdIndex].soundCollection[index];
  27114. }
  27115. }
  27116. }
  27117. }
  27118. return null;
  27119. };
  27120. /**
  27121. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27122. * @param id defines the id to search for
  27123. * @return the found skeleton or null if not found at all.
  27124. */
  27125. Scene.prototype.getLastSkeletonByID = function (id) {
  27126. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27127. if (this.skeletons[index].id === id) {
  27128. return this.skeletons[index];
  27129. }
  27130. }
  27131. return null;
  27132. };
  27133. /**
  27134. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27135. * @param id defines the id to search for
  27136. * @return the found skeleton or null if not found at all.
  27137. */
  27138. Scene.prototype.getSkeletonById = function (id) {
  27139. for (var index = 0; index < this.skeletons.length; index++) {
  27140. if (this.skeletons[index].id === id) {
  27141. return this.skeletons[index];
  27142. }
  27143. }
  27144. return null;
  27145. };
  27146. /**
  27147. * Gets a skeleton using a given name
  27148. * @param name defines the name to search for
  27149. * @return the found skeleton or null if not found at all.
  27150. */
  27151. Scene.prototype.getSkeletonByName = function (name) {
  27152. for (var index = 0; index < this.skeletons.length; index++) {
  27153. if (this.skeletons[index].name === name) {
  27154. return this.skeletons[index];
  27155. }
  27156. }
  27157. return null;
  27158. };
  27159. /**
  27160. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27161. * @param id defines the id to search for
  27162. * @return the found morph target manager or null if not found at all.
  27163. */
  27164. Scene.prototype.getMorphTargetManagerById = function (id) {
  27165. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27166. if (this.morphTargetManagers[index].uniqueId === id) {
  27167. return this.morphTargetManagers[index];
  27168. }
  27169. }
  27170. return null;
  27171. };
  27172. /**
  27173. * Gets a boolean indicating if the given mesh is active
  27174. * @param mesh defines the mesh to look for
  27175. * @returns true if the mesh is in the active list
  27176. */
  27177. Scene.prototype.isActiveMesh = function (mesh) {
  27178. return (this._activeMeshes.indexOf(mesh) !== -1);
  27179. };
  27180. /**
  27181. * Return a the first highlight layer of the scene with a given name.
  27182. * @param name The name of the highlight layer to look for.
  27183. * @return The highlight layer if found otherwise null.
  27184. */
  27185. Scene.prototype.getHighlightLayerByName = function (name) {
  27186. for (var index = 0; index < this.effectLayers.length; index++) {
  27187. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27188. return this.effectLayers[index];
  27189. }
  27190. }
  27191. return null;
  27192. };
  27193. /**
  27194. * Return a the first highlight layer of the scene with a given name.
  27195. * @param name The name of the highlight layer to look for.
  27196. * @return The highlight layer if found otherwise null.
  27197. */
  27198. Scene.prototype.getGlowLayerByName = function (name) {
  27199. for (var index = 0; index < this.effectLayers.length; index++) {
  27200. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27201. return this.effectLayers[index];
  27202. }
  27203. }
  27204. return null;
  27205. };
  27206. Object.defineProperty(Scene.prototype, "uid", {
  27207. /**
  27208. * Return a unique id as a string which can serve as an identifier for the scene
  27209. */
  27210. get: function () {
  27211. if (!this._uid) {
  27212. this._uid = BABYLON.Tools.RandomId();
  27213. }
  27214. return this._uid;
  27215. },
  27216. enumerable: true,
  27217. configurable: true
  27218. });
  27219. /**
  27220. * Add an externaly attached data from its key.
  27221. * This method call will fail and return false, if such key already exists.
  27222. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27223. * @param key the unique key that identifies the data
  27224. * @param data the data object to associate to the key for this Engine instance
  27225. * @return true if no such key were already present and the data was added successfully, false otherwise
  27226. */
  27227. Scene.prototype.addExternalData = function (key, data) {
  27228. if (!this._externalData) {
  27229. this._externalData = new BABYLON.StringDictionary();
  27230. }
  27231. return this._externalData.add(key, data);
  27232. };
  27233. /**
  27234. * Get an externaly attached data from its key
  27235. * @param key the unique key that identifies the data
  27236. * @return the associated data, if present (can be null), or undefined if not present
  27237. */
  27238. Scene.prototype.getExternalData = function (key) {
  27239. if (!this._externalData) {
  27240. return null;
  27241. }
  27242. return this._externalData.get(key);
  27243. };
  27244. /**
  27245. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27246. * @param key the unique key that identifies the data
  27247. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27248. * @return the associated data, can be null if the factory returned null.
  27249. */
  27250. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27251. if (!this._externalData) {
  27252. this._externalData = new BABYLON.StringDictionary();
  27253. }
  27254. return this._externalData.getOrAddWithFactory(key, factory);
  27255. };
  27256. /**
  27257. * Remove an externaly attached data from the Engine instance
  27258. * @param key the unique key that identifies the data
  27259. * @return true if the data was successfully removed, false if it doesn't exist
  27260. */
  27261. Scene.prototype.removeExternalData = function (key) {
  27262. return this._externalData.remove(key);
  27263. };
  27264. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27265. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27266. if (mesh.showSubMeshesBoundingBox) {
  27267. var boundingInfo = subMesh.getBoundingInfo();
  27268. if (boundingInfo !== null && boundingInfo !== undefined) {
  27269. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27270. }
  27271. }
  27272. var material = subMesh.getMaterial();
  27273. if (material !== null && material !== undefined) {
  27274. // Render targets
  27275. if (material.getRenderTargetTextures !== undefined) {
  27276. if (this._processedMaterials.indexOf(material) === -1) {
  27277. this._processedMaterials.push(material);
  27278. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27279. }
  27280. }
  27281. // Dispatch
  27282. this._activeIndices.addCount(subMesh.indexCount, false);
  27283. this._renderingManager.dispatch(subMesh, mesh, material);
  27284. }
  27285. }
  27286. };
  27287. /**
  27288. * Clear the processed materials smart array preventing retention point in material dispose.
  27289. */
  27290. Scene.prototype.freeProcessedMaterials = function () {
  27291. this._processedMaterials.dispose();
  27292. };
  27293. /**
  27294. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27295. */
  27296. Scene.prototype.freeActiveMeshes = function () {
  27297. this._activeMeshes.dispose();
  27298. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27299. this.activeCamera._activeMeshes.dispose();
  27300. }
  27301. if (this.activeCameras) {
  27302. for (var i = 0; i < this.activeCameras.length; i++) {
  27303. var activeCamera = this.activeCameras[i];
  27304. if (activeCamera && activeCamera._activeMeshes) {
  27305. activeCamera._activeMeshes.dispose();
  27306. }
  27307. }
  27308. }
  27309. };
  27310. /**
  27311. * Clear the info related to rendering groups preventing retention points during dispose.
  27312. */
  27313. Scene.prototype.freeRenderingGroups = function () {
  27314. if (this._renderingManager) {
  27315. this._renderingManager.freeRenderingGroups();
  27316. }
  27317. if (this.textures) {
  27318. for (var i = 0; i < this.textures.length; i++) {
  27319. var texture = this.textures[i];
  27320. if (texture && texture.renderList) {
  27321. texture.freeRenderingGroups();
  27322. }
  27323. }
  27324. }
  27325. };
  27326. /** @hidden */
  27327. Scene.prototype._isInIntermediateRendering = function () {
  27328. return this._intermediateRendering;
  27329. };
  27330. /**
  27331. * Defines the current active mesh candidate provider
  27332. * @param provider defines the provider to use
  27333. */
  27334. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27335. this._activeMeshCandidateProvider = provider;
  27336. };
  27337. /**
  27338. * Gets the current active mesh candidate provider
  27339. * @returns the current active mesh candidate provider
  27340. */
  27341. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27342. return this._activeMeshCandidateProvider;
  27343. };
  27344. /**
  27345. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27346. * @returns the current scene
  27347. */
  27348. Scene.prototype.freezeActiveMeshes = function () {
  27349. if (!this.activeCamera) {
  27350. return this;
  27351. }
  27352. if (!this._frustumPlanes) {
  27353. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27354. }
  27355. this._evaluateActiveMeshes();
  27356. this._activeMeshesFrozen = true;
  27357. return this;
  27358. };
  27359. /**
  27360. * Use this function to restart evaluating active meshes on every frame
  27361. * @returns the current scene
  27362. */
  27363. Scene.prototype.unfreezeActiveMeshes = function () {
  27364. this._activeMeshesFrozen = false;
  27365. return this;
  27366. };
  27367. Scene.prototype._evaluateActiveMeshes = function () {
  27368. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27369. return;
  27370. }
  27371. if (!this.activeCamera) {
  27372. return;
  27373. }
  27374. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27375. this.activeCamera._activeMeshes.reset();
  27376. this._activeMeshes.reset();
  27377. this._renderingManager.reset();
  27378. this._processedMaterials.reset();
  27379. this._activeParticleSystems.reset();
  27380. this._activeSkeletons.reset();
  27381. this._softwareSkinnedMeshes.reset();
  27382. if (this._boundingBoxRenderer) {
  27383. this._boundingBoxRenderer.reset();
  27384. }
  27385. // Meshes
  27386. var meshes;
  27387. var len;
  27388. var checkIsEnabled = true;
  27389. // Determine mesh candidates
  27390. if (this._activeMeshCandidateProvider !== undefined) {
  27391. // Use _activeMeshCandidateProvider
  27392. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27393. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27394. if (meshes !== undefined) {
  27395. len = meshes.length;
  27396. }
  27397. else {
  27398. len = 0;
  27399. }
  27400. }
  27401. else if (this._selectionOctree !== undefined) {
  27402. // Octree
  27403. var selection = this._selectionOctree.select(this._frustumPlanes);
  27404. meshes = selection.data;
  27405. len = selection.length;
  27406. }
  27407. else {
  27408. // Full scene traversal
  27409. len = this.meshes.length;
  27410. meshes = this.meshes;
  27411. }
  27412. // Check each mesh
  27413. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27414. mesh = meshes[meshIndex];
  27415. if (mesh.isBlocked) {
  27416. continue;
  27417. }
  27418. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27419. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27420. continue;
  27421. }
  27422. mesh.computeWorldMatrix();
  27423. // Intersections
  27424. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27425. this._meshesForIntersections.pushNoDuplicate(mesh);
  27426. }
  27427. // Switch to current LOD
  27428. meshLOD = mesh.getLOD(this.activeCamera);
  27429. if (meshLOD === undefined || meshLOD === null) {
  27430. continue;
  27431. }
  27432. mesh._preActivate();
  27433. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27434. this._activeMeshes.push(mesh);
  27435. this.activeCamera._activeMeshes.push(mesh);
  27436. mesh._activate(this._renderId);
  27437. if (meshLOD !== mesh) {
  27438. meshLOD._activate(this._renderId);
  27439. }
  27440. this._activeMesh(mesh, meshLOD);
  27441. }
  27442. }
  27443. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27444. // Particle systems
  27445. if (this.particlesEnabled) {
  27446. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27447. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27448. var particleSystem = this.particleSystems[particleIndex];
  27449. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27450. continue;
  27451. }
  27452. var emitter = particleSystem.emitter;
  27453. if (!emitter.position || emitter.isEnabled()) {
  27454. this._activeParticleSystems.push(particleSystem);
  27455. particleSystem.animate();
  27456. this._renderingManager.dispatchParticles(particleSystem);
  27457. }
  27458. }
  27459. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27460. }
  27461. };
  27462. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27463. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27464. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27465. mesh.skeleton.prepare();
  27466. }
  27467. if (!mesh.computeBonesUsingShaders) {
  27468. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27469. }
  27470. }
  27471. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27472. var boundingInfo = sourceMesh.getBoundingInfo();
  27473. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27474. }
  27475. if (mesh !== undefined && mesh !== null
  27476. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27477. // Submeshes Octrees
  27478. var len;
  27479. var subMeshes;
  27480. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27481. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27482. len = intersections.length;
  27483. subMeshes = intersections.data;
  27484. }
  27485. else {
  27486. subMeshes = mesh.subMeshes;
  27487. len = subMeshes.length;
  27488. }
  27489. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27490. subMesh = subMeshes[subIndex];
  27491. this._evaluateSubMesh(subMesh, mesh);
  27492. }
  27493. }
  27494. };
  27495. /**
  27496. * Update the transform matrix to update from the current active camera
  27497. * @param force defines a boolean used to force the update even if cache is up to date
  27498. */
  27499. Scene.prototype.updateTransformMatrix = function (force) {
  27500. if (!this.activeCamera) {
  27501. return;
  27502. }
  27503. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27504. };
  27505. /**
  27506. * Defines an alternate camera (used mostly in VR-like scenario where two cameras can render the same scene from a slightly different point of view)
  27507. * @param alternateCamera defines the camera to use
  27508. */
  27509. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27510. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27511. };
  27512. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27513. if (camera && camera._skipRendering) {
  27514. return;
  27515. }
  27516. var engine = this._engine;
  27517. this.activeCamera = camera;
  27518. if (!this.activeCamera)
  27519. throw new Error("Active camera not set");
  27520. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27521. // Viewport
  27522. engine.setViewport(this.activeCamera.viewport);
  27523. // Camera
  27524. this.resetCachedMaterial();
  27525. this._renderId++;
  27526. this.updateTransformMatrix();
  27527. if (camera._alternateCamera) {
  27528. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27529. this._alternateRendering = true;
  27530. }
  27531. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27532. // Meshes
  27533. this._evaluateActiveMeshes();
  27534. // Software skinning
  27535. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27536. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27537. mesh.applySkeleton(mesh.skeleton);
  27538. }
  27539. // Render targets
  27540. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27541. var needsRestoreFrameBuffer = false;
  27542. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27543. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27544. }
  27545. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27546. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27547. }
  27548. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27549. this._intermediateRendering = true;
  27550. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27551. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27552. var renderTarget = this._renderTargets.data[renderIndex];
  27553. if (renderTarget._shouldRender()) {
  27554. this._renderId++;
  27555. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27556. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27557. }
  27558. }
  27559. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27560. this._intermediateRendering = false;
  27561. this._renderId++;
  27562. needsRestoreFrameBuffer = true; // Restore back buffer
  27563. }
  27564. // Render EffecttLayer Texture
  27565. var stencilState = this._engine.getStencilBuffer();
  27566. var renderEffects = false;
  27567. var needStencil = false;
  27568. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27569. this._intermediateRendering = true;
  27570. for (var i = 0; i < this.effectLayers.length; i++) {
  27571. var effectLayer = this.effectLayers[i];
  27572. if (effectLayer.shouldRender() &&
  27573. (!effectLayer.camera ||
  27574. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27575. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27576. renderEffects = true;
  27577. needStencil = needStencil || effectLayer.needStencil();
  27578. var renderTarget = effectLayer._mainTexture;
  27579. if (renderTarget._shouldRender()) {
  27580. this._renderId++;
  27581. renderTarget.render(false, false);
  27582. needsRestoreFrameBuffer = true;
  27583. }
  27584. }
  27585. }
  27586. this._intermediateRendering = false;
  27587. this._renderId++;
  27588. }
  27589. if (needsRestoreFrameBuffer) {
  27590. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27591. }
  27592. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27593. // Prepare Frame
  27594. this.postProcessManager._prepareFrame();
  27595. // Backgrounds
  27596. var layerIndex;
  27597. var layer;
  27598. if (this.layers.length) {
  27599. engine.setDepthBuffer(false);
  27600. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27601. layer = this.layers[layerIndex];
  27602. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27603. layer.render();
  27604. }
  27605. }
  27606. engine.setDepthBuffer(true);
  27607. }
  27608. // Activate effect Layer stencil
  27609. if (needStencil) {
  27610. this._engine.setStencilBuffer(true);
  27611. }
  27612. // Render
  27613. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27614. this._renderingManager.render(null, null, true, true);
  27615. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27616. // Restore effect Layer stencil
  27617. if (needStencil) {
  27618. this._engine.setStencilBuffer(stencilState);
  27619. }
  27620. // Bounding boxes
  27621. if (this._boundingBoxRenderer) {
  27622. this._boundingBoxRenderer.render();
  27623. }
  27624. // Lens flares
  27625. if (this.lensFlaresEnabled) {
  27626. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27627. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27628. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27629. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27630. lensFlareSystem.render();
  27631. }
  27632. }
  27633. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27634. }
  27635. // Effect Layer
  27636. if (renderEffects) {
  27637. engine.setDepthBuffer(false);
  27638. for (var i = 0; i < this.effectLayers.length; i++) {
  27639. if (this.effectLayers[i].shouldRender()) {
  27640. this.effectLayers[i].render();
  27641. }
  27642. }
  27643. engine.setDepthBuffer(true);
  27644. }
  27645. // Foregrounds
  27646. if (this.layers.length) {
  27647. engine.setDepthBuffer(false);
  27648. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27649. layer = this.layers[layerIndex];
  27650. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27651. layer.render();
  27652. }
  27653. }
  27654. engine.setDepthBuffer(true);
  27655. }
  27656. // Finalize frame
  27657. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27658. // Reset some special arrays
  27659. this._renderTargets.reset();
  27660. this._alternateRendering = false;
  27661. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27662. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27663. };
  27664. Scene.prototype._processSubCameras = function (camera) {
  27665. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27666. this._renderForCamera(camera);
  27667. return;
  27668. }
  27669. // rig cameras
  27670. for (var index = 0; index < camera._rigCameras.length; index++) {
  27671. this._renderForCamera(camera._rigCameras[index], camera);
  27672. }
  27673. this.activeCamera = camera;
  27674. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27675. };
  27676. Scene.prototype._checkIntersections = function () {
  27677. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27678. var sourceMesh = this._meshesForIntersections.data[index];
  27679. if (!sourceMesh.actionManager) {
  27680. continue;
  27681. }
  27682. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27683. var action = sourceMesh.actionManager.actions[actionIndex];
  27684. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27685. var parameters = action.getTriggerParameter();
  27686. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27687. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27688. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27689. if (areIntersecting && currentIntersectionInProgress === -1) {
  27690. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27691. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27692. sourceMesh._intersectionsInProgress.push(otherMesh);
  27693. }
  27694. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27695. sourceMesh._intersectionsInProgress.push(otherMesh);
  27696. }
  27697. }
  27698. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27699. //They intersected, and now they don't.
  27700. //is this trigger an exit trigger? execute an event.
  27701. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27702. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27703. }
  27704. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27705. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27706. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27707. return otherMesh === parameterMesh;
  27708. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27709. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27710. }
  27711. }
  27712. }
  27713. }
  27714. }
  27715. };
  27716. /**
  27717. * Render the scene
  27718. */
  27719. Scene.prototype.render = function () {
  27720. if (this.isDisposed) {
  27721. return;
  27722. }
  27723. this._activeParticles.fetchNewFrame();
  27724. this._totalVertices.fetchNewFrame();
  27725. this._activeIndices.fetchNewFrame();
  27726. this._activeBones.fetchNewFrame();
  27727. this._meshesForIntersections.reset();
  27728. this.resetCachedMaterial();
  27729. this.onBeforeAnimationsObservable.notifyObservers(this);
  27730. // Actions
  27731. if (this.actionManager) {
  27732. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27733. }
  27734. //Simplification Queue
  27735. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27736. this.simplificationQueue.executeNext();
  27737. }
  27738. if (this._engine.isDeterministicLockStep()) {
  27739. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27740. var defaultFPS = (60.0 / 1000.0);
  27741. var defaultFrameTime = 1000 / 60; // frame time in MS
  27742. if (this._physicsEngine) {
  27743. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27744. }
  27745. var stepsTaken = 0;
  27746. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27747. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27748. internalSteps = Math.min(internalSteps, maxSubSteps);
  27749. do {
  27750. this.onBeforeStepObservable.notifyObservers(this);
  27751. // Animations
  27752. this._animationRatio = defaultFrameTime * defaultFPS;
  27753. this._animate();
  27754. this.onAfterAnimationsObservable.notifyObservers(this);
  27755. // Physics
  27756. if (this._physicsEngine) {
  27757. this.onBeforePhysicsObservable.notifyObservers(this);
  27758. this._physicsEngine._step(defaultFrameTime / 1000);
  27759. this.onAfterPhysicsObservable.notifyObservers(this);
  27760. }
  27761. this.onAfterStepObservable.notifyObservers(this);
  27762. this._currentStepId++;
  27763. stepsTaken++;
  27764. deltaTime -= defaultFrameTime;
  27765. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27766. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27767. }
  27768. else {
  27769. // Animations
  27770. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27771. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27772. this._animate();
  27773. this.onAfterAnimationsObservable.notifyObservers(this);
  27774. // Physics
  27775. if (this._physicsEngine) {
  27776. this.onBeforePhysicsObservable.notifyObservers(this);
  27777. this._physicsEngine._step(deltaTime / 1000.0);
  27778. this.onAfterPhysicsObservable.notifyObservers(this);
  27779. }
  27780. }
  27781. // update gamepad manager
  27782. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27783. this._gamepadManager._checkGamepadsStatus();
  27784. }
  27785. // Update Cameras
  27786. if (this.activeCameras.length > 0) {
  27787. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27788. var camera = this.activeCameras[cameraIndex];
  27789. camera.update();
  27790. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27791. // rig cameras
  27792. for (var index = 0; index < camera._rigCameras.length; index++) {
  27793. camera._rigCameras[index].update();
  27794. }
  27795. }
  27796. }
  27797. }
  27798. else if (this.activeCamera) {
  27799. this.activeCamera.update();
  27800. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27801. // rig cameras
  27802. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27803. this.activeCamera._rigCameras[index].update();
  27804. }
  27805. }
  27806. }
  27807. // Before render
  27808. this.onBeforeRenderObservable.notifyObservers(this);
  27809. // Customs render targets
  27810. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27811. var engine = this.getEngine();
  27812. var currentActiveCamera = this.activeCamera;
  27813. if (this.renderTargetsEnabled) {
  27814. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27815. this._intermediateRendering = true;
  27816. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27817. var renderTarget = this.customRenderTargets[customIndex];
  27818. if (renderTarget._shouldRender()) {
  27819. this._renderId++;
  27820. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27821. if (!this.activeCamera)
  27822. throw new Error("Active camera not set");
  27823. // Viewport
  27824. engine.setViewport(this.activeCamera.viewport);
  27825. // Camera
  27826. this.updateTransformMatrix();
  27827. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27828. }
  27829. }
  27830. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27831. this._intermediateRendering = false;
  27832. this._renderId++;
  27833. }
  27834. // Restore back buffer
  27835. if (this.customRenderTargets.length > 0) {
  27836. engine.restoreDefaultFramebuffer();
  27837. }
  27838. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27839. this.activeCamera = currentActiveCamera;
  27840. // Procedural textures
  27841. if (this.proceduralTexturesEnabled) {
  27842. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27843. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27844. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27845. if (proceduralTexture._shouldRender()) {
  27846. proceduralTexture.render();
  27847. }
  27848. }
  27849. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27850. }
  27851. // Clear
  27852. if (this.autoClearDepthAndStencil || this.autoClear) {
  27853. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27854. }
  27855. // Shadows
  27856. if (this.shadowsEnabled) {
  27857. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27858. var light = this.lights[lightIndex];
  27859. var shadowGenerator = light.getShadowGenerator();
  27860. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27861. var shadowMap = (shadowGenerator.getShadowMap());
  27862. if (this.textures.indexOf(shadowMap) !== -1) {
  27863. this._renderTargets.push(shadowMap);
  27864. }
  27865. }
  27866. }
  27867. }
  27868. // Depth renderer
  27869. for (var key in this._depthRenderer) {
  27870. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27871. }
  27872. // Geometry renderer
  27873. if (this._geometryBufferRenderer) {
  27874. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27875. }
  27876. // RenderPipeline
  27877. if (this._postProcessRenderPipelineManager) {
  27878. this._postProcessRenderPipelineManager.update();
  27879. }
  27880. // Multi-cameras?
  27881. if (this.activeCameras.length > 0) {
  27882. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27883. if (cameraIndex > 0) {
  27884. this._engine.clear(null, false, true, true);
  27885. }
  27886. this._processSubCameras(this.activeCameras[cameraIndex]);
  27887. }
  27888. }
  27889. else {
  27890. if (!this.activeCamera) {
  27891. throw new Error("No camera defined");
  27892. }
  27893. this._processSubCameras(this.activeCamera);
  27894. }
  27895. // Intersection checks
  27896. this._checkIntersections();
  27897. // Update the audio listener attached to the camera
  27898. if (BABYLON.AudioEngine) {
  27899. this._updateAudioParameters();
  27900. }
  27901. // After render
  27902. if (this.afterRender) {
  27903. this.afterRender();
  27904. }
  27905. this.onAfterRenderObservable.notifyObservers(this);
  27906. // Cleaning
  27907. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27908. var data = this._toBeDisposed.data[index];
  27909. if (data) {
  27910. data.dispose();
  27911. }
  27912. this._toBeDisposed[index] = null;
  27913. }
  27914. this._toBeDisposed.reset();
  27915. if (this.dumpNextRenderTargets) {
  27916. this.dumpNextRenderTargets = false;
  27917. }
  27918. this._activeBones.addCount(0, true);
  27919. this._activeIndices.addCount(0, true);
  27920. this._activeParticles.addCount(0, true);
  27921. };
  27922. Scene.prototype._updateAudioParameters = function () {
  27923. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27924. return;
  27925. }
  27926. var listeningCamera;
  27927. var audioEngine = BABYLON.Engine.audioEngine;
  27928. if (this.activeCameras.length > 0) {
  27929. listeningCamera = this.activeCameras[0];
  27930. }
  27931. else {
  27932. listeningCamera = this.activeCamera;
  27933. }
  27934. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27935. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27936. // for VR cameras
  27937. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27938. listeningCamera = listeningCamera.rigCameras[0];
  27939. }
  27940. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27941. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27942. cameraDirection.normalize();
  27943. // To avoid some errors on GearVR
  27944. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27945. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27946. }
  27947. var i;
  27948. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27949. var sound = this.mainSoundTrack.soundCollection[i];
  27950. if (sound.useCustomAttenuation) {
  27951. sound.updateDistanceFromListener();
  27952. }
  27953. }
  27954. for (i = 0; i < this.soundTracks.length; i++) {
  27955. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27956. sound = this.soundTracks[i].soundCollection[j];
  27957. if (sound.useCustomAttenuation) {
  27958. sound.updateDistanceFromListener();
  27959. }
  27960. }
  27961. }
  27962. }
  27963. };
  27964. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27965. // Audio
  27966. /**
  27967. * Gets or sets if audio support is enabled
  27968. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27969. */
  27970. get: function () {
  27971. return this._audioEnabled;
  27972. },
  27973. set: function (value) {
  27974. this._audioEnabled = value;
  27975. if (BABYLON.AudioEngine) {
  27976. if (this._audioEnabled) {
  27977. this._enableAudio();
  27978. }
  27979. else {
  27980. this._disableAudio();
  27981. }
  27982. }
  27983. },
  27984. enumerable: true,
  27985. configurable: true
  27986. });
  27987. Scene.prototype._disableAudio = function () {
  27988. var i;
  27989. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27990. this.mainSoundTrack.soundCollection[i].pause();
  27991. }
  27992. for (i = 0; i < this.soundTracks.length; i++) {
  27993. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27994. this.soundTracks[i].soundCollection[j].pause();
  27995. }
  27996. }
  27997. };
  27998. Scene.prototype._enableAudio = function () {
  27999. var i;
  28000. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28001. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28002. this.mainSoundTrack.soundCollection[i].play();
  28003. }
  28004. }
  28005. for (i = 0; i < this.soundTracks.length; i++) {
  28006. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28007. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28008. this.soundTracks[i].soundCollection[j].play();
  28009. }
  28010. }
  28011. }
  28012. };
  28013. Object.defineProperty(Scene.prototype, "headphone", {
  28014. /**
  28015. * Gets or sets if audio will be output to headphones
  28016. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28017. */
  28018. get: function () {
  28019. return this._headphone;
  28020. },
  28021. set: function (value) {
  28022. this._headphone = value;
  28023. if (BABYLON.AudioEngine) {
  28024. if (this._headphone) {
  28025. this._switchAudioModeForHeadphones();
  28026. }
  28027. else {
  28028. this._switchAudioModeForNormalSpeakers();
  28029. }
  28030. }
  28031. },
  28032. enumerable: true,
  28033. configurable: true
  28034. });
  28035. Scene.prototype._switchAudioModeForHeadphones = function () {
  28036. this.mainSoundTrack.switchPanningModelToHRTF();
  28037. for (var i = 0; i < this.soundTracks.length; i++) {
  28038. this.soundTracks[i].switchPanningModelToHRTF();
  28039. }
  28040. };
  28041. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28042. this.mainSoundTrack.switchPanningModelToEqualPower();
  28043. for (var i = 0; i < this.soundTracks.length; i++) {
  28044. this.soundTracks[i].switchPanningModelToEqualPower();
  28045. }
  28046. };
  28047. /**
  28048. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28049. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28050. * @returns the created depth renderer
  28051. */
  28052. Scene.prototype.enableDepthRenderer = function (camera) {
  28053. camera = camera || this.activeCamera;
  28054. if (!camera) {
  28055. throw "No camera available to enable depth renderer";
  28056. }
  28057. if (!this._depthRenderer[camera.id]) {
  28058. var textureType = 0;
  28059. if (this._engine.getCaps().textureHalfFloatRender) {
  28060. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28061. }
  28062. else if (this._engine.getCaps().textureFloatRender) {
  28063. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28064. }
  28065. else {
  28066. throw "Depth renderer does not support int texture type";
  28067. }
  28068. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28069. }
  28070. return this._depthRenderer[camera.id];
  28071. };
  28072. /**
  28073. * Disables a depth renderer for a given camera
  28074. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28075. */
  28076. Scene.prototype.disableDepthRenderer = function (camera) {
  28077. camera = camera || this.activeCamera;
  28078. if (!camera || !this._depthRenderer[camera.id]) {
  28079. return;
  28080. }
  28081. this._depthRenderer[camera.id].dispose();
  28082. delete this._depthRenderer[camera.id];
  28083. };
  28084. /**
  28085. * Enables a GeometryBufferRender and associates it with the scene
  28086. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28087. * @returns the GeometryBufferRenderer
  28088. */
  28089. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28090. if (ratio === void 0) { ratio = 1; }
  28091. if (this._geometryBufferRenderer) {
  28092. return this._geometryBufferRenderer;
  28093. }
  28094. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28095. if (!this._geometryBufferRenderer.isSupported) {
  28096. this._geometryBufferRenderer = null;
  28097. }
  28098. return this._geometryBufferRenderer;
  28099. };
  28100. /**
  28101. * Disables the GeometryBufferRender associated with the scene
  28102. */
  28103. Scene.prototype.disableGeometryBufferRenderer = function () {
  28104. if (!this._geometryBufferRenderer) {
  28105. return;
  28106. }
  28107. this._geometryBufferRenderer.dispose();
  28108. this._geometryBufferRenderer = null;
  28109. };
  28110. /**
  28111. * Freeze all materials
  28112. * A frozen material will not be updatable but should be faster to render
  28113. */
  28114. Scene.prototype.freezeMaterials = function () {
  28115. for (var i = 0; i < this.materials.length; i++) {
  28116. this.materials[i].freeze();
  28117. }
  28118. };
  28119. /**
  28120. * Unfreeze all materials
  28121. * A frozen material will not be updatable but should be faster to render
  28122. */
  28123. Scene.prototype.unfreezeMaterials = function () {
  28124. for (var i = 0; i < this.materials.length; i++) {
  28125. this.materials[i].unfreeze();
  28126. }
  28127. };
  28128. /**
  28129. * Releases all held ressources
  28130. */
  28131. Scene.prototype.dispose = function () {
  28132. this.beforeRender = null;
  28133. this.afterRender = null;
  28134. this.skeletons = [];
  28135. this.morphTargetManagers = [];
  28136. this.importedMeshesFiles = new Array();
  28137. this.stopAllAnimations();
  28138. this.resetCachedMaterial();
  28139. for (var key in this._depthRenderer) {
  28140. this._depthRenderer[key].dispose();
  28141. }
  28142. if (this._gamepadManager) {
  28143. this._gamepadManager.dispose();
  28144. this._gamepadManager = null;
  28145. }
  28146. // Smart arrays
  28147. if (this.activeCamera) {
  28148. this.activeCamera._activeMeshes.dispose();
  28149. this.activeCamera = null;
  28150. }
  28151. this._activeMeshes.dispose();
  28152. this._renderingManager.dispose();
  28153. this._processedMaterials.dispose();
  28154. this._activeParticleSystems.dispose();
  28155. this._activeSkeletons.dispose();
  28156. this._softwareSkinnedMeshes.dispose();
  28157. this._renderTargets.dispose();
  28158. this._registeredForLateAnimationBindings.dispose();
  28159. if (this._boundingBoxRenderer) {
  28160. this._boundingBoxRenderer.dispose();
  28161. }
  28162. this._meshesForIntersections.dispose();
  28163. this._toBeDisposed.dispose();
  28164. // Abort active requests
  28165. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28166. var request = _a[_i];
  28167. request.abort();
  28168. }
  28169. // Debug layer
  28170. if (this._debugLayer) {
  28171. this._debugLayer.hide();
  28172. }
  28173. // Events
  28174. this.onDisposeObservable.notifyObservers(this);
  28175. this.onDisposeObservable.clear();
  28176. this.onBeforeRenderObservable.clear();
  28177. this.onAfterRenderObservable.clear();
  28178. this.onBeforeRenderTargetsRenderObservable.clear();
  28179. this.onAfterRenderTargetsRenderObservable.clear();
  28180. this.onAfterStepObservable.clear();
  28181. this.onBeforeStepObservable.clear();
  28182. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28183. this.onAfterActiveMeshesEvaluationObservable.clear();
  28184. this.onBeforeParticlesRenderingObservable.clear();
  28185. this.onAfterParticlesRenderingObservable.clear();
  28186. this.onBeforeSpritesRenderingObservable.clear();
  28187. this.onAfterSpritesRenderingObservable.clear();
  28188. this.onBeforeDrawPhaseObservable.clear();
  28189. this.onAfterDrawPhaseObservable.clear();
  28190. this.onBeforePhysicsObservable.clear();
  28191. this.onAfterPhysicsObservable.clear();
  28192. this.onBeforeAnimationsObservable.clear();
  28193. this.onAfterAnimationsObservable.clear();
  28194. this.onDataLoadedObservable.clear();
  28195. this.detachControl();
  28196. // Release sounds & sounds tracks
  28197. if (BABYLON.AudioEngine) {
  28198. this.disposeSounds();
  28199. }
  28200. // VR Helper
  28201. if (this.VRHelper) {
  28202. this.VRHelper.dispose();
  28203. }
  28204. // Detach cameras
  28205. var canvas = this._engine.getRenderingCanvas();
  28206. if (canvas) {
  28207. var index;
  28208. for (index = 0; index < this.cameras.length; index++) {
  28209. this.cameras[index].detachControl(canvas);
  28210. }
  28211. }
  28212. // Release animation groups
  28213. while (this.animationGroups.length) {
  28214. this.animationGroups[0].dispose();
  28215. }
  28216. // Release lights
  28217. while (this.lights.length) {
  28218. this.lights[0].dispose();
  28219. }
  28220. // Release meshes
  28221. while (this.meshes.length) {
  28222. this.meshes[0].dispose(true);
  28223. }
  28224. while (this.transformNodes.length) {
  28225. this.removeTransformNode(this.transformNodes[0]);
  28226. }
  28227. // Release cameras
  28228. while (this.cameras.length) {
  28229. this.cameras[0].dispose();
  28230. }
  28231. // Release materials
  28232. if (this.defaultMaterial) {
  28233. this.defaultMaterial.dispose();
  28234. }
  28235. while (this.multiMaterials.length) {
  28236. this.multiMaterials[0].dispose();
  28237. }
  28238. while (this.materials.length) {
  28239. this.materials[0].dispose();
  28240. }
  28241. // Release particles
  28242. while (this.particleSystems.length) {
  28243. this.particleSystems[0].dispose();
  28244. }
  28245. // Release sprites
  28246. while (this.spriteManagers.length) {
  28247. this.spriteManagers[0].dispose();
  28248. }
  28249. // Release postProcesses
  28250. while (this.postProcesses.length) {
  28251. this.postProcesses[0].dispose();
  28252. }
  28253. // Release layers
  28254. while (this.layers.length) {
  28255. this.layers[0].dispose();
  28256. }
  28257. while (this.effectLayers.length) {
  28258. this.effectLayers[0].dispose();
  28259. }
  28260. // Release textures
  28261. while (this.textures.length) {
  28262. this.textures[0].dispose();
  28263. }
  28264. // Release UBO
  28265. this._sceneUbo.dispose();
  28266. if (this._alternateSceneUbo) {
  28267. this._alternateSceneUbo.dispose();
  28268. }
  28269. // Post-processes
  28270. this.postProcessManager.dispose();
  28271. if (this._postProcessRenderPipelineManager) {
  28272. this._postProcessRenderPipelineManager.dispose();
  28273. }
  28274. // Physics
  28275. if (this._physicsEngine) {
  28276. this.disablePhysicsEngine();
  28277. }
  28278. // Remove from engine
  28279. index = this._engine.scenes.indexOf(this);
  28280. if (index > -1) {
  28281. this._engine.scenes.splice(index, 1);
  28282. }
  28283. this._engine.wipeCaches(true);
  28284. this._isDisposed = true;
  28285. };
  28286. Object.defineProperty(Scene.prototype, "isDisposed", {
  28287. /**
  28288. * Gets if the scene is already disposed
  28289. */
  28290. get: function () {
  28291. return this._isDisposed;
  28292. },
  28293. enumerable: true,
  28294. configurable: true
  28295. });
  28296. /**
  28297. * Releases sounds & soundtracks
  28298. */
  28299. Scene.prototype.disposeSounds = function () {
  28300. if (!this._mainSoundTrack) {
  28301. return;
  28302. }
  28303. this.mainSoundTrack.dispose();
  28304. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28305. this.soundTracks[scIndex].dispose();
  28306. }
  28307. };
  28308. /**
  28309. * Call this function to reduce memory footprint of the scene.
  28310. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28311. */
  28312. Scene.prototype.clearCachedVertexData = function () {
  28313. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28314. var mesh = this.meshes[meshIndex];
  28315. var geometry = mesh.geometry;
  28316. if (geometry) {
  28317. geometry._indices = [];
  28318. for (var vbName in geometry._vertexBuffers) {
  28319. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28320. continue;
  28321. }
  28322. geometry._vertexBuffers[vbName]._buffer._data = null;
  28323. }
  28324. }
  28325. }
  28326. };
  28327. /**
  28328. * This function will remove the local cached buffer data from texture.
  28329. * It will save memory but will prevent the texture from being rebuilt
  28330. */
  28331. Scene.prototype.cleanCachedTextureBuffer = function () {
  28332. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28333. var baseTexture = _a[_i];
  28334. var buffer = baseTexture._buffer;
  28335. if (buffer) {
  28336. baseTexture._buffer = null;
  28337. }
  28338. }
  28339. };
  28340. // Octrees
  28341. /**
  28342. * Get the world extend vectors with an optional filter
  28343. *
  28344. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28345. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28346. */
  28347. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28348. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28349. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28350. filterPredicate = filterPredicate || (function () { return true; });
  28351. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28352. mesh.computeWorldMatrix(true);
  28353. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28354. return;
  28355. }
  28356. var boundingInfo = mesh.getBoundingInfo();
  28357. var minBox = boundingInfo.boundingBox.minimumWorld;
  28358. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28359. BABYLON.Tools.CheckExtends(minBox, min, max);
  28360. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28361. });
  28362. return {
  28363. min: min,
  28364. max: max
  28365. };
  28366. };
  28367. /**
  28368. * Creates or updates the octree used to boost selection (picking)
  28369. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28370. * @param maxCapacity defines the maximum capacity per leaf
  28371. * @param maxDepth defines the maximum depth of the octree
  28372. * @returns an octree of AbstractMesh
  28373. */
  28374. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28375. if (maxCapacity === void 0) { maxCapacity = 64; }
  28376. if (maxDepth === void 0) { maxDepth = 2; }
  28377. if (!this._selectionOctree) {
  28378. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28379. }
  28380. var worldExtends = this.getWorldExtends();
  28381. // Update octree
  28382. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28383. return this._selectionOctree;
  28384. };
  28385. // Picking
  28386. /**
  28387. * Creates a ray that can be used to pick in the scene
  28388. * @param x defines the x coordinate of the origin (on-screen)
  28389. * @param y defines the y coordinate of the origin (on-screen)
  28390. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28391. * @param camera defines the camera to use for the picking
  28392. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28393. * @returns a Ray
  28394. */
  28395. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28396. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28397. var result = BABYLON.Ray.Zero();
  28398. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28399. return result;
  28400. };
  28401. /**
  28402. * Creates a ray that can be used to pick in the scene
  28403. * @param x defines the x coordinate of the origin (on-screen)
  28404. * @param y defines the y coordinate of the origin (on-screen)
  28405. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28406. * @param result defines the ray where to store the picking ray
  28407. * @param camera defines the camera to use for the picking
  28408. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28409. * @returns the current scene
  28410. */
  28411. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28412. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28413. var engine = this._engine;
  28414. if (!camera) {
  28415. if (!this.activeCamera)
  28416. throw new Error("Active camera not set");
  28417. camera = this.activeCamera;
  28418. }
  28419. var cameraViewport = camera.viewport;
  28420. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28421. // Moving coordinates to local viewport world
  28422. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28423. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28424. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28425. return this;
  28426. };
  28427. /**
  28428. * Creates a ray that can be used to pick in the scene
  28429. * @param x defines the x coordinate of the origin (on-screen)
  28430. * @param y defines the y coordinate of the origin (on-screen)
  28431. * @param camera defines the camera to use for the picking
  28432. * @returns a Ray
  28433. */
  28434. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28435. var result = BABYLON.Ray.Zero();
  28436. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28437. return result;
  28438. };
  28439. /**
  28440. * Creates a ray that can be used to pick in the scene
  28441. * @param x defines the x coordinate of the origin (on-screen)
  28442. * @param y defines the y coordinate of the origin (on-screen)
  28443. * @param result defines the ray where to store the picking ray
  28444. * @param camera defines the camera to use for the picking
  28445. * @returns the current scene
  28446. */
  28447. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28448. if (!BABYLON.PickingInfo) {
  28449. return this;
  28450. }
  28451. var engine = this._engine;
  28452. if (!camera) {
  28453. if (!this.activeCamera)
  28454. throw new Error("Active camera not set");
  28455. camera = this.activeCamera;
  28456. }
  28457. var cameraViewport = camera.viewport;
  28458. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28459. var identity = BABYLON.Matrix.Identity();
  28460. // Moving coordinates to local viewport world
  28461. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28462. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28463. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28464. return this;
  28465. };
  28466. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28467. if (!BABYLON.PickingInfo) {
  28468. return null;
  28469. }
  28470. var pickingInfo = null;
  28471. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28472. var mesh = this.meshes[meshIndex];
  28473. if (predicate) {
  28474. if (!predicate(mesh)) {
  28475. continue;
  28476. }
  28477. }
  28478. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28479. continue;
  28480. }
  28481. var world = mesh.getWorldMatrix();
  28482. var ray = rayFunction(world);
  28483. var result = mesh.intersects(ray, fastCheck);
  28484. if (!result || !result.hit)
  28485. continue;
  28486. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28487. continue;
  28488. pickingInfo = result;
  28489. if (fastCheck) {
  28490. break;
  28491. }
  28492. }
  28493. return pickingInfo || new BABYLON.PickingInfo();
  28494. };
  28495. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28496. if (!BABYLON.PickingInfo) {
  28497. return null;
  28498. }
  28499. var pickingInfos = new Array();
  28500. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28501. var mesh = this.meshes[meshIndex];
  28502. if (predicate) {
  28503. if (!predicate(mesh)) {
  28504. continue;
  28505. }
  28506. }
  28507. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28508. continue;
  28509. }
  28510. var world = mesh.getWorldMatrix();
  28511. var ray = rayFunction(world);
  28512. var result = mesh.intersects(ray, false);
  28513. if (!result || !result.hit)
  28514. continue;
  28515. pickingInfos.push(result);
  28516. }
  28517. return pickingInfos;
  28518. };
  28519. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28520. if (!BABYLON.PickingInfo) {
  28521. return null;
  28522. }
  28523. var pickingInfo = null;
  28524. if (!camera) {
  28525. if (!this.activeCamera) {
  28526. return null;
  28527. }
  28528. camera = this.activeCamera;
  28529. }
  28530. if (this.spriteManagers.length > 0) {
  28531. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28532. var spriteManager = this.spriteManagers[spriteIndex];
  28533. if (!spriteManager.isPickable) {
  28534. continue;
  28535. }
  28536. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28537. if (!result || !result.hit)
  28538. continue;
  28539. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28540. continue;
  28541. pickingInfo = result;
  28542. if (fastCheck) {
  28543. break;
  28544. }
  28545. }
  28546. }
  28547. return pickingInfo || new BABYLON.PickingInfo();
  28548. };
  28549. /** Launch a ray to try to pick a mesh in the scene
  28550. * @param x position on screen
  28551. * @param y position on screen
  28552. * @param 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
  28553. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28554. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28555. * @returns a PickingInfo
  28556. */
  28557. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28558. var _this = this;
  28559. if (!BABYLON.PickingInfo) {
  28560. return null;
  28561. }
  28562. return this._internalPick(function (world) {
  28563. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28564. return _this._tempPickingRay;
  28565. }, predicate, fastCheck);
  28566. };
  28567. /** Launch a ray to try to pick a sprite in the scene
  28568. * @param x position on screen
  28569. * @param y position on screen
  28570. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28571. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28572. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28573. * @returns a PickingInfo
  28574. */
  28575. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28576. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28577. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28578. };
  28579. /** Use the given ray to pick a mesh in the scene
  28580. * @param ray The ray to use to pick meshes
  28581. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28582. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28583. * @returns a PickingInfo
  28584. */
  28585. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28586. var _this = this;
  28587. var result = this._internalPick(function (world) {
  28588. if (!_this._pickWithRayInverseMatrix) {
  28589. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28590. }
  28591. world.invertToRef(_this._pickWithRayInverseMatrix);
  28592. if (!_this._cachedRayForTransform) {
  28593. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28594. }
  28595. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28596. return _this._cachedRayForTransform;
  28597. }, predicate, fastCheck);
  28598. if (result) {
  28599. result.ray = ray;
  28600. }
  28601. return result;
  28602. };
  28603. /**
  28604. * Launch a ray to try to pick a mesh in the scene
  28605. * @param x X position on screen
  28606. * @param y Y position on screen
  28607. * @param 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
  28608. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28609. * @returns an array of PickingInfo
  28610. */
  28611. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28612. var _this = this;
  28613. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28614. };
  28615. /**
  28616. * Launch a ray to try to pick a mesh in the scene
  28617. * @param ray Ray to use
  28618. * @param 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
  28619. * @returns an array of PickingInfo
  28620. */
  28621. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28622. var _this = this;
  28623. return this._internalMultiPick(function (world) {
  28624. if (!_this._pickWithRayInverseMatrix) {
  28625. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28626. }
  28627. world.invertToRef(_this._pickWithRayInverseMatrix);
  28628. if (!_this._cachedRayForTransform) {
  28629. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28630. }
  28631. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28632. return _this._cachedRayForTransform;
  28633. }, predicate);
  28634. };
  28635. /**
  28636. * Force the value of meshUnderPointer
  28637. * @param mesh defines the mesh to use
  28638. */
  28639. Scene.prototype.setPointerOverMesh = function (mesh) {
  28640. if (this._pointerOverMesh === mesh) {
  28641. return;
  28642. }
  28643. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28644. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28645. }
  28646. this._pointerOverMesh = mesh;
  28647. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28648. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28649. }
  28650. };
  28651. /**
  28652. * Gets the mesh under the pointer
  28653. * @returns a Mesh or null if no mesh is under the pointer
  28654. */
  28655. Scene.prototype.getPointerOverMesh = function () {
  28656. return this._pointerOverMesh;
  28657. };
  28658. /**
  28659. * Force the sprite under the pointer
  28660. * @param sprite defines the sprite to use
  28661. */
  28662. Scene.prototype.setPointerOverSprite = function (sprite) {
  28663. if (this._pointerOverSprite === sprite) {
  28664. return;
  28665. }
  28666. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28667. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28668. }
  28669. this._pointerOverSprite = sprite;
  28670. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28671. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28672. }
  28673. };
  28674. /**
  28675. * Gets the sprite under the pointer
  28676. * @returns a Sprite or null if no sprite is under the pointer
  28677. */
  28678. Scene.prototype.getPointerOverSprite = function () {
  28679. return this._pointerOverSprite;
  28680. };
  28681. // Physics
  28682. /**
  28683. * Gets the current physics engine
  28684. * @returns a PhysicsEngine or null if none attached
  28685. */
  28686. Scene.prototype.getPhysicsEngine = function () {
  28687. return this._physicsEngine;
  28688. };
  28689. /**
  28690. * Enables physics to the current scene
  28691. * @param gravity defines the scene's gravity for the physics engine
  28692. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28693. * @return a boolean indicating if the physics engine was initialized
  28694. */
  28695. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28696. if (gravity === void 0) { gravity = null; }
  28697. if (this._physicsEngine) {
  28698. return true;
  28699. }
  28700. try {
  28701. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28702. return true;
  28703. }
  28704. catch (e) {
  28705. BABYLON.Tools.Error(e.message);
  28706. return false;
  28707. }
  28708. };
  28709. /**
  28710. * Disables and disposes the physics engine associated with the scene
  28711. */
  28712. Scene.prototype.disablePhysicsEngine = function () {
  28713. if (!this._physicsEngine) {
  28714. return;
  28715. }
  28716. this._physicsEngine.dispose();
  28717. this._physicsEngine = null;
  28718. };
  28719. /**
  28720. * Gets a boolean indicating if there is an active physics engine
  28721. * @returns a boolean indicating if there is an active physics engine
  28722. */
  28723. Scene.prototype.isPhysicsEnabled = function () {
  28724. return this._physicsEngine !== undefined;
  28725. };
  28726. /**
  28727. * Deletes a physics compound impostor
  28728. * @param compound defines the compound to delete
  28729. */
  28730. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28731. var mesh = compound.parts[0].mesh;
  28732. if (mesh.physicsImpostor) {
  28733. mesh.physicsImpostor.dispose( /*true*/);
  28734. mesh.physicsImpostor = null;
  28735. }
  28736. };
  28737. // Misc.
  28738. /** @hidden */
  28739. Scene.prototype._rebuildGeometries = function () {
  28740. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28741. var geometry = _a[_i];
  28742. geometry._rebuild();
  28743. }
  28744. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28745. var mesh = _c[_b];
  28746. mesh._rebuild();
  28747. }
  28748. if (this.postProcessManager) {
  28749. this.postProcessManager._rebuild();
  28750. }
  28751. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28752. var layer = _e[_d];
  28753. layer._rebuild();
  28754. }
  28755. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28756. var effectLayer = _g[_f];
  28757. effectLayer._rebuild();
  28758. }
  28759. if (this._boundingBoxRenderer) {
  28760. this._boundingBoxRenderer._rebuild();
  28761. }
  28762. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28763. var system = _j[_h];
  28764. system.rebuild();
  28765. }
  28766. if (this._postProcessRenderPipelineManager) {
  28767. this._postProcessRenderPipelineManager._rebuild();
  28768. }
  28769. };
  28770. /** @hidden */
  28771. Scene.prototype._rebuildTextures = function () {
  28772. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28773. var texture = _a[_i];
  28774. texture._rebuild();
  28775. }
  28776. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28777. };
  28778. /**
  28779. * Creates a default light for the scene.
  28780. * @param replace Whether to replace the existing lights in the scene.
  28781. */
  28782. Scene.prototype.createDefaultLight = function (replace) {
  28783. if (replace === void 0) { replace = false; }
  28784. // Dispose existing light in replace mode.
  28785. if (replace) {
  28786. if (this.lights) {
  28787. for (var i = 0; i < this.lights.length; i++) {
  28788. this.lights[i].dispose();
  28789. }
  28790. }
  28791. }
  28792. // Light
  28793. if (this.lights.length === 0) {
  28794. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28795. }
  28796. };
  28797. /**
  28798. * Creates a default camera for the scene.
  28799. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28800. * @param replace Whether to replace the existing active camera in the scene.
  28801. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28802. */
  28803. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28804. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28805. if (replace === void 0) { replace = false; }
  28806. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28807. // Dispose existing camera in replace mode.
  28808. if (replace) {
  28809. if (this.activeCamera) {
  28810. this.activeCamera.dispose();
  28811. this.activeCamera = null;
  28812. }
  28813. }
  28814. // Camera
  28815. if (!this.activeCamera) {
  28816. var worldExtends = this.getWorldExtends();
  28817. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28818. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28819. var camera;
  28820. var radius = worldSize.length() * 1.5;
  28821. // empty scene scenario!
  28822. if (!isFinite(radius)) {
  28823. radius = 1;
  28824. worldCenter.copyFromFloats(0, 0, 0);
  28825. }
  28826. if (createArcRotateCamera) {
  28827. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28828. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28829. arcRotateCamera.wheelPrecision = 100 / radius;
  28830. camera = arcRotateCamera;
  28831. }
  28832. else {
  28833. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28834. freeCamera.setTarget(worldCenter);
  28835. camera = freeCamera;
  28836. }
  28837. camera.minZ = radius * 0.01;
  28838. camera.maxZ = radius * 1000;
  28839. camera.speed = radius * 0.2;
  28840. this.activeCamera = camera;
  28841. var canvas = this.getEngine().getRenderingCanvas();
  28842. if (attachCameraControls && canvas) {
  28843. camera.attachControl(canvas);
  28844. }
  28845. }
  28846. };
  28847. /**
  28848. * Creates a default camera and a default light
  28849. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28850. * @param replace defines if the camera and/or light will replace the existing ones
  28851. * @param attachCameraControls defines if attachControl will be called on the new camera
  28852. */
  28853. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28854. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28855. if (replace === void 0) { replace = false; }
  28856. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28857. this.createDefaultLight(replace);
  28858. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28859. };
  28860. /**
  28861. * Creates a new sky box
  28862. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28863. * @param environmentTexture defines the texture to use as environment texture
  28864. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28865. * @param scale defines the overall scale of the skybox
  28866. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28867. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28868. * @returns a new mesh holding the sky box
  28869. */
  28870. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28871. if (pbr === void 0) { pbr = false; }
  28872. if (scale === void 0) { scale = 1000; }
  28873. if (blur === void 0) { blur = 0; }
  28874. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28875. if (!environmentTexture) {
  28876. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28877. return null;
  28878. }
  28879. if (setGlobalEnvTexture) {
  28880. if (environmentTexture) {
  28881. this.environmentTexture = environmentTexture;
  28882. }
  28883. }
  28884. // Skybox
  28885. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28886. if (pbr) {
  28887. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28888. hdrSkyboxMaterial.backFaceCulling = false;
  28889. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28890. if (hdrSkyboxMaterial.reflectionTexture) {
  28891. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28892. }
  28893. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28894. hdrSkyboxMaterial.disableLighting = true;
  28895. hdrSkyboxMaterial.twoSidedLighting = true;
  28896. hdrSkybox.infiniteDistance = true;
  28897. hdrSkybox.material = hdrSkyboxMaterial;
  28898. }
  28899. else {
  28900. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28901. skyboxMaterial.backFaceCulling = false;
  28902. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28903. if (skyboxMaterial.reflectionTexture) {
  28904. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28905. }
  28906. skyboxMaterial.disableLighting = true;
  28907. hdrSkybox.infiniteDistance = true;
  28908. hdrSkybox.material = skyboxMaterial;
  28909. }
  28910. return hdrSkybox;
  28911. };
  28912. /**
  28913. * Creates a new environment
  28914. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28915. * @param options defines the options you can use to configure the environment
  28916. * @returns the new EnvironmentHelper
  28917. */
  28918. Scene.prototype.createDefaultEnvironment = function (options) {
  28919. if (BABYLON.EnvironmentHelper) {
  28920. return new BABYLON.EnvironmentHelper(options, this);
  28921. }
  28922. return null;
  28923. };
  28924. /**
  28925. * Creates a new VREXperienceHelper
  28926. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28927. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28928. * @returns a new VREXperienceHelper
  28929. */
  28930. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28931. if (webVROptions === void 0) { webVROptions = {}; }
  28932. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28933. };
  28934. // Tags
  28935. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28936. if (tagsQuery === undefined) {
  28937. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28938. return list;
  28939. }
  28940. var listByTags = [];
  28941. forEach = forEach || (function (item) { return; });
  28942. for (var i in list) {
  28943. var item = list[i];
  28944. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28945. listByTags.push(item);
  28946. forEach(item);
  28947. }
  28948. }
  28949. return listByTags;
  28950. };
  28951. /**
  28952. * Get a list of meshes by tags
  28953. * @param tagsQuery defines the tags query to use
  28954. * @param forEach defines a predicate used to filter results
  28955. * @returns an array of Mesh
  28956. */
  28957. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28958. return this._getByTags(this.meshes, tagsQuery, forEach);
  28959. };
  28960. /**
  28961. * Get a list of cameras by tags
  28962. * @param tagsQuery defines the tags query to use
  28963. * @param forEach defines a predicate used to filter results
  28964. * @returns an array of Camera
  28965. */
  28966. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28967. return this._getByTags(this.cameras, tagsQuery, forEach);
  28968. };
  28969. /**
  28970. * Get a list of lights by tags
  28971. * @param tagsQuery defines the tags query to use
  28972. * @param forEach defines a predicate used to filter results
  28973. * @returns an array of Light
  28974. */
  28975. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28976. return this._getByTags(this.lights, tagsQuery, forEach);
  28977. };
  28978. /**
  28979. * Get a list of materials by tags
  28980. * @param tagsQuery defines the tags query to use
  28981. * @param forEach defines a predicate used to filter results
  28982. * @returns an array of Material
  28983. */
  28984. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28985. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28986. };
  28987. /**
  28988. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28989. * This allowed control for front to back rendering or reversly depending of the special needs.
  28990. *
  28991. * @param renderingGroupId The rendering group id corresponding to its index
  28992. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28993. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28994. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28995. */
  28996. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28997. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28998. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28999. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29000. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29001. };
  29002. /**
  29003. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29004. *
  29005. * @param renderingGroupId The rendering group id corresponding to its index
  29006. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29007. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29008. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29009. */
  29010. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29011. if (depth === void 0) { depth = true; }
  29012. if (stencil === void 0) { stencil = true; }
  29013. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29014. };
  29015. /**
  29016. * Will flag all materials as dirty to trigger new shader compilation
  29017. * @param flag defines the flag used to specify which material part must be marked as dirty
  29018. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29019. */
  29020. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29021. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29022. var material = _a[_i];
  29023. if (predicate && !predicate(material)) {
  29024. continue;
  29025. }
  29026. material.markAsDirty(flag);
  29027. }
  29028. };
  29029. /** @hidden */
  29030. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29031. var _this = this;
  29032. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29033. this._activeRequests.push(request);
  29034. request.onCompleteObservable.add(function (request) {
  29035. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29036. });
  29037. return request;
  29038. };
  29039. /** @hidden */
  29040. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29041. var _this = this;
  29042. return new Promise(function (resolve, reject) {
  29043. _this._loadFile(url, function (data) {
  29044. resolve(data);
  29045. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29046. reject(exception);
  29047. });
  29048. });
  29049. };
  29050. // Statics
  29051. Scene._FOGMODE_NONE = 0;
  29052. Scene._FOGMODE_EXP = 1;
  29053. Scene._FOGMODE_EXP2 = 2;
  29054. Scene._FOGMODE_LINEAR = 3;
  29055. Scene._uniqueIdCounter = 0;
  29056. /**
  29057. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29058. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29059. */
  29060. Scene.MinDeltaTime = 1.0;
  29061. /**
  29062. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29063. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29064. */
  29065. Scene.MaxDeltaTime = 1000.0;
  29066. /** The distance in pixel that you have to move to prevent some events */
  29067. Scene.DragMovementThreshold = 10; // in pixels
  29068. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29069. Scene.LongPressDelay = 500; // in milliseconds
  29070. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29071. Scene.DoubleClickDelay = 300; // in milliseconds
  29072. /** If you need to check double click without raising a single click at first click, enable this flag */
  29073. Scene.ExclusiveDoubleClickMode = false;
  29074. return Scene;
  29075. }());
  29076. BABYLON.Scene = Scene;
  29077. })(BABYLON || (BABYLON = {}));
  29078. //# sourceMappingURL=babylon.scene.js.map
  29079. var BABYLON;
  29080. (function (BABYLON) {
  29081. /**
  29082. * Set of assets to keep when moving a scene into an asset container.
  29083. */
  29084. var KeepAssets = /** @class */ (function () {
  29085. function KeepAssets() {
  29086. /**
  29087. * Cameras to keep.
  29088. */
  29089. this.cameras = new Array();
  29090. /**
  29091. * Lights to keep.
  29092. */
  29093. this.lights = new Array();
  29094. /**
  29095. * Meshes to keep.
  29096. */
  29097. this.meshes = new Array();
  29098. /**
  29099. * Skeletons to keep.
  29100. */
  29101. this.skeletons = new Array();
  29102. /**
  29103. * ParticleSystems to keep.
  29104. */
  29105. this.particleSystems = new Array();
  29106. /**
  29107. * Animations to keep.
  29108. */
  29109. this.animations = new Array();
  29110. /**
  29111. * AnimationGroups to keep.
  29112. */
  29113. this.animationGroups = new Array();
  29114. /**
  29115. * MultiMaterials to keep.
  29116. */
  29117. this.multiMaterials = new Array();
  29118. /**
  29119. * Materials to keep.
  29120. */
  29121. this.materials = new Array();
  29122. /**
  29123. * MorphTargetManagers to keep.
  29124. */
  29125. this.morphTargetManagers = new Array();
  29126. /**
  29127. * Geometries to keep.
  29128. */
  29129. this.geometries = new Array();
  29130. /**
  29131. * TransformNodes to keep.
  29132. */
  29133. this.transformNodes = new Array();
  29134. /**
  29135. * LensFlareSystems to keep.
  29136. */
  29137. this.lensFlareSystems = new Array();
  29138. /**
  29139. * ShadowGenerators to keep.
  29140. */
  29141. this.shadowGenerators = new Array();
  29142. /**
  29143. * ActionManagers to keep.
  29144. */
  29145. this.actionManagers = new Array();
  29146. /**
  29147. * Sounds to keep.
  29148. */
  29149. this.sounds = new Array();
  29150. /**
  29151. * Textures to keep.
  29152. */
  29153. this.textures = new Array();
  29154. /**
  29155. * Effect layers to keep.
  29156. */
  29157. this.effectLayers = new Array();
  29158. }
  29159. return KeepAssets;
  29160. }());
  29161. BABYLON.KeepAssets = KeepAssets;
  29162. /**
  29163. * Container with a set of assets that can be added or removed from a scene.
  29164. */
  29165. var AssetContainer = /** @class */ (function () {
  29166. /**
  29167. * Instantiates an AssetContainer.
  29168. * @param scene The scene the AssetContainer belongs to.
  29169. */
  29170. function AssetContainer(scene) {
  29171. // Objects
  29172. /**
  29173. * Cameras populated in the container.
  29174. */
  29175. this.cameras = new Array();
  29176. /**
  29177. * Lights populated in the container.
  29178. */
  29179. this.lights = new Array();
  29180. /**
  29181. * Meshes populated in the container.
  29182. */
  29183. this.meshes = new Array();
  29184. /**
  29185. * Skeletons populated in the container.
  29186. */
  29187. this.skeletons = new Array();
  29188. /**
  29189. * ParticleSystems populated in the container.
  29190. */
  29191. this.particleSystems = new Array();
  29192. /**
  29193. * Animations populated in the container.
  29194. */
  29195. this.animations = new Array();
  29196. /**
  29197. * AnimationGroups populated in the container.
  29198. */
  29199. this.animationGroups = new Array();
  29200. /**
  29201. * MultiMaterials populated in the container.
  29202. */
  29203. this.multiMaterials = new Array();
  29204. /**
  29205. * Materials populated in the container.
  29206. */
  29207. this.materials = new Array();
  29208. /**
  29209. * MorphTargetManagers populated in the container.
  29210. */
  29211. this.morphTargetManagers = new Array();
  29212. /**
  29213. * Geometries populated in the container.
  29214. */
  29215. this.geometries = new Array();
  29216. /**
  29217. * TransformNodes populated in the container.
  29218. */
  29219. this.transformNodes = new Array();
  29220. /**
  29221. * LensFlareSystems populated in the container.
  29222. */
  29223. this.lensFlareSystems = new Array();
  29224. /**
  29225. * ShadowGenerators populated in the container.
  29226. */
  29227. this.shadowGenerators = new Array();
  29228. /**
  29229. * ActionManagers populated in the container.
  29230. */
  29231. this.actionManagers = new Array();
  29232. /**
  29233. * Sounds populated in the container.
  29234. */
  29235. this.sounds = new Array();
  29236. /**
  29237. * Textures populated in the container.
  29238. */
  29239. this.textures = new Array();
  29240. /**
  29241. * Effect layers populated in the container.
  29242. */
  29243. this.effectLayers = new Array();
  29244. this.scene = scene;
  29245. }
  29246. /**
  29247. * Adds all the assets from the container to the scene.
  29248. */
  29249. AssetContainer.prototype.addAllToScene = function () {
  29250. var _this = this;
  29251. this.cameras.forEach(function (o) {
  29252. _this.scene.addCamera(o);
  29253. });
  29254. this.lights.forEach(function (o) {
  29255. _this.scene.addLight(o);
  29256. });
  29257. this.meshes.forEach(function (o) {
  29258. _this.scene.addMesh(o);
  29259. });
  29260. this.skeletons.forEach(function (o) {
  29261. _this.scene.addSkeleton(o);
  29262. });
  29263. this.particleSystems.forEach(function (o) {
  29264. _this.scene.addParticleSystem(o);
  29265. });
  29266. this.animations.forEach(function (o) {
  29267. _this.scene.addAnimation(o);
  29268. });
  29269. this.animationGroups.forEach(function (o) {
  29270. _this.scene.addAnimationGroup(o);
  29271. });
  29272. this.multiMaterials.forEach(function (o) {
  29273. _this.scene.addMultiMaterial(o);
  29274. });
  29275. this.materials.forEach(function (o) {
  29276. _this.scene.addMaterial(o);
  29277. });
  29278. this.morphTargetManagers.forEach(function (o) {
  29279. _this.scene.addMorphTargetManager(o);
  29280. });
  29281. this.geometries.forEach(function (o) {
  29282. _this.scene.addGeometry(o);
  29283. });
  29284. this.transformNodes.forEach(function (o) {
  29285. _this.scene.addTransformNode(o);
  29286. });
  29287. this.lensFlareSystems.forEach(function (o) {
  29288. _this.scene.addLensFlareSystem(o);
  29289. });
  29290. this.actionManagers.forEach(function (o) {
  29291. _this.scene.addActionManager(o);
  29292. });
  29293. this.sounds.forEach(function (o) {
  29294. o.play();
  29295. o.autoplay = true;
  29296. _this.scene.mainSoundTrack.AddSound(o);
  29297. });
  29298. this.textures.forEach(function (o) {
  29299. _this.scene.addTexture(o);
  29300. });
  29301. this.effectLayers.forEach(function (o) {
  29302. _this.scene.addEffectLayer(o);
  29303. });
  29304. };
  29305. /**
  29306. * Removes all the assets in the container from the scene
  29307. */
  29308. AssetContainer.prototype.removeAllFromScene = function () {
  29309. var _this = this;
  29310. this.cameras.forEach(function (o) {
  29311. _this.scene.removeCamera(o);
  29312. });
  29313. this.lights.forEach(function (o) {
  29314. _this.scene.removeLight(o);
  29315. });
  29316. this.meshes.forEach(function (o) {
  29317. _this.scene.removeMesh(o);
  29318. });
  29319. this.skeletons.forEach(function (o) {
  29320. _this.scene.removeSkeleton(o);
  29321. });
  29322. this.particleSystems.forEach(function (o) {
  29323. _this.scene.removeParticleSystem(o);
  29324. });
  29325. this.animations.forEach(function (o) {
  29326. _this.scene.removeAnimation(o);
  29327. });
  29328. this.animationGroups.forEach(function (o) {
  29329. _this.scene.removeAnimationGroup(o);
  29330. });
  29331. this.multiMaterials.forEach(function (o) {
  29332. _this.scene.removeMultiMaterial(o);
  29333. });
  29334. this.materials.forEach(function (o) {
  29335. _this.scene.removeMaterial(o);
  29336. });
  29337. this.morphTargetManagers.forEach(function (o) {
  29338. _this.scene.removeMorphTargetManager(o);
  29339. });
  29340. this.geometries.forEach(function (o) {
  29341. _this.scene.removeGeometry(o);
  29342. });
  29343. this.transformNodes.forEach(function (o) {
  29344. _this.scene.removeTransformNode(o);
  29345. });
  29346. this.lensFlareSystems.forEach(function (o) {
  29347. _this.scene.removeLensFlareSystem(o);
  29348. });
  29349. this.actionManagers.forEach(function (o) {
  29350. _this.scene.removeActionManager(o);
  29351. });
  29352. this.sounds.forEach(function (o) {
  29353. o.stop();
  29354. o.autoplay = false;
  29355. _this.scene.mainSoundTrack.RemoveSound(o);
  29356. });
  29357. this.textures.forEach(function (o) {
  29358. _this.scene.removeTexture(o);
  29359. });
  29360. this.effectLayers.forEach(function (o) {
  29361. _this.scene.removeEffectLayer(o);
  29362. });
  29363. };
  29364. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29365. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29366. var asset = sourceAssets_1[_i];
  29367. var move = true;
  29368. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29369. var keepAsset = keepAssets_1[_a];
  29370. if (asset === keepAsset) {
  29371. move = false;
  29372. break;
  29373. }
  29374. }
  29375. if (move) {
  29376. targetAssets.push(asset);
  29377. }
  29378. }
  29379. };
  29380. /**
  29381. * Removes all the assets contained in the scene and adds them to the container.
  29382. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29383. */
  29384. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29385. if (keepAssets === undefined) {
  29386. keepAssets = new KeepAssets();
  29387. }
  29388. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29389. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29390. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29391. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29392. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29393. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29394. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29395. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29396. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29397. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29398. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29399. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29400. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29401. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29402. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29403. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29404. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29405. this.removeAllFromScene();
  29406. };
  29407. /**
  29408. * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.
  29409. * @returns the root mesh
  29410. */
  29411. AssetContainer.prototype.createRootMesh = function () {
  29412. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29413. this.meshes.forEach(function (m) {
  29414. if (!m.parent) {
  29415. rootMesh.addChild(m);
  29416. }
  29417. });
  29418. this.meshes.unshift(rootMesh);
  29419. return rootMesh;
  29420. };
  29421. return AssetContainer;
  29422. }());
  29423. BABYLON.AssetContainer = AssetContainer;
  29424. })(BABYLON || (BABYLON = {}));
  29425. //# sourceMappingURL=babylon.assetContainer.js.map
  29426. var BABYLON;
  29427. (function (BABYLON) {
  29428. var Buffer = /** @class */ (function () {
  29429. /**
  29430. * Constructor
  29431. * @param engine the engine
  29432. * @param data the data to use for this buffer
  29433. * @param updatable whether the data is updatable
  29434. * @param stride the stride (optional)
  29435. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29436. * @param instanced whether the buffer is instanced (optional)
  29437. * @param useBytes set to true if the stride in in bytes (optional)
  29438. */
  29439. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29440. if (stride === void 0) { stride = 0; }
  29441. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29442. if (instanced === void 0) { instanced = false; }
  29443. if (useBytes === void 0) { useBytes = false; }
  29444. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29445. this._engine = engine.getScene().getEngine();
  29446. }
  29447. else {
  29448. this._engine = engine;
  29449. }
  29450. this._updatable = updatable;
  29451. this._instanced = instanced;
  29452. this._data = data;
  29453. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29454. if (!postponeInternalCreation) { // by default
  29455. this.create();
  29456. }
  29457. }
  29458. /**
  29459. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29460. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29461. * @param offset defines offset in the buffer (0 by default)
  29462. * @param size defines the size in floats of attributes (position is 3 for instance)
  29463. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29464. * @param instanced defines if the vertex buffer contains indexed data
  29465. * @param useBytes defines if the offset and stride are in bytes
  29466. * @returns the new vertex buffer
  29467. */
  29468. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29469. if (useBytes === void 0) { useBytes = false; }
  29470. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29471. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29472. // a lot of these parameters are ignored as they are overriden by the buffer
  29473. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29474. };
  29475. // Properties
  29476. Buffer.prototype.isUpdatable = function () {
  29477. return this._updatable;
  29478. };
  29479. Buffer.prototype.getData = function () {
  29480. return this._data;
  29481. };
  29482. Buffer.prototype.getBuffer = function () {
  29483. return this._buffer;
  29484. };
  29485. /**
  29486. * Gets the stride in float32 units (i.e. byte stride / 4).
  29487. * May not be an integer if the byte stride is not divisible by 4.
  29488. * DEPRECATED. Use byteStride instead.
  29489. * @returns the stride in float32 units
  29490. */
  29491. Buffer.prototype.getStrideSize = function () {
  29492. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29493. };
  29494. // Methods
  29495. Buffer.prototype.create = function (data) {
  29496. if (data === void 0) { data = null; }
  29497. if (!data && this._buffer) {
  29498. return; // nothing to do
  29499. }
  29500. data = data || this._data;
  29501. if (!data) {
  29502. return;
  29503. }
  29504. if (!this._buffer) { // create buffer
  29505. if (this._updatable) {
  29506. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29507. this._data = data;
  29508. }
  29509. else {
  29510. this._buffer = this._engine.createVertexBuffer(data);
  29511. }
  29512. }
  29513. else if (this._updatable) { // update buffer
  29514. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29515. this._data = data;
  29516. }
  29517. };
  29518. Buffer.prototype._rebuild = function () {
  29519. this._buffer = null;
  29520. this.create(this._data);
  29521. };
  29522. Buffer.prototype.update = function (data) {
  29523. this.create(data);
  29524. };
  29525. /**
  29526. * Updates the data directly.
  29527. * @param data the new data
  29528. * @param offset the new offset
  29529. * @param vertexCount the vertex count (optional)
  29530. * @param useBytes set to true if the offset is in bytes
  29531. */
  29532. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29533. if (useBytes === void 0) { useBytes = false; }
  29534. if (!this._buffer) {
  29535. return;
  29536. }
  29537. if (this._updatable) { // update buffer
  29538. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29539. this._data = null;
  29540. }
  29541. };
  29542. Buffer.prototype.dispose = function () {
  29543. if (!this._buffer) {
  29544. return;
  29545. }
  29546. if (this._engine._releaseBuffer(this._buffer)) {
  29547. this._buffer = null;
  29548. }
  29549. };
  29550. return Buffer;
  29551. }());
  29552. BABYLON.Buffer = Buffer;
  29553. })(BABYLON || (BABYLON = {}));
  29554. //# sourceMappingURL=babylon.buffer.js.map
  29555. var BABYLON;
  29556. (function (BABYLON) {
  29557. var VertexBuffer = /** @class */ (function () {
  29558. /**
  29559. * Constructor
  29560. * @param engine the engine
  29561. * @param data the data to use for this vertex buffer
  29562. * @param kind the vertex buffer kind
  29563. * @param updatable whether the data is updatable
  29564. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29565. * @param stride the stride (optional)
  29566. * @param instanced whether the buffer is instanced (optional)
  29567. * @param offset the offset of the data (optional)
  29568. * @param size the number of components (optional)
  29569. * @param type the type of the component (optional)
  29570. * @param normalized whether the data contains normalized data (optional)
  29571. * @param useBytes set to true if stride and offset are in bytes (optional)
  29572. */
  29573. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29574. if (normalized === void 0) { normalized = false; }
  29575. if (useBytes === void 0) { useBytes = false; }
  29576. if (data instanceof BABYLON.Buffer) {
  29577. this._buffer = data;
  29578. this._ownsBuffer = false;
  29579. }
  29580. else {
  29581. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29582. this._ownsBuffer = true;
  29583. }
  29584. this._kind = kind;
  29585. if (type == undefined) {
  29586. var data_1 = this.getData();
  29587. this.type = VertexBuffer.FLOAT;
  29588. if (data_1 instanceof Int8Array)
  29589. this.type = VertexBuffer.BYTE;
  29590. else if (data_1 instanceof Uint8Array)
  29591. this.type = VertexBuffer.UNSIGNED_BYTE;
  29592. else if (data_1 instanceof Int16Array)
  29593. this.type = VertexBuffer.SHORT;
  29594. else if (data_1 instanceof Uint16Array)
  29595. this.type = VertexBuffer.UNSIGNED_SHORT;
  29596. else if (data_1 instanceof Int32Array)
  29597. this.type = VertexBuffer.INT;
  29598. else if (data_1 instanceof Uint32Array)
  29599. this.type = VertexBuffer.UNSIGNED_INT;
  29600. }
  29601. else {
  29602. this.type = type;
  29603. }
  29604. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29605. if (useBytes) {
  29606. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29607. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29608. this.byteOffset = offset || 0;
  29609. }
  29610. else {
  29611. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29612. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29613. this.byteOffset = (offset || 0) * typeByteLength;
  29614. }
  29615. this.normalized = normalized;
  29616. this._instanced = instanced !== undefined ? instanced : false;
  29617. this._instanceDivisor = instanced ? 1 : 0;
  29618. }
  29619. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29620. /**
  29621. * Gets or sets the instance divisor when in instanced mode
  29622. */
  29623. get: function () {
  29624. return this._instanceDivisor;
  29625. },
  29626. set: function (value) {
  29627. this._instanceDivisor = value;
  29628. if (value == 0) {
  29629. this._instanced = false;
  29630. }
  29631. else {
  29632. this._instanced = true;
  29633. }
  29634. },
  29635. enumerable: true,
  29636. configurable: true
  29637. });
  29638. VertexBuffer.prototype._rebuild = function () {
  29639. if (!this._buffer) {
  29640. return;
  29641. }
  29642. this._buffer._rebuild();
  29643. };
  29644. /**
  29645. * Returns the kind of the VertexBuffer (string).
  29646. */
  29647. VertexBuffer.prototype.getKind = function () {
  29648. return this._kind;
  29649. };
  29650. // Properties
  29651. /**
  29652. * Boolean : is the VertexBuffer updatable ?
  29653. */
  29654. VertexBuffer.prototype.isUpdatable = function () {
  29655. return this._buffer.isUpdatable();
  29656. };
  29657. /**
  29658. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29659. */
  29660. VertexBuffer.prototype.getData = function () {
  29661. return this._buffer.getData();
  29662. };
  29663. /**
  29664. * Returns the WebGLBuffer associated to the VertexBuffer.
  29665. */
  29666. VertexBuffer.prototype.getBuffer = function () {
  29667. return this._buffer.getBuffer();
  29668. };
  29669. /**
  29670. * Returns the stride as a multiple of the type byte length.
  29671. * DEPRECATED. Use byteStride instead.
  29672. */
  29673. VertexBuffer.prototype.getStrideSize = function () {
  29674. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29675. };
  29676. /**
  29677. * Returns the offset as a multiple of the type byte length.
  29678. * DEPRECATED. Use byteOffset instead.
  29679. */
  29680. VertexBuffer.prototype.getOffset = function () {
  29681. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29682. };
  29683. /**
  29684. * Returns the number of components per vertex attribute (integer).
  29685. */
  29686. VertexBuffer.prototype.getSize = function () {
  29687. return this._size;
  29688. };
  29689. /**
  29690. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29691. */
  29692. VertexBuffer.prototype.getIsInstanced = function () {
  29693. return this._instanced;
  29694. };
  29695. /**
  29696. * Returns the instancing divisor, zero for non-instanced (integer).
  29697. */
  29698. VertexBuffer.prototype.getInstanceDivisor = function () {
  29699. return this._instanceDivisor;
  29700. };
  29701. // Methods
  29702. /**
  29703. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29704. * Returns the created WebGLBuffer.
  29705. */
  29706. VertexBuffer.prototype.create = function (data) {
  29707. return this._buffer.create(data);
  29708. };
  29709. /**
  29710. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29711. * This function will create a new buffer if the current one is not updatable
  29712. * Returns the updated WebGLBuffer.
  29713. */
  29714. VertexBuffer.prototype.update = function (data) {
  29715. return this._buffer.update(data);
  29716. };
  29717. /**
  29718. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29719. * Returns the directly updated WebGLBuffer.
  29720. * @param data the new data
  29721. * @param offset the new offset
  29722. * @param useBytes set to true if the offset is in bytes
  29723. */
  29724. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29725. if (useBytes === void 0) { useBytes = false; }
  29726. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29727. };
  29728. /**
  29729. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29730. */
  29731. VertexBuffer.prototype.dispose = function () {
  29732. if (this._ownsBuffer) {
  29733. this._buffer.dispose();
  29734. }
  29735. };
  29736. /**
  29737. * Enumerates each value of this vertex buffer as numbers.
  29738. * @param count the number of values to enumerate
  29739. * @param callback the callback function called for each value
  29740. */
  29741. VertexBuffer.prototype.forEach = function (count, callback) {
  29742. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29743. };
  29744. Object.defineProperty(VertexBuffer, "PositionKind", {
  29745. get: function () {
  29746. return VertexBuffer._PositionKind;
  29747. },
  29748. enumerable: true,
  29749. configurable: true
  29750. });
  29751. Object.defineProperty(VertexBuffer, "NormalKind", {
  29752. get: function () {
  29753. return VertexBuffer._NormalKind;
  29754. },
  29755. enumerable: true,
  29756. configurable: true
  29757. });
  29758. Object.defineProperty(VertexBuffer, "TangentKind", {
  29759. get: function () {
  29760. return VertexBuffer._TangentKind;
  29761. },
  29762. enumerable: true,
  29763. configurable: true
  29764. });
  29765. Object.defineProperty(VertexBuffer, "UVKind", {
  29766. get: function () {
  29767. return VertexBuffer._UVKind;
  29768. },
  29769. enumerable: true,
  29770. configurable: true
  29771. });
  29772. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29773. get: function () {
  29774. return VertexBuffer._UV2Kind;
  29775. },
  29776. enumerable: true,
  29777. configurable: true
  29778. });
  29779. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29780. get: function () {
  29781. return VertexBuffer._UV3Kind;
  29782. },
  29783. enumerable: true,
  29784. configurable: true
  29785. });
  29786. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29787. get: function () {
  29788. return VertexBuffer._UV4Kind;
  29789. },
  29790. enumerable: true,
  29791. configurable: true
  29792. });
  29793. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29794. get: function () {
  29795. return VertexBuffer._UV5Kind;
  29796. },
  29797. enumerable: true,
  29798. configurable: true
  29799. });
  29800. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29801. get: function () {
  29802. return VertexBuffer._UV6Kind;
  29803. },
  29804. enumerable: true,
  29805. configurable: true
  29806. });
  29807. Object.defineProperty(VertexBuffer, "ColorKind", {
  29808. get: function () {
  29809. return VertexBuffer._ColorKind;
  29810. },
  29811. enumerable: true,
  29812. configurable: true
  29813. });
  29814. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29815. get: function () {
  29816. return VertexBuffer._MatricesIndicesKind;
  29817. },
  29818. enumerable: true,
  29819. configurable: true
  29820. });
  29821. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29822. get: function () {
  29823. return VertexBuffer._MatricesWeightsKind;
  29824. },
  29825. enumerable: true,
  29826. configurable: true
  29827. });
  29828. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29829. get: function () {
  29830. return VertexBuffer._MatricesIndicesExtraKind;
  29831. },
  29832. enumerable: true,
  29833. configurable: true
  29834. });
  29835. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29836. get: function () {
  29837. return VertexBuffer._MatricesWeightsExtraKind;
  29838. },
  29839. enumerable: true,
  29840. configurable: true
  29841. });
  29842. /**
  29843. * Deduces the stride given a kind.
  29844. * @param kind The kind string to deduce
  29845. * @returns The deduced stride
  29846. */
  29847. VertexBuffer.DeduceStride = function (kind) {
  29848. switch (kind) {
  29849. case VertexBuffer.UVKind:
  29850. case VertexBuffer.UV2Kind:
  29851. case VertexBuffer.UV3Kind:
  29852. case VertexBuffer.UV4Kind:
  29853. case VertexBuffer.UV5Kind:
  29854. case VertexBuffer.UV6Kind:
  29855. return 2;
  29856. case VertexBuffer.NormalKind:
  29857. case VertexBuffer.PositionKind:
  29858. return 3;
  29859. case VertexBuffer.ColorKind:
  29860. case VertexBuffer.MatricesIndicesKind:
  29861. case VertexBuffer.MatricesIndicesExtraKind:
  29862. case VertexBuffer.MatricesWeightsKind:
  29863. case VertexBuffer.MatricesWeightsExtraKind:
  29864. case VertexBuffer.TangentKind:
  29865. return 4;
  29866. default:
  29867. throw new Error("Invalid kind '" + kind + "'");
  29868. }
  29869. };
  29870. /**
  29871. * Gets the byte length of the given type.
  29872. * @param type the type
  29873. * @returns the number of bytes
  29874. */
  29875. VertexBuffer.GetTypeByteLength = function (type) {
  29876. switch (type) {
  29877. case VertexBuffer.BYTE:
  29878. case VertexBuffer.UNSIGNED_BYTE:
  29879. return 1;
  29880. case VertexBuffer.SHORT:
  29881. case VertexBuffer.UNSIGNED_SHORT:
  29882. return 2;
  29883. case VertexBuffer.INT:
  29884. case VertexBuffer.FLOAT:
  29885. return 4;
  29886. default:
  29887. throw new Error("Invalid type '" + type + "'");
  29888. }
  29889. };
  29890. /**
  29891. * Enumerates each value of the given parameters as numbers.
  29892. * @param data the data to enumerate
  29893. * @param byteOffset the byte offset of the data
  29894. * @param byteStride the byte stride of the data
  29895. * @param componentCount the number of components per element
  29896. * @param componentType the type of the component
  29897. * @param count the total number of components
  29898. * @param normalized whether the data is normalized
  29899. * @param callback the callback function called for each value
  29900. */
  29901. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29902. if (data instanceof Array) {
  29903. var offset = byteOffset / 4;
  29904. var stride = byteStride / 4;
  29905. for (var index = 0; index < count; index += componentCount) {
  29906. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29907. callback(data[offset + componentIndex], index + componentIndex);
  29908. }
  29909. offset += stride;
  29910. }
  29911. }
  29912. else {
  29913. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29914. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29915. for (var index = 0; index < count; index += componentCount) {
  29916. var componentByteOffset = byteOffset;
  29917. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29918. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29919. callback(value, index + componentIndex);
  29920. componentByteOffset += componentByteLength;
  29921. }
  29922. byteOffset += byteStride;
  29923. }
  29924. }
  29925. };
  29926. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29927. switch (type) {
  29928. case VertexBuffer.BYTE: {
  29929. var value = dataView.getInt8(byteOffset);
  29930. if (normalized) {
  29931. value = Math.max(value / 127, -1);
  29932. }
  29933. return value;
  29934. }
  29935. case VertexBuffer.UNSIGNED_BYTE: {
  29936. var value = dataView.getUint8(byteOffset);
  29937. if (normalized) {
  29938. value = value / 255;
  29939. }
  29940. return value;
  29941. }
  29942. case VertexBuffer.SHORT: {
  29943. var value = dataView.getInt16(byteOffset, true);
  29944. if (normalized) {
  29945. value = Math.max(value / 16383, -1);
  29946. }
  29947. return value;
  29948. }
  29949. case VertexBuffer.UNSIGNED_SHORT: {
  29950. var value = dataView.getUint16(byteOffset, true);
  29951. if (normalized) {
  29952. value = value / 65535;
  29953. }
  29954. return value;
  29955. }
  29956. case VertexBuffer.FLOAT: {
  29957. return dataView.getFloat32(byteOffset, true);
  29958. }
  29959. default: {
  29960. throw new Error("Invalid component type " + type);
  29961. }
  29962. }
  29963. };
  29964. /**
  29965. * The byte type.
  29966. */
  29967. VertexBuffer.BYTE = 5120;
  29968. /**
  29969. * The unsigned byte type.
  29970. */
  29971. VertexBuffer.UNSIGNED_BYTE = 5121;
  29972. /**
  29973. * The short type.
  29974. */
  29975. VertexBuffer.SHORT = 5122;
  29976. /**
  29977. * The unsigned short type.
  29978. */
  29979. VertexBuffer.UNSIGNED_SHORT = 5123;
  29980. /**
  29981. * The integer type.
  29982. */
  29983. VertexBuffer.INT = 5124;
  29984. /**
  29985. * The unsigned integer type.
  29986. */
  29987. VertexBuffer.UNSIGNED_INT = 5125;
  29988. /**
  29989. * The float type.
  29990. */
  29991. VertexBuffer.FLOAT = 5126;
  29992. // Enums
  29993. VertexBuffer._PositionKind = "position";
  29994. VertexBuffer._NormalKind = "normal";
  29995. VertexBuffer._TangentKind = "tangent";
  29996. VertexBuffer._UVKind = "uv";
  29997. VertexBuffer._UV2Kind = "uv2";
  29998. VertexBuffer._UV3Kind = "uv3";
  29999. VertexBuffer._UV4Kind = "uv4";
  30000. VertexBuffer._UV5Kind = "uv5";
  30001. VertexBuffer._UV6Kind = "uv6";
  30002. VertexBuffer._ColorKind = "color";
  30003. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  30004. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  30005. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  30006. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  30007. return VertexBuffer;
  30008. }());
  30009. BABYLON.VertexBuffer = VertexBuffer;
  30010. })(BABYLON || (BABYLON = {}));
  30011. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30012. var BABYLON;
  30013. (function (BABYLON) {
  30014. /**
  30015. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30016. */
  30017. var DummyInternalTextureTracker = /** @class */ (function () {
  30018. function DummyInternalTextureTracker() {
  30019. /**
  30020. * Gets or set the previous tracker in the list
  30021. */
  30022. this.previous = null;
  30023. /**
  30024. * Gets or set the next tracker in the list
  30025. */
  30026. this.next = null;
  30027. }
  30028. return DummyInternalTextureTracker;
  30029. }());
  30030. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30031. })(BABYLON || (BABYLON = {}));
  30032. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30033. var BABYLON;
  30034. (function (BABYLON) {
  30035. /**
  30036. * Class used to store data associated with WebGL texture data for the engine
  30037. * This class should not be used directly
  30038. */
  30039. var InternalTexture = /** @class */ (function () {
  30040. /**
  30041. * Creates a new InternalTexture
  30042. * @param engine defines the engine to use
  30043. * @param dataSource defines the type of data that will be used
  30044. */
  30045. function InternalTexture(engine, dataSource) {
  30046. /**
  30047. * Observable called when the texture is loaded
  30048. */
  30049. this.onLoadedObservable = new BABYLON.Observable();
  30050. /**
  30051. * Gets or set the previous tracker in the list
  30052. */
  30053. this.previous = null;
  30054. /**
  30055. * Gets or set the next tracker in the list
  30056. */
  30057. this.next = null;
  30058. // Private
  30059. /** @hidden */
  30060. this._initialSlot = -1;
  30061. /** @hidden */
  30062. this._designatedSlot = -1;
  30063. /** @hidden */
  30064. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30065. /** @hidden */
  30066. this._comparisonFunction = 0;
  30067. /** @hidden */
  30068. this._references = 1;
  30069. this._engine = engine;
  30070. this._dataSource = dataSource;
  30071. this._webGLTexture = engine._createTexture();
  30072. }
  30073. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30074. /**
  30075. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30076. */
  30077. get: function () {
  30078. return this._dataSource;
  30079. },
  30080. enumerable: true,
  30081. configurable: true
  30082. });
  30083. /**
  30084. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30085. */
  30086. InternalTexture.prototype.incrementReferences = function () {
  30087. this._references++;
  30088. };
  30089. /**
  30090. * Change the size of the texture (not the size of the content)
  30091. * @param width defines the new width
  30092. * @param height defines the new height
  30093. * @param depth defines the new depth (1 by default)
  30094. */
  30095. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30096. if (depth === void 0) { depth = 1; }
  30097. this.width = width;
  30098. this.height = height;
  30099. this.depth = depth;
  30100. this.baseWidth = width;
  30101. this.baseHeight = height;
  30102. this.baseDepth = depth;
  30103. this._size = width * height * depth;
  30104. };
  30105. /** @hidden */
  30106. InternalTexture.prototype._rebuild = function () {
  30107. var _this = this;
  30108. var proxy;
  30109. this.isReady = false;
  30110. this._cachedCoordinatesMode = null;
  30111. this._cachedWrapU = null;
  30112. this._cachedWrapV = null;
  30113. this._cachedAnisotropicFilteringLevel = null;
  30114. switch (this._dataSource) {
  30115. case InternalTexture.DATASOURCE_TEMP:
  30116. return;
  30117. case InternalTexture.DATASOURCE_URL:
  30118. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30119. _this.isReady = true;
  30120. }, null, this._buffer, undefined, this.format);
  30121. proxy._swapAndDie(this);
  30122. return;
  30123. case InternalTexture.DATASOURCE_RAW:
  30124. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30125. proxy._swapAndDie(this);
  30126. this.isReady = true;
  30127. return;
  30128. case InternalTexture.DATASOURCE_RAW3D:
  30129. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30130. proxy._swapAndDie(this);
  30131. this.isReady = true;
  30132. return;
  30133. case InternalTexture.DATASOURCE_DYNAMIC:
  30134. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30135. proxy._swapAndDie(this);
  30136. // The engine will make sure to update content so no need to flag it as isReady = true
  30137. return;
  30138. case InternalTexture.DATASOURCE_RENDERTARGET:
  30139. var options = new BABYLON.RenderTargetCreationOptions();
  30140. options.generateDepthBuffer = this._generateDepthBuffer;
  30141. options.generateMipMaps = this.generateMipMaps;
  30142. options.generateStencilBuffer = this._generateStencilBuffer;
  30143. options.samplingMode = this.samplingMode;
  30144. options.type = this.type;
  30145. if (this.isCube) {
  30146. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30147. }
  30148. else {
  30149. var size = {
  30150. width: this.width,
  30151. height: this.height
  30152. };
  30153. proxy = this._engine.createRenderTargetTexture(size, options);
  30154. }
  30155. proxy._swapAndDie(this);
  30156. this.isReady = true;
  30157. return;
  30158. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30159. var depthTextureOptions = {
  30160. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30161. comparisonFunction: this._comparisonFunction,
  30162. generateStencil: this._generateStencilBuffer,
  30163. isCube: this.isCube
  30164. };
  30165. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30166. proxy._swapAndDie(this);
  30167. this.isReady = true;
  30168. return;
  30169. case InternalTexture.DATASOURCE_CUBE:
  30170. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30171. _this.isReady = true;
  30172. }, null, this.format, this._extension);
  30173. proxy._swapAndDie(this);
  30174. return;
  30175. case InternalTexture.DATASOURCE_CUBERAW:
  30176. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30177. proxy._swapAndDie(this);
  30178. this.isReady = true;
  30179. return;
  30180. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30181. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30182. if (proxy) {
  30183. proxy._swapAndDie(_this);
  30184. }
  30185. _this.isReady = true;
  30186. }, null, this.format, this._extension);
  30187. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30188. return;
  30189. }
  30190. };
  30191. InternalTexture.prototype._swapAndDie = function (target) {
  30192. target._webGLTexture = this._webGLTexture;
  30193. if (this._framebuffer) {
  30194. target._framebuffer = this._framebuffer;
  30195. }
  30196. if (this._depthStencilBuffer) {
  30197. target._depthStencilBuffer = this._depthStencilBuffer;
  30198. }
  30199. if (this._lodTextureHigh) {
  30200. if (target._lodTextureHigh) {
  30201. target._lodTextureHigh.dispose();
  30202. }
  30203. target._lodTextureHigh = this._lodTextureHigh;
  30204. }
  30205. if (this._lodTextureMid) {
  30206. if (target._lodTextureMid) {
  30207. target._lodTextureMid.dispose();
  30208. }
  30209. target._lodTextureMid = this._lodTextureMid;
  30210. }
  30211. if (this._lodTextureLow) {
  30212. if (target._lodTextureLow) {
  30213. target._lodTextureLow.dispose();
  30214. }
  30215. target._lodTextureLow = this._lodTextureLow;
  30216. }
  30217. var cache = this._engine.getLoadedTexturesCache();
  30218. var index = cache.indexOf(this);
  30219. if (index !== -1) {
  30220. cache.splice(index, 1);
  30221. }
  30222. };
  30223. /**
  30224. * Dispose the current allocated resources
  30225. */
  30226. InternalTexture.prototype.dispose = function () {
  30227. if (!this._webGLTexture) {
  30228. return;
  30229. }
  30230. this._references--;
  30231. if (this._references === 0) {
  30232. this._engine._releaseTexture(this);
  30233. this._webGLTexture = null;
  30234. this.previous = null;
  30235. this.next = null;
  30236. }
  30237. };
  30238. /**
  30239. * The source of the texture data is unknown
  30240. */
  30241. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30242. /**
  30243. * Texture data comes from an URL
  30244. */
  30245. InternalTexture.DATASOURCE_URL = 1;
  30246. /**
  30247. * Texture data is only used for temporary storage
  30248. */
  30249. InternalTexture.DATASOURCE_TEMP = 2;
  30250. /**
  30251. * Texture data comes from raw data (ArrayBuffer)
  30252. */
  30253. InternalTexture.DATASOURCE_RAW = 3;
  30254. /**
  30255. * Texture content is dynamic (video or dynamic texture)
  30256. */
  30257. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30258. /**
  30259. * Texture content is generated by rendering to it
  30260. */
  30261. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30262. /**
  30263. * Texture content is part of a multi render target process
  30264. */
  30265. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30266. /**
  30267. * Texture data comes from a cube data file
  30268. */
  30269. InternalTexture.DATASOURCE_CUBE = 7;
  30270. /**
  30271. * Texture data comes from a raw cube data
  30272. */
  30273. InternalTexture.DATASOURCE_CUBERAW = 8;
  30274. /**
  30275. * Texture data come from a prefiltered cube data file
  30276. */
  30277. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30278. /**
  30279. * Texture content is raw 3D data
  30280. */
  30281. InternalTexture.DATASOURCE_RAW3D = 10;
  30282. /**
  30283. * Texture content is a depth texture
  30284. */
  30285. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30286. return InternalTexture;
  30287. }());
  30288. BABYLON.InternalTexture = InternalTexture;
  30289. })(BABYLON || (BABYLON = {}));
  30290. //# sourceMappingURL=babylon.internalTexture.js.map
  30291. var BABYLON;
  30292. (function (BABYLON) {
  30293. var BaseTexture = /** @class */ (function () {
  30294. function BaseTexture(scene) {
  30295. this._hasAlpha = false;
  30296. this.getAlphaFromRGB = false;
  30297. this.level = 1;
  30298. this.coordinatesIndex = 0;
  30299. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30300. /**
  30301. * | Value | Type | Description |
  30302. * | ----- | ------------------ | ----------- |
  30303. * | 0 | CLAMP_ADDRESSMODE | |
  30304. * | 1 | WRAP_ADDRESSMODE | |
  30305. * | 2 | MIRROR_ADDRESSMODE | |
  30306. */
  30307. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30308. /**
  30309. * | Value | Type | Description |
  30310. * | ----- | ------------------ | ----------- |
  30311. * | 0 | CLAMP_ADDRESSMODE | |
  30312. * | 1 | WRAP_ADDRESSMODE | |
  30313. * | 2 | MIRROR_ADDRESSMODE | |
  30314. */
  30315. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30316. /**
  30317. * | Value | Type | Description |
  30318. * | ----- | ------------------ | ----------- |
  30319. * | 0 | CLAMP_ADDRESSMODE | |
  30320. * | 1 | WRAP_ADDRESSMODE | |
  30321. * | 2 | MIRROR_ADDRESSMODE | |
  30322. */
  30323. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30324. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30325. this.isCube = false;
  30326. this.is3D = false;
  30327. this.gammaSpace = true;
  30328. this.invertZ = false;
  30329. this.lodLevelInAlpha = false;
  30330. this.lodGenerationOffset = 0.0;
  30331. this.lodGenerationScale = 0.8;
  30332. this.isRenderTarget = false;
  30333. this.animations = new Array();
  30334. /**
  30335. * An event triggered when the texture is disposed.
  30336. */
  30337. this.onDisposeObservable = new BABYLON.Observable();
  30338. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30339. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30340. if (this._scene) {
  30341. this._scene.textures.push(this);
  30342. }
  30343. this._uid = null;
  30344. }
  30345. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30346. get: function () {
  30347. return this._hasAlpha;
  30348. },
  30349. set: function (value) {
  30350. if (this._hasAlpha === value) {
  30351. return;
  30352. }
  30353. this._hasAlpha = value;
  30354. if (this._scene) {
  30355. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30356. }
  30357. },
  30358. enumerable: true,
  30359. configurable: true
  30360. });
  30361. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30362. get: function () {
  30363. return this._coordinatesMode;
  30364. },
  30365. /**
  30366. * How a texture is mapped.
  30367. *
  30368. * | Value | Type | Description |
  30369. * | ----- | ----------------------------------- | ----------- |
  30370. * | 0 | EXPLICIT_MODE | |
  30371. * | 1 | SPHERICAL_MODE | |
  30372. * | 2 | PLANAR_MODE | |
  30373. * | 3 | CUBIC_MODE | |
  30374. * | 4 | PROJECTION_MODE | |
  30375. * | 5 | SKYBOX_MODE | |
  30376. * | 6 | INVCUBIC_MODE | |
  30377. * | 7 | EQUIRECTANGULAR_MODE | |
  30378. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30379. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30380. */
  30381. set: function (value) {
  30382. if (this._coordinatesMode === value) {
  30383. return;
  30384. }
  30385. this._coordinatesMode = value;
  30386. if (this._scene) {
  30387. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30388. }
  30389. },
  30390. enumerable: true,
  30391. configurable: true
  30392. });
  30393. Object.defineProperty(BaseTexture.prototype, "uid", {
  30394. get: function () {
  30395. if (!this._uid) {
  30396. this._uid = BABYLON.Tools.RandomId();
  30397. }
  30398. return this._uid;
  30399. },
  30400. enumerable: true,
  30401. configurable: true
  30402. });
  30403. BaseTexture.prototype.toString = function () {
  30404. return this.name;
  30405. };
  30406. BaseTexture.prototype.getClassName = function () {
  30407. return "BaseTexture";
  30408. };
  30409. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30410. set: function (callback) {
  30411. if (this._onDisposeObserver) {
  30412. this.onDisposeObservable.remove(this._onDisposeObserver);
  30413. }
  30414. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30415. },
  30416. enumerable: true,
  30417. configurable: true
  30418. });
  30419. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30420. get: function () {
  30421. return true;
  30422. },
  30423. enumerable: true,
  30424. configurable: true
  30425. });
  30426. BaseTexture.prototype.getScene = function () {
  30427. return this._scene;
  30428. };
  30429. BaseTexture.prototype.getTextureMatrix = function () {
  30430. return BABYLON.Matrix.IdentityReadOnly;
  30431. };
  30432. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30433. return BABYLON.Matrix.IdentityReadOnly;
  30434. };
  30435. BaseTexture.prototype.getInternalTexture = function () {
  30436. return this._texture;
  30437. };
  30438. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30439. return !this.isBlocking || this.isReady();
  30440. };
  30441. BaseTexture.prototype.isReady = function () {
  30442. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30443. this.delayLoad();
  30444. return false;
  30445. }
  30446. if (this._texture) {
  30447. return this._texture.isReady;
  30448. }
  30449. return false;
  30450. };
  30451. BaseTexture.prototype.getSize = function () {
  30452. if (this._texture && this._texture.width) {
  30453. return new BABYLON.Size(this._texture.width, this._texture.height);
  30454. }
  30455. if (this._texture && this._texture._size) {
  30456. return new BABYLON.Size(this._texture._size, this._texture._size);
  30457. }
  30458. return BABYLON.Size.Zero();
  30459. };
  30460. BaseTexture.prototype.getBaseSize = function () {
  30461. if (!this.isReady() || !this._texture)
  30462. return BABYLON.Size.Zero();
  30463. if (this._texture._size) {
  30464. return new BABYLON.Size(this._texture._size, this._texture._size);
  30465. }
  30466. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30467. };
  30468. BaseTexture.prototype.scale = function (ratio) {
  30469. };
  30470. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30471. get: function () {
  30472. return false;
  30473. },
  30474. enumerable: true,
  30475. configurable: true
  30476. });
  30477. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30478. if (!this._scene) {
  30479. return null;
  30480. }
  30481. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30482. for (var index = 0; index < texturesCache.length; index++) {
  30483. var texturesCacheEntry = texturesCache[index];
  30484. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30485. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30486. texturesCacheEntry.incrementReferences();
  30487. return texturesCacheEntry;
  30488. }
  30489. }
  30490. }
  30491. return null;
  30492. };
  30493. BaseTexture.prototype._rebuild = function () {
  30494. };
  30495. BaseTexture.prototype.delayLoad = function () {
  30496. };
  30497. BaseTexture.prototype.clone = function () {
  30498. return null;
  30499. };
  30500. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30501. get: function () {
  30502. if (!this._texture) {
  30503. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30504. }
  30505. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30506. },
  30507. enumerable: true,
  30508. configurable: true
  30509. });
  30510. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30511. get: function () {
  30512. if (!this._texture) {
  30513. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30514. }
  30515. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30516. },
  30517. enumerable: true,
  30518. configurable: true
  30519. });
  30520. BaseTexture.prototype.readPixels = function (faceIndex) {
  30521. if (faceIndex === void 0) { faceIndex = 0; }
  30522. if (!this._texture) {
  30523. return null;
  30524. }
  30525. var size = this.getSize();
  30526. var scene = this.getScene();
  30527. if (!scene) {
  30528. return null;
  30529. }
  30530. var engine = scene.getEngine();
  30531. if (this._texture.isCube) {
  30532. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  30533. }
  30534. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  30535. };
  30536. BaseTexture.prototype.releaseInternalTexture = function () {
  30537. if (this._texture) {
  30538. this._texture.dispose();
  30539. this._texture = null;
  30540. }
  30541. };
  30542. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30543. get: function () {
  30544. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30545. return null;
  30546. }
  30547. if (!this._texture._sphericalPolynomial) {
  30548. this._texture._sphericalPolynomial =
  30549. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30550. }
  30551. return this._texture._sphericalPolynomial;
  30552. },
  30553. set: function (value) {
  30554. if (this._texture) {
  30555. this._texture._sphericalPolynomial = value;
  30556. }
  30557. },
  30558. enumerable: true,
  30559. configurable: true
  30560. });
  30561. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30562. get: function () {
  30563. if (this._texture) {
  30564. return this._texture._lodTextureHigh;
  30565. }
  30566. return null;
  30567. },
  30568. enumerable: true,
  30569. configurable: true
  30570. });
  30571. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30572. get: function () {
  30573. if (this._texture) {
  30574. return this._texture._lodTextureMid;
  30575. }
  30576. return null;
  30577. },
  30578. enumerable: true,
  30579. configurable: true
  30580. });
  30581. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30582. get: function () {
  30583. if (this._texture) {
  30584. return this._texture._lodTextureLow;
  30585. }
  30586. return null;
  30587. },
  30588. enumerable: true,
  30589. configurable: true
  30590. });
  30591. BaseTexture.prototype.dispose = function () {
  30592. if (!this._scene) {
  30593. return;
  30594. }
  30595. // Animations
  30596. this._scene.stopAnimation(this);
  30597. // Remove from scene
  30598. this._scene._removePendingData(this);
  30599. var index = this._scene.textures.indexOf(this);
  30600. if (index >= 0) {
  30601. this._scene.textures.splice(index, 1);
  30602. }
  30603. if (this._texture === undefined) {
  30604. return;
  30605. }
  30606. // Release
  30607. this.releaseInternalTexture();
  30608. // Callback
  30609. this.onDisposeObservable.notifyObservers(this);
  30610. this.onDisposeObservable.clear();
  30611. };
  30612. BaseTexture.prototype.serialize = function () {
  30613. if (!this.name) {
  30614. return null;
  30615. }
  30616. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30617. // Animations
  30618. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30619. return serializationObject;
  30620. };
  30621. BaseTexture.WhenAllReady = function (textures, callback) {
  30622. var numRemaining = textures.length;
  30623. if (numRemaining === 0) {
  30624. callback();
  30625. return;
  30626. }
  30627. var _loop_1 = function () {
  30628. texture = textures[i];
  30629. if (texture.isReady()) {
  30630. if (--numRemaining === 0) {
  30631. callback();
  30632. }
  30633. }
  30634. else {
  30635. onLoadObservable = texture.onLoadObservable;
  30636. var onLoadCallback_1 = function () {
  30637. onLoadObservable.removeCallback(onLoadCallback_1);
  30638. if (--numRemaining === 0) {
  30639. callback();
  30640. }
  30641. };
  30642. onLoadObservable.add(onLoadCallback_1);
  30643. }
  30644. };
  30645. var texture, onLoadObservable;
  30646. for (var i = 0; i < textures.length; i++) {
  30647. _loop_1();
  30648. }
  30649. };
  30650. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30651. __decorate([
  30652. BABYLON.serialize()
  30653. ], BaseTexture.prototype, "name", void 0);
  30654. __decorate([
  30655. BABYLON.serialize("hasAlpha")
  30656. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30657. __decorate([
  30658. BABYLON.serialize()
  30659. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30660. __decorate([
  30661. BABYLON.serialize()
  30662. ], BaseTexture.prototype, "level", void 0);
  30663. __decorate([
  30664. BABYLON.serialize()
  30665. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30666. __decorate([
  30667. BABYLON.serialize("coordinatesMode")
  30668. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30669. __decorate([
  30670. BABYLON.serialize()
  30671. ], BaseTexture.prototype, "wrapU", void 0);
  30672. __decorate([
  30673. BABYLON.serialize()
  30674. ], BaseTexture.prototype, "wrapV", void 0);
  30675. __decorate([
  30676. BABYLON.serialize()
  30677. ], BaseTexture.prototype, "wrapR", void 0);
  30678. __decorate([
  30679. BABYLON.serialize()
  30680. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30681. __decorate([
  30682. BABYLON.serialize()
  30683. ], BaseTexture.prototype, "isCube", void 0);
  30684. __decorate([
  30685. BABYLON.serialize()
  30686. ], BaseTexture.prototype, "is3D", void 0);
  30687. __decorate([
  30688. BABYLON.serialize()
  30689. ], BaseTexture.prototype, "gammaSpace", void 0);
  30690. __decorate([
  30691. BABYLON.serialize()
  30692. ], BaseTexture.prototype, "invertZ", void 0);
  30693. __decorate([
  30694. BABYLON.serialize()
  30695. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30696. __decorate([
  30697. BABYLON.serialize()
  30698. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30699. __decorate([
  30700. BABYLON.serialize()
  30701. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30702. __decorate([
  30703. BABYLON.serialize()
  30704. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30705. return BaseTexture;
  30706. }());
  30707. BABYLON.BaseTexture = BaseTexture;
  30708. })(BABYLON || (BABYLON = {}));
  30709. //# sourceMappingURL=babylon.baseTexture.js.map
  30710. var BABYLON;
  30711. (function (BABYLON) {
  30712. var Texture = /** @class */ (function (_super) {
  30713. __extends(Texture, _super);
  30714. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30715. if (noMipmap === void 0) { noMipmap = false; }
  30716. if (invertY === void 0) { invertY = true; }
  30717. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30718. if (onLoad === void 0) { onLoad = null; }
  30719. if (onError === void 0) { onError = null; }
  30720. if (buffer === void 0) { buffer = null; }
  30721. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30722. var _this = _super.call(this, scene) || this;
  30723. _this.uOffset = 0;
  30724. _this.vOffset = 0;
  30725. _this.uScale = 1.0;
  30726. _this.vScale = 1.0;
  30727. _this.uAng = 0;
  30728. _this.vAng = 0;
  30729. _this.wAng = 0;
  30730. /**
  30731. * Defines the center of rotation (U)
  30732. */
  30733. _this.uRotationCenter = 0.5;
  30734. /**
  30735. * Defines the center of rotation (V)
  30736. */
  30737. _this.vRotationCenter = 0.5;
  30738. /**
  30739. * Defines the center of rotation (W)
  30740. */
  30741. _this.wRotationCenter = 0.5;
  30742. _this._isBlocking = true;
  30743. _this.name = url || "";
  30744. _this.url = url;
  30745. _this._noMipmap = noMipmap;
  30746. _this._invertY = invertY;
  30747. _this._samplingMode = samplingMode;
  30748. _this._buffer = buffer;
  30749. _this._deleteBuffer = deleteBuffer;
  30750. if (format) {
  30751. _this._format = format;
  30752. }
  30753. scene = _this.getScene();
  30754. if (!scene) {
  30755. return _this;
  30756. }
  30757. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30758. var load = function () {
  30759. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30760. _this.onLoadObservable.notifyObservers(_this);
  30761. }
  30762. if (onLoad) {
  30763. onLoad();
  30764. }
  30765. if (!_this.isBlocking && scene) {
  30766. scene.resetCachedMaterial();
  30767. }
  30768. };
  30769. if (!_this.url) {
  30770. _this._delayedOnLoad = load;
  30771. _this._delayedOnError = onError;
  30772. return _this;
  30773. }
  30774. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30775. if (!_this._texture) {
  30776. if (!scene.useDelayedTextureLoading) {
  30777. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30778. if (deleteBuffer) {
  30779. delete _this._buffer;
  30780. }
  30781. }
  30782. else {
  30783. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30784. _this._delayedOnLoad = load;
  30785. _this._delayedOnError = onError;
  30786. }
  30787. }
  30788. else {
  30789. if (_this._texture.isReady) {
  30790. BABYLON.Tools.SetImmediate(function () { return load(); });
  30791. }
  30792. else {
  30793. _this._texture.onLoadedObservable.add(load);
  30794. }
  30795. }
  30796. return _this;
  30797. }
  30798. Object.defineProperty(Texture.prototype, "noMipmap", {
  30799. get: function () {
  30800. return this._noMipmap;
  30801. },
  30802. enumerable: true,
  30803. configurable: true
  30804. });
  30805. Object.defineProperty(Texture.prototype, "isBlocking", {
  30806. get: function () {
  30807. return this._isBlocking;
  30808. },
  30809. set: function (value) {
  30810. this._isBlocking = value;
  30811. },
  30812. enumerable: true,
  30813. configurable: true
  30814. });
  30815. Object.defineProperty(Texture.prototype, "samplingMode", {
  30816. get: function () {
  30817. return this._samplingMode;
  30818. },
  30819. enumerable: true,
  30820. configurable: true
  30821. });
  30822. /**
  30823. * Update the url (and optional buffer) of this texture if url was null during construction.
  30824. * @param url the url of the texture
  30825. * @param buffer the buffer of the texture (defaults to null)
  30826. */
  30827. Texture.prototype.updateURL = function (url, buffer) {
  30828. if (buffer === void 0) { buffer = null; }
  30829. if (this.url) {
  30830. throw new Error("URL is already set");
  30831. }
  30832. this.url = url;
  30833. this._buffer = buffer;
  30834. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30835. this.delayLoad();
  30836. };
  30837. Texture.prototype.delayLoad = function () {
  30838. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30839. return;
  30840. }
  30841. var scene = this.getScene();
  30842. if (!scene) {
  30843. return;
  30844. }
  30845. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30846. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30847. if (!this._texture) {
  30848. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30849. if (this._deleteBuffer) {
  30850. delete this._buffer;
  30851. }
  30852. }
  30853. else {
  30854. if (this._delayedOnLoad) {
  30855. if (this._texture.isReady) {
  30856. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30857. }
  30858. else {
  30859. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30860. }
  30861. }
  30862. }
  30863. this._delayedOnLoad = null;
  30864. this._delayedOnError = null;
  30865. };
  30866. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30867. if (!this._texture) {
  30868. return;
  30869. }
  30870. var scene = this.getScene();
  30871. if (!scene) {
  30872. return;
  30873. }
  30874. this._samplingMode = samplingMode;
  30875. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30876. };
  30877. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30878. x *= this.uScale;
  30879. y *= this.vScale;
  30880. x -= this.uRotationCenter * this.uScale;
  30881. y -= this.vRotationCenter * this.vScale;
  30882. z -= this.wRotationCenter;
  30883. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30884. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30885. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30886. t.z += this.wRotationCenter;
  30887. };
  30888. Texture.prototype.getTextureMatrix = function () {
  30889. var _this = this;
  30890. if (this.uOffset === this._cachedUOffset &&
  30891. this.vOffset === this._cachedVOffset &&
  30892. this.uScale === this._cachedUScale &&
  30893. this.vScale === this._cachedVScale &&
  30894. this.uAng === this._cachedUAng &&
  30895. this.vAng === this._cachedVAng &&
  30896. this.wAng === this._cachedWAng) {
  30897. return this._cachedTextureMatrix;
  30898. }
  30899. this._cachedUOffset = this.uOffset;
  30900. this._cachedVOffset = this.vOffset;
  30901. this._cachedUScale = this.uScale;
  30902. this._cachedVScale = this.vScale;
  30903. this._cachedUAng = this.uAng;
  30904. this._cachedVAng = this.vAng;
  30905. this._cachedWAng = this.wAng;
  30906. if (!this._cachedTextureMatrix) {
  30907. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30908. this._rowGenerationMatrix = new BABYLON.Matrix();
  30909. this._t0 = BABYLON.Vector3.Zero();
  30910. this._t1 = BABYLON.Vector3.Zero();
  30911. this._t2 = BABYLON.Vector3.Zero();
  30912. }
  30913. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30914. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30915. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30916. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30917. this._t1.subtractInPlace(this._t0);
  30918. this._t2.subtractInPlace(this._t0);
  30919. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30920. this._cachedTextureMatrix.m[0] = this._t1.x;
  30921. this._cachedTextureMatrix.m[1] = this._t1.y;
  30922. this._cachedTextureMatrix.m[2] = this._t1.z;
  30923. this._cachedTextureMatrix.m[4] = this._t2.x;
  30924. this._cachedTextureMatrix.m[5] = this._t2.y;
  30925. this._cachedTextureMatrix.m[6] = this._t2.z;
  30926. this._cachedTextureMatrix.m[8] = this._t0.x;
  30927. this._cachedTextureMatrix.m[9] = this._t0.y;
  30928. this._cachedTextureMatrix.m[10] = this._t0.z;
  30929. var scene = this.getScene();
  30930. if (!scene) {
  30931. return this._cachedTextureMatrix;
  30932. }
  30933. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30934. return mat.hasTexture(_this);
  30935. });
  30936. return this._cachedTextureMatrix;
  30937. };
  30938. Texture.prototype.getReflectionTextureMatrix = function () {
  30939. var _this = this;
  30940. var scene = this.getScene();
  30941. if (!scene) {
  30942. return this._cachedTextureMatrix;
  30943. }
  30944. if (this.uOffset === this._cachedUOffset &&
  30945. this.vOffset === this._cachedVOffset &&
  30946. this.uScale === this._cachedUScale &&
  30947. this.vScale === this._cachedVScale &&
  30948. this.coordinatesMode === this._cachedCoordinatesMode) {
  30949. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30950. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30951. return this._cachedTextureMatrix;
  30952. }
  30953. }
  30954. else {
  30955. return this._cachedTextureMatrix;
  30956. }
  30957. }
  30958. if (!this._cachedTextureMatrix) {
  30959. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30960. }
  30961. if (!this._projectionModeMatrix) {
  30962. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30963. }
  30964. this._cachedUOffset = this.uOffset;
  30965. this._cachedVOffset = this.vOffset;
  30966. this._cachedUScale = this.uScale;
  30967. this._cachedVScale = this.vScale;
  30968. this._cachedCoordinatesMode = this.coordinatesMode;
  30969. switch (this.coordinatesMode) {
  30970. case Texture.PLANAR_MODE:
  30971. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30972. this._cachedTextureMatrix[0] = this.uScale;
  30973. this._cachedTextureMatrix[5] = this.vScale;
  30974. this._cachedTextureMatrix[12] = this.uOffset;
  30975. this._cachedTextureMatrix[13] = this.vOffset;
  30976. break;
  30977. case Texture.PROJECTION_MODE:
  30978. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30979. this._projectionModeMatrix.m[0] = 0.5;
  30980. this._projectionModeMatrix.m[5] = -0.5;
  30981. this._projectionModeMatrix.m[10] = 0.0;
  30982. this._projectionModeMatrix.m[12] = 0.5;
  30983. this._projectionModeMatrix.m[13] = 0.5;
  30984. this._projectionModeMatrix.m[14] = 1.0;
  30985. this._projectionModeMatrix.m[15] = 1.0;
  30986. var projectionMatrix = scene.getProjectionMatrix();
  30987. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30988. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30989. break;
  30990. default:
  30991. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30992. break;
  30993. }
  30994. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30995. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30996. });
  30997. return this._cachedTextureMatrix;
  30998. };
  30999. Texture.prototype.clone = function () {
  31000. var _this = this;
  31001. return BABYLON.SerializationHelper.Clone(function () {
  31002. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31003. }, this);
  31004. };
  31005. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31006. get: function () {
  31007. if (!this._onLoadObservable) {
  31008. this._onLoadObservable = new BABYLON.Observable();
  31009. }
  31010. return this._onLoadObservable;
  31011. },
  31012. enumerable: true,
  31013. configurable: true
  31014. });
  31015. Texture.prototype.serialize = function () {
  31016. var serializationObject = _super.prototype.serialize.call(this);
  31017. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31018. serializationObject.base64String = this._buffer;
  31019. serializationObject.name = serializationObject.name.replace("data:", "");
  31020. }
  31021. serializationObject.invertY = this._invertY;
  31022. serializationObject.samplingMode = this.samplingMode;
  31023. return serializationObject;
  31024. };
  31025. Texture.prototype.getClassName = function () {
  31026. return "Texture";
  31027. };
  31028. Texture.prototype.dispose = function () {
  31029. _super.prototype.dispose.call(this);
  31030. if (this.onLoadObservable) {
  31031. this.onLoadObservable.clear();
  31032. this._onLoadObservable = null;
  31033. }
  31034. this._delayedOnLoad = null;
  31035. this._delayedOnError = null;
  31036. };
  31037. // Statics
  31038. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31039. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31040. if (onLoad === void 0) { onLoad = null; }
  31041. if (onError === void 0) { onError = null; }
  31042. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31043. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31044. };
  31045. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31046. if (parsedTexture.customType) {
  31047. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31048. // Update Sampling Mode
  31049. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31050. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31051. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31052. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31053. }
  31054. }
  31055. return parsedCustomTexture;
  31056. }
  31057. if (parsedTexture.isCube) {
  31058. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31059. }
  31060. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31061. return null;
  31062. }
  31063. var texture = BABYLON.SerializationHelper.Parse(function () {
  31064. var generateMipMaps = true;
  31065. if (parsedTexture.noMipmap) {
  31066. generateMipMaps = false;
  31067. }
  31068. if (parsedTexture.mirrorPlane) {
  31069. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31070. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31071. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31072. return mirrorTexture;
  31073. }
  31074. else if (parsedTexture.isRenderTarget) {
  31075. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31076. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31077. return renderTargetTexture;
  31078. }
  31079. else {
  31080. var texture;
  31081. if (parsedTexture.base64String) {
  31082. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31083. }
  31084. else {
  31085. var url = rootUrl + parsedTexture.name;
  31086. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31087. url = parsedTexture.url;
  31088. }
  31089. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31090. }
  31091. return texture;
  31092. }
  31093. }, parsedTexture, scene);
  31094. // Update Sampling Mode
  31095. if (parsedTexture.samplingMode) {
  31096. var sampling = parsedTexture.samplingMode;
  31097. if (texture._samplingMode !== sampling) {
  31098. texture.updateSamplingMode(sampling);
  31099. }
  31100. }
  31101. // Animations
  31102. if (parsedTexture.animations) {
  31103. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31104. var parsedAnimation = parsedTexture.animations[animationIndex];
  31105. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31106. }
  31107. }
  31108. return texture;
  31109. };
  31110. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31111. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31112. if (noMipmap === void 0) { noMipmap = false; }
  31113. if (invertY === void 0) { invertY = true; }
  31114. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31115. if (onLoad === void 0) { onLoad = null; }
  31116. if (onError === void 0) { onError = null; }
  31117. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31118. if (name.substr(0, 5) !== "data:") {
  31119. name = "data:" + name;
  31120. }
  31121. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31122. };
  31123. // Constants
  31124. Texture.NEAREST_SAMPLINGMODE = 1;
  31125. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31126. Texture.BILINEAR_SAMPLINGMODE = 2;
  31127. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31128. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31129. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31130. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31131. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31132. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31133. Texture.NEAREST_LINEAR = 7;
  31134. Texture.NEAREST_NEAREST = 8;
  31135. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31136. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31137. Texture.LINEAR_LINEAR = 11;
  31138. Texture.LINEAR_NEAREST = 12;
  31139. Texture.EXPLICIT_MODE = 0;
  31140. Texture.SPHERICAL_MODE = 1;
  31141. Texture.PLANAR_MODE = 2;
  31142. Texture.CUBIC_MODE = 3;
  31143. Texture.PROJECTION_MODE = 4;
  31144. Texture.SKYBOX_MODE = 5;
  31145. Texture.INVCUBIC_MODE = 6;
  31146. Texture.EQUIRECTANGULAR_MODE = 7;
  31147. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31148. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31149. Texture.CLAMP_ADDRESSMODE = 0;
  31150. Texture.WRAP_ADDRESSMODE = 1;
  31151. Texture.MIRROR_ADDRESSMODE = 2;
  31152. /**
  31153. * Gets or sets a boolean which defines if the texture url must be build from the serialized URL instead of just using the name and loading them side by side with the scene file
  31154. */
  31155. Texture.UseSerializedUrlIfAny = false;
  31156. __decorate([
  31157. BABYLON.serialize()
  31158. ], Texture.prototype, "url", void 0);
  31159. __decorate([
  31160. BABYLON.serialize()
  31161. ], Texture.prototype, "uOffset", void 0);
  31162. __decorate([
  31163. BABYLON.serialize()
  31164. ], Texture.prototype, "vOffset", void 0);
  31165. __decorate([
  31166. BABYLON.serialize()
  31167. ], Texture.prototype, "uScale", void 0);
  31168. __decorate([
  31169. BABYLON.serialize()
  31170. ], Texture.prototype, "vScale", void 0);
  31171. __decorate([
  31172. BABYLON.serialize()
  31173. ], Texture.prototype, "uAng", void 0);
  31174. __decorate([
  31175. BABYLON.serialize()
  31176. ], Texture.prototype, "vAng", void 0);
  31177. __decorate([
  31178. BABYLON.serialize()
  31179. ], Texture.prototype, "wAng", void 0);
  31180. __decorate([
  31181. BABYLON.serialize()
  31182. ], Texture.prototype, "uRotationCenter", void 0);
  31183. __decorate([
  31184. BABYLON.serialize()
  31185. ], Texture.prototype, "vRotationCenter", void 0);
  31186. __decorate([
  31187. BABYLON.serialize()
  31188. ], Texture.prototype, "wRotationCenter", void 0);
  31189. __decorate([
  31190. BABYLON.serialize()
  31191. ], Texture.prototype, "isBlocking", null);
  31192. return Texture;
  31193. }(BABYLON.BaseTexture));
  31194. BABYLON.Texture = Texture;
  31195. })(BABYLON || (BABYLON = {}));
  31196. //# sourceMappingURL=babylon.texture.js.map
  31197. var BABYLON;
  31198. (function (BABYLON) {
  31199. /**
  31200. * @hidden
  31201. **/
  31202. var _InstancesBatch = /** @class */ (function () {
  31203. function _InstancesBatch() {
  31204. this.mustReturn = false;
  31205. this.visibleInstances = new Array();
  31206. this.renderSelf = new Array();
  31207. }
  31208. return _InstancesBatch;
  31209. }());
  31210. BABYLON._InstancesBatch = _InstancesBatch;
  31211. var Mesh = /** @class */ (function (_super) {
  31212. __extends(Mesh, _super);
  31213. /**
  31214. * @constructor
  31215. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31216. * @param {Scene} scene The scene to add this mesh to.
  31217. * @param {Node} parent The parent of this mesh, if it has one
  31218. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31219. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31220. * When false, achieved by calling a clone(), also passing False.
  31221. * This will make creation of children, recursive.
  31222. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31223. */
  31224. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31225. if (scene === void 0) { scene = null; }
  31226. if (parent === void 0) { parent = null; }
  31227. if (source === void 0) { source = null; }
  31228. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31229. var _this = _super.call(this, name, scene) || this;
  31230. // Events
  31231. /**
  31232. * An event triggered before rendering the mesh
  31233. */
  31234. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31235. /**
  31236. * An event triggered after rendering the mesh
  31237. */
  31238. _this.onAfterRenderObservable = new BABYLON.Observable();
  31239. /**
  31240. * An event triggered before drawing the mesh
  31241. */
  31242. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31243. // Members
  31244. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31245. _this.instances = new Array();
  31246. _this._LODLevels = new Array();
  31247. _this._visibleInstances = {};
  31248. _this._renderIdForInstances = new Array();
  31249. _this._batchCache = new _InstancesBatch();
  31250. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31251. // Use by builder only to know what orientation were the mesh build in.
  31252. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31253. _this.overrideMaterialSideOrientation = null;
  31254. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31255. // Will be used to save a source mesh reference, If any
  31256. _this._source = null;
  31257. scene = _this.getScene();
  31258. if (source) {
  31259. // Geometry
  31260. if (source._geometry) {
  31261. source._geometry.applyToMesh(_this);
  31262. }
  31263. // Deep copy
  31264. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31265. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31266. // Source mesh
  31267. _this._source = source;
  31268. // Metadata
  31269. if (source.metadata && source.metadata.clone) {
  31270. _this.metadata = source.metadata.clone();
  31271. }
  31272. else {
  31273. _this.metadata = source.metadata;
  31274. }
  31275. // Tags
  31276. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31277. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31278. }
  31279. // Parent
  31280. _this.parent = source.parent;
  31281. // Pivot
  31282. _this.setPivotMatrix(source.getPivotMatrix());
  31283. _this.id = name + "." + source.id;
  31284. // Material
  31285. _this.material = source.material;
  31286. var index;
  31287. if (!doNotCloneChildren) {
  31288. // Children
  31289. var directDescendants = source.getDescendants(true);
  31290. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31291. var child = directDescendants[index_1];
  31292. if (child.clone) {
  31293. child.clone(name + "." + child.name, _this);
  31294. }
  31295. }
  31296. }
  31297. // Physics clone
  31298. var physicsEngine = _this.getScene().getPhysicsEngine();
  31299. if (clonePhysicsImpostor && physicsEngine) {
  31300. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31301. if (impostor) {
  31302. _this.physicsImpostor = impostor.clone(_this);
  31303. }
  31304. }
  31305. // Particles
  31306. for (index = 0; index < scene.particleSystems.length; index++) {
  31307. var system = scene.particleSystems[index];
  31308. if (system.emitter === source) {
  31309. system.clone(system.name, _this);
  31310. }
  31311. }
  31312. _this.computeWorldMatrix(true);
  31313. }
  31314. // Parent
  31315. if (parent !== null) {
  31316. _this.parent = parent;
  31317. }
  31318. return _this;
  31319. }
  31320. Object.defineProperty(Mesh, "FRONTSIDE", {
  31321. /**
  31322. * Mesh side orientation : usually the external or front surface
  31323. */
  31324. get: function () {
  31325. return Mesh._FRONTSIDE;
  31326. },
  31327. enumerable: true,
  31328. configurable: true
  31329. });
  31330. Object.defineProperty(Mesh, "BACKSIDE", {
  31331. /**
  31332. * Mesh side orientation : usually the internal or back surface
  31333. */
  31334. get: function () {
  31335. return Mesh._BACKSIDE;
  31336. },
  31337. enumerable: true,
  31338. configurable: true
  31339. });
  31340. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31341. /**
  31342. * Mesh side orientation : both internal and external or front and back surfaces
  31343. */
  31344. get: function () {
  31345. return Mesh._DOUBLESIDE;
  31346. },
  31347. enumerable: true,
  31348. configurable: true
  31349. });
  31350. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31351. /**
  31352. * Mesh side orientation : by default, `FRONTSIDE`
  31353. */
  31354. get: function () {
  31355. return Mesh._DEFAULTSIDE;
  31356. },
  31357. enumerable: true,
  31358. configurable: true
  31359. });
  31360. Object.defineProperty(Mesh, "NO_CAP", {
  31361. /**
  31362. * Mesh cap setting : no cap
  31363. */
  31364. get: function () {
  31365. return Mesh._NO_CAP;
  31366. },
  31367. enumerable: true,
  31368. configurable: true
  31369. });
  31370. Object.defineProperty(Mesh, "CAP_START", {
  31371. /**
  31372. * Mesh cap setting : one cap at the beginning of the mesh
  31373. */
  31374. get: function () {
  31375. return Mesh._CAP_START;
  31376. },
  31377. enumerable: true,
  31378. configurable: true
  31379. });
  31380. Object.defineProperty(Mesh, "CAP_END", {
  31381. /**
  31382. * Mesh cap setting : one cap at the end of the mesh
  31383. */
  31384. get: function () {
  31385. return Mesh._CAP_END;
  31386. },
  31387. enumerable: true,
  31388. configurable: true
  31389. });
  31390. Object.defineProperty(Mesh, "CAP_ALL", {
  31391. /**
  31392. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31393. */
  31394. get: function () {
  31395. return Mesh._CAP_ALL;
  31396. },
  31397. enumerable: true,
  31398. configurable: true
  31399. });
  31400. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31401. set: function (callback) {
  31402. if (this._onBeforeDrawObserver) {
  31403. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31404. }
  31405. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31406. },
  31407. enumerable: true,
  31408. configurable: true
  31409. });
  31410. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31411. get: function () {
  31412. return this._morphTargetManager;
  31413. },
  31414. set: function (value) {
  31415. if (this._morphTargetManager === value) {
  31416. return;
  31417. }
  31418. this._morphTargetManager = value;
  31419. this._syncGeometryWithMorphTargetManager();
  31420. },
  31421. enumerable: true,
  31422. configurable: true
  31423. });
  31424. Object.defineProperty(Mesh.prototype, "source", {
  31425. get: function () {
  31426. return this._source;
  31427. },
  31428. enumerable: true,
  31429. configurable: true
  31430. });
  31431. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31432. get: function () {
  31433. return this._unIndexed;
  31434. },
  31435. set: function (value) {
  31436. if (this._unIndexed !== value) {
  31437. this._unIndexed = value;
  31438. this._markSubMeshesAsAttributesDirty();
  31439. }
  31440. },
  31441. enumerable: true,
  31442. configurable: true
  31443. });
  31444. // Methods
  31445. /**
  31446. * Returns the string "Mesh".
  31447. */
  31448. Mesh.prototype.getClassName = function () {
  31449. return "Mesh";
  31450. };
  31451. /**
  31452. * Returns a string.
  31453. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31454. */
  31455. Mesh.prototype.toString = function (fullDetails) {
  31456. var ret = _super.prototype.toString.call(this, fullDetails);
  31457. ret += ", n vertices: " + this.getTotalVertices();
  31458. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31459. if (this.animations) {
  31460. for (var i = 0; i < this.animations.length; i++) {
  31461. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31462. }
  31463. }
  31464. if (fullDetails) {
  31465. if (this._geometry) {
  31466. var ib = this.getIndices();
  31467. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31468. if (vb && ib) {
  31469. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31470. }
  31471. }
  31472. else {
  31473. ret += ", flat shading: UNKNOWN";
  31474. }
  31475. }
  31476. return ret;
  31477. };
  31478. Mesh.prototype._unBindEffect = function () {
  31479. _super.prototype._unBindEffect.call(this);
  31480. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31481. var instance = _a[_i];
  31482. instance._unBindEffect();
  31483. }
  31484. };
  31485. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31486. /**
  31487. * True if the mesh has some Levels Of Details (LOD).
  31488. * Returns a boolean.
  31489. */
  31490. get: function () {
  31491. return this._LODLevels.length > 0;
  31492. },
  31493. enumerable: true,
  31494. configurable: true
  31495. });
  31496. /**
  31497. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31498. * @returns an array of {BABYLON.MeshLODLevel}
  31499. */
  31500. Mesh.prototype.getLODLevels = function () {
  31501. return this._LODLevels;
  31502. };
  31503. Mesh.prototype._sortLODLevels = function () {
  31504. this._LODLevels.sort(function (a, b) {
  31505. if (a.distance < b.distance) {
  31506. return 1;
  31507. }
  31508. if (a.distance > b.distance) {
  31509. return -1;
  31510. }
  31511. return 0;
  31512. });
  31513. };
  31514. /**
  31515. * Add a mesh as LOD level triggered at the given distance.
  31516. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31517. * @param {number} distance The distance from the center of the object to show this level
  31518. * @param {Mesh} mesh The mesh to be added as LOD level
  31519. * @return {Mesh} This mesh (for chaining)
  31520. */
  31521. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31522. if (mesh && mesh._masterMesh) {
  31523. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31524. return this;
  31525. }
  31526. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31527. this._LODLevels.push(level);
  31528. if (mesh) {
  31529. mesh._masterMesh = this;
  31530. }
  31531. this._sortLODLevels();
  31532. return this;
  31533. };
  31534. /**
  31535. * Returns the LOD level mesh at the passed distance or null if not found.
  31536. * It is related to the method `addLODLevel(distance, mesh)`.
  31537. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31538. * Returns an object Mesh or `null`.
  31539. */
  31540. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31541. for (var index = 0; index < this._LODLevels.length; index++) {
  31542. var level = this._LODLevels[index];
  31543. if (level.distance === distance) {
  31544. return level.mesh;
  31545. }
  31546. }
  31547. return null;
  31548. };
  31549. /**
  31550. * Remove a mesh from the LOD array
  31551. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31552. * @param {Mesh} mesh The mesh to be removed.
  31553. * @return {Mesh} This mesh (for chaining)
  31554. */
  31555. Mesh.prototype.removeLODLevel = function (mesh) {
  31556. for (var index = 0; index < this._LODLevels.length; index++) {
  31557. if (this._LODLevels[index].mesh === mesh) {
  31558. this._LODLevels.splice(index, 1);
  31559. if (mesh) {
  31560. mesh._masterMesh = null;
  31561. }
  31562. }
  31563. }
  31564. this._sortLODLevels();
  31565. return this;
  31566. };
  31567. /**
  31568. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31569. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31570. */
  31571. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31572. if (!this._LODLevels || this._LODLevels.length === 0) {
  31573. return this;
  31574. }
  31575. var bSphere;
  31576. if (boundingSphere) {
  31577. bSphere = boundingSphere;
  31578. }
  31579. else {
  31580. var boundingInfo = this.getBoundingInfo();
  31581. bSphere = boundingInfo.boundingSphere;
  31582. }
  31583. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31584. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31585. if (this.onLODLevelSelection) {
  31586. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31587. }
  31588. return this;
  31589. }
  31590. for (var index = 0; index < this._LODLevels.length; index++) {
  31591. var level = this._LODLevels[index];
  31592. if (level.distance < distanceToCamera) {
  31593. if (level.mesh) {
  31594. level.mesh._preActivate();
  31595. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31596. }
  31597. if (this.onLODLevelSelection) {
  31598. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31599. }
  31600. return level.mesh;
  31601. }
  31602. }
  31603. if (this.onLODLevelSelection) {
  31604. this.onLODLevelSelection(distanceToCamera, this, this);
  31605. }
  31606. return this;
  31607. };
  31608. Object.defineProperty(Mesh.prototype, "geometry", {
  31609. /**
  31610. * Returns the mesh internal Geometry object.
  31611. */
  31612. get: function () {
  31613. return this._geometry;
  31614. },
  31615. enumerable: true,
  31616. configurable: true
  31617. });
  31618. /**
  31619. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31620. */
  31621. Mesh.prototype.getTotalVertices = function () {
  31622. if (this._geometry === null || this._geometry === undefined) {
  31623. return 0;
  31624. }
  31625. return this._geometry.getTotalVertices();
  31626. };
  31627. /**
  31628. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31629. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  31630. * You can force the copy with forceCopy === true
  31631. * Returns null if the mesh has no geometry or no vertex buffer.
  31632. * Possible `kind` values :
  31633. * - BABYLON.VertexBuffer.PositionKind
  31634. * - BABYLON.VertexBuffer.UVKind
  31635. * - BABYLON.VertexBuffer.UV2Kind
  31636. * - BABYLON.VertexBuffer.UV3Kind
  31637. * - BABYLON.VertexBuffer.UV4Kind
  31638. * - BABYLON.VertexBuffer.UV5Kind
  31639. * - BABYLON.VertexBuffer.UV6Kind
  31640. * - BABYLON.VertexBuffer.ColorKind
  31641. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31642. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31643. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31644. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31645. */
  31646. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31647. if (!this._geometry) {
  31648. return null;
  31649. }
  31650. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31651. };
  31652. /**
  31653. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31654. * Returns `null` if the mesh has no geometry.
  31655. * Possible `kind` values :
  31656. * - BABYLON.VertexBuffer.PositionKind
  31657. * - BABYLON.VertexBuffer.UVKind
  31658. * - BABYLON.VertexBuffer.UV2Kind
  31659. * - BABYLON.VertexBuffer.UV3Kind
  31660. * - BABYLON.VertexBuffer.UV4Kind
  31661. * - BABYLON.VertexBuffer.UV5Kind
  31662. * - BABYLON.VertexBuffer.UV6Kind
  31663. * - BABYLON.VertexBuffer.ColorKind
  31664. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31665. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31666. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31667. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31668. */
  31669. Mesh.prototype.getVertexBuffer = function (kind) {
  31670. if (!this._geometry) {
  31671. return null;
  31672. }
  31673. return this._geometry.getVertexBuffer(kind);
  31674. };
  31675. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31676. if (!this._geometry) {
  31677. if (this._delayInfo) {
  31678. return this._delayInfo.indexOf(kind) !== -1;
  31679. }
  31680. return false;
  31681. }
  31682. return this._geometry.isVerticesDataPresent(kind);
  31683. };
  31684. /**
  31685. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31686. * Possible `kind` values :
  31687. * - BABYLON.VertexBuffer.PositionKind
  31688. * - BABYLON.VertexBuffer.UVKind
  31689. * - BABYLON.VertexBuffer.UV2Kind
  31690. * - BABYLON.VertexBuffer.UV3Kind
  31691. * - BABYLON.VertexBuffer.UV4Kind
  31692. * - BABYLON.VertexBuffer.UV5Kind
  31693. * - BABYLON.VertexBuffer.UV6Kind
  31694. * - BABYLON.VertexBuffer.ColorKind
  31695. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31696. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31697. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31698. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31699. */
  31700. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31701. if (!this._geometry) {
  31702. if (this._delayInfo) {
  31703. return this._delayInfo.indexOf(kind) !== -1;
  31704. }
  31705. return false;
  31706. }
  31707. return this._geometry.isVertexBufferUpdatable(kind);
  31708. };
  31709. /**
  31710. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31711. * Possible `kind` values :
  31712. * - BABYLON.VertexBuffer.PositionKind
  31713. * - BABYLON.VertexBuffer.UVKind
  31714. * - BABYLON.VertexBuffer.UV2Kind
  31715. * - BABYLON.VertexBuffer.UV3Kind
  31716. * - BABYLON.VertexBuffer.UV4Kind
  31717. * - BABYLON.VertexBuffer.UV5Kind
  31718. * - BABYLON.VertexBuffer.UV6Kind
  31719. * - BABYLON.VertexBuffer.ColorKind
  31720. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31721. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31722. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31723. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31724. */
  31725. Mesh.prototype.getVerticesDataKinds = function () {
  31726. if (!this._geometry) {
  31727. var result = new Array();
  31728. if (this._delayInfo) {
  31729. this._delayInfo.forEach(function (kind, index, array) {
  31730. result.push(kind);
  31731. });
  31732. }
  31733. return result;
  31734. }
  31735. return this._geometry.getVerticesDataKinds();
  31736. };
  31737. /**
  31738. * Returns a positive integer : the total number of indices in this mesh geometry.
  31739. * Returns zero if the mesh has no geometry.
  31740. */
  31741. Mesh.prototype.getTotalIndices = function () {
  31742. if (!this._geometry) {
  31743. return 0;
  31744. }
  31745. return this._geometry.getTotalIndices();
  31746. };
  31747. /**
  31748. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31749. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  31750. * Returns an empty array if the mesh has no geometry.
  31751. */
  31752. Mesh.prototype.getIndices = function (copyWhenShared) {
  31753. if (!this._geometry) {
  31754. return [];
  31755. }
  31756. return this._geometry.getIndices(copyWhenShared);
  31757. };
  31758. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31759. get: function () {
  31760. return this._masterMesh !== null && this._masterMesh !== undefined;
  31761. },
  31762. enumerable: true,
  31763. configurable: true
  31764. });
  31765. /**
  31766. * Determine if the current mesh is ready to be rendered
  31767. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31768. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31769. * @returns true if all associated assets are ready (material, textures, shaders)
  31770. */
  31771. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31772. if (completeCheck === void 0) { completeCheck = false; }
  31773. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31774. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31775. return false;
  31776. }
  31777. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31778. return false;
  31779. }
  31780. if (!this.subMeshes || this.subMeshes.length === 0) {
  31781. return true;
  31782. }
  31783. if (!completeCheck) {
  31784. return true;
  31785. }
  31786. var engine = this.getEngine();
  31787. var scene = this.getScene();
  31788. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31789. this.computeWorldMatrix();
  31790. var mat = this.material || scene.defaultMaterial;
  31791. if (mat) {
  31792. if (mat.storeEffectOnSubMeshes) {
  31793. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31794. var subMesh = _a[_i];
  31795. var effectiveMaterial = subMesh.getMaterial();
  31796. if (effectiveMaterial) {
  31797. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31798. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31799. return false;
  31800. }
  31801. }
  31802. else {
  31803. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31804. return false;
  31805. }
  31806. }
  31807. }
  31808. }
  31809. }
  31810. else {
  31811. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31812. return false;
  31813. }
  31814. }
  31815. }
  31816. // Shadows
  31817. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31818. var light = _c[_b];
  31819. var generator = light.getShadowGenerator();
  31820. if (generator) {
  31821. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31822. var subMesh = _e[_d];
  31823. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31824. return false;
  31825. }
  31826. }
  31827. }
  31828. }
  31829. // LOD
  31830. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31831. var lod = _g[_f];
  31832. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31833. return false;
  31834. }
  31835. }
  31836. return true;
  31837. };
  31838. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31839. /**
  31840. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31841. * This property is pertinent only for updatable parametric shapes.
  31842. */
  31843. get: function () {
  31844. return this._areNormalsFrozen;
  31845. },
  31846. enumerable: true,
  31847. configurable: true
  31848. });
  31849. /**
  31850. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31851. * It has no effect at all on other shapes.
  31852. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31853. * Returns the Mesh.
  31854. */
  31855. Mesh.prototype.freezeNormals = function () {
  31856. this._areNormalsFrozen = true;
  31857. return this;
  31858. };
  31859. /**
  31860. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31861. * It has no effect at all on other shapes.
  31862. * It reactivates the mesh normals computation if it was previously frozen.
  31863. * Returns the Mesh.
  31864. */
  31865. Mesh.prototype.unfreezeNormals = function () {
  31866. this._areNormalsFrozen = false;
  31867. return this;
  31868. };
  31869. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31870. /**
  31871. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31872. */
  31873. set: function (count) {
  31874. this._overridenInstanceCount = count;
  31875. },
  31876. enumerable: true,
  31877. configurable: true
  31878. });
  31879. // Methods
  31880. Mesh.prototype._preActivate = function () {
  31881. var sceneRenderId = this.getScene().getRenderId();
  31882. if (this._preActivateId === sceneRenderId) {
  31883. return this;
  31884. }
  31885. this._preActivateId = sceneRenderId;
  31886. this._visibleInstances = null;
  31887. return this;
  31888. };
  31889. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31890. if (this._visibleInstances) {
  31891. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31892. }
  31893. return this;
  31894. };
  31895. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31896. if (!this._visibleInstances) {
  31897. this._visibleInstances = {};
  31898. this._visibleInstances.defaultRenderId = renderId;
  31899. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31900. }
  31901. if (!this._visibleInstances[renderId]) {
  31902. this._visibleInstances[renderId] = new Array();
  31903. }
  31904. this._visibleInstances[renderId].push(instance);
  31905. return this;
  31906. };
  31907. /**
  31908. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31909. * This means the mesh underlying bounding box and sphere are recomputed.
  31910. * Returns the Mesh.
  31911. */
  31912. Mesh.prototype.refreshBoundingInfo = function () {
  31913. return this._refreshBoundingInfo(false);
  31914. };
  31915. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31916. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31917. return this;
  31918. }
  31919. var data = this._getPositionData(applySkeleton);
  31920. if (data) {
  31921. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31922. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31923. }
  31924. if (this.subMeshes) {
  31925. for (var index = 0; index < this.subMeshes.length; index++) {
  31926. this.subMeshes[index].refreshBoundingInfo();
  31927. }
  31928. }
  31929. this._updateBoundingInfo();
  31930. return this;
  31931. };
  31932. Mesh.prototype._getPositionData = function (applySkeleton) {
  31933. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31934. if (data && applySkeleton && this.skeleton) {
  31935. data = BABYLON.Tools.Slice(data);
  31936. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31937. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31938. if (matricesWeightsData && matricesIndicesData) {
  31939. var needExtras = this.numBoneInfluencers > 4;
  31940. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31941. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31942. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31943. var tempVector = BABYLON.Tmp.Vector3[0];
  31944. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31945. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31946. var matWeightIdx = 0;
  31947. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31948. finalMatrix.reset();
  31949. var inf;
  31950. var weight;
  31951. for (inf = 0; inf < 4; inf++) {
  31952. weight = matricesWeightsData[matWeightIdx + inf];
  31953. if (weight <= 0)
  31954. break;
  31955. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31956. finalMatrix.addToSelf(tempMatrix);
  31957. }
  31958. if (needExtras) {
  31959. for (inf = 0; inf < 4; inf++) {
  31960. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31961. if (weight <= 0)
  31962. break;
  31963. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31964. finalMatrix.addToSelf(tempMatrix);
  31965. }
  31966. }
  31967. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31968. tempVector.toArray(data, index);
  31969. }
  31970. }
  31971. }
  31972. return data;
  31973. };
  31974. Mesh.prototype._createGlobalSubMesh = function (force) {
  31975. var totalVertices = this.getTotalVertices();
  31976. if (!totalVertices || !this.getIndices()) {
  31977. return null;
  31978. }
  31979. // Check if we need to recreate the submeshes
  31980. if (this.subMeshes && this.subMeshes.length > 0) {
  31981. var ib = this.getIndices();
  31982. if (!ib) {
  31983. return null;
  31984. }
  31985. var totalIndices = ib.length;
  31986. var needToRecreate = false;
  31987. if (force) {
  31988. needToRecreate = true;
  31989. }
  31990. else {
  31991. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31992. var submesh = _a[_i];
  31993. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31994. needToRecreate = true;
  31995. break;
  31996. }
  31997. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31998. needToRecreate = true;
  31999. break;
  32000. }
  32001. }
  32002. }
  32003. if (!needToRecreate) {
  32004. return this.subMeshes[0];
  32005. }
  32006. }
  32007. this.releaseSubMeshes();
  32008. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32009. };
  32010. Mesh.prototype.subdivide = function (count) {
  32011. if (count < 1) {
  32012. return;
  32013. }
  32014. var totalIndices = this.getTotalIndices();
  32015. var subdivisionSize = (totalIndices / count) | 0;
  32016. var offset = 0;
  32017. // Ensure that subdivisionSize is a multiple of 3
  32018. while (subdivisionSize % 3 !== 0) {
  32019. subdivisionSize++;
  32020. }
  32021. this.releaseSubMeshes();
  32022. for (var index = 0; index < count; index++) {
  32023. if (offset >= totalIndices) {
  32024. break;
  32025. }
  32026. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32027. offset += subdivisionSize;
  32028. }
  32029. this.synchronizeInstances();
  32030. };
  32031. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32032. if (updatable === void 0) { updatable = false; }
  32033. if (!this._geometry) {
  32034. var vertexData = new BABYLON.VertexData();
  32035. vertexData.set(data, kind);
  32036. var scene = this.getScene();
  32037. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32038. }
  32039. else {
  32040. this._geometry.setVerticesData(kind, data, updatable, stride);
  32041. }
  32042. return this;
  32043. };
  32044. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32045. if (updatable === void 0) { updatable = true; }
  32046. var vb = this.getVertexBuffer(kind);
  32047. if (!vb || vb.isUpdatable() === updatable) {
  32048. return;
  32049. }
  32050. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32051. };
  32052. /**
  32053. * Sets the mesh VertexBuffer.
  32054. * Returns the Mesh.
  32055. */
  32056. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32057. if (!this._geometry) {
  32058. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32059. }
  32060. this._geometry.setVerticesBuffer(buffer);
  32061. return this;
  32062. };
  32063. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32064. if (!this._geometry) {
  32065. return this;
  32066. }
  32067. if (!makeItUnique) {
  32068. this._geometry.updateVerticesData(kind, data, updateExtends);
  32069. }
  32070. else {
  32071. this.makeGeometryUnique();
  32072. this.updateVerticesData(kind, data, updateExtends, false);
  32073. }
  32074. return this;
  32075. };
  32076. /**
  32077. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32078. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32079. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32080. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32081. * Returns the Mesh.
  32082. */
  32083. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32084. if (computeNormals === void 0) { computeNormals = true; }
  32085. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32086. if (!positions) {
  32087. return this;
  32088. }
  32089. positionFunction(positions);
  32090. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32091. if (computeNormals) {
  32092. var indices = this.getIndices();
  32093. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32094. if (!normals) {
  32095. return this;
  32096. }
  32097. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32098. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32099. }
  32100. return this;
  32101. };
  32102. /**
  32103. * Creates a un-shared specific occurence of the geometry for the mesh.
  32104. * Returns the Mesh.
  32105. */
  32106. Mesh.prototype.makeGeometryUnique = function () {
  32107. if (!this._geometry) {
  32108. return this;
  32109. }
  32110. var oldGeometry = this._geometry;
  32111. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32112. oldGeometry.releaseForMesh(this, true);
  32113. geometry.applyToMesh(this);
  32114. return this;
  32115. };
  32116. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32117. if (totalVertices === void 0) { totalVertices = null; }
  32118. if (updatable === void 0) { updatable = false; }
  32119. if (!this._geometry) {
  32120. var vertexData = new BABYLON.VertexData();
  32121. vertexData.indices = indices;
  32122. var scene = this.getScene();
  32123. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32124. }
  32125. else {
  32126. this._geometry.setIndices(indices, totalVertices, updatable);
  32127. }
  32128. return this;
  32129. };
  32130. /**
  32131. * Update the current index buffer
  32132. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32133. * Returns the Mesh.
  32134. */
  32135. Mesh.prototype.updateIndices = function (indices, offset) {
  32136. if (!this._geometry) {
  32137. return this;
  32138. }
  32139. this._geometry.updateIndices(indices, offset);
  32140. return this;
  32141. };
  32142. /**
  32143. * Invert the geometry to move from a right handed system to a left handed one.
  32144. * Returns the Mesh.
  32145. */
  32146. Mesh.prototype.toLeftHanded = function () {
  32147. if (!this._geometry) {
  32148. return this;
  32149. }
  32150. this._geometry.toLeftHanded();
  32151. return this;
  32152. };
  32153. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32154. if (!this._geometry) {
  32155. return this;
  32156. }
  32157. var engine = this.getScene().getEngine();
  32158. // Wireframe
  32159. var indexToBind;
  32160. if (this._unIndexed) {
  32161. indexToBind = null;
  32162. }
  32163. else {
  32164. switch (fillMode) {
  32165. case BABYLON.Material.PointFillMode:
  32166. indexToBind = null;
  32167. break;
  32168. case BABYLON.Material.WireFrameFillMode:
  32169. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32170. break;
  32171. default:
  32172. case BABYLON.Material.TriangleFillMode:
  32173. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32174. break;
  32175. }
  32176. }
  32177. // VBOs
  32178. this._geometry._bind(effect, indexToBind);
  32179. return this;
  32180. };
  32181. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32182. if (alternate === void 0) { alternate = false; }
  32183. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32184. return this;
  32185. }
  32186. this.onBeforeDrawObservable.notifyObservers(this);
  32187. var scene = this.getScene();
  32188. var engine = scene.getEngine();
  32189. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32190. // or triangles as points
  32191. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32192. }
  32193. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32194. // Triangles as wireframe
  32195. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32196. }
  32197. else {
  32198. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32199. }
  32200. if (scene._isAlternateRenderingEnabled && !alternate) {
  32201. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32202. if (!effect || !scene.activeCamera) {
  32203. return this;
  32204. }
  32205. scene._switchToAlternateCameraConfiguration(true);
  32206. this._effectiveMaterial.bindView(effect);
  32207. this._effectiveMaterial.bindViewProjection(effect);
  32208. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32209. this._draw(subMesh, fillMode, instancesCount, true);
  32210. engine.setViewport(scene.activeCamera.viewport);
  32211. scene._switchToAlternateCameraConfiguration(false);
  32212. this._effectiveMaterial.bindView(effect);
  32213. this._effectiveMaterial.bindViewProjection(effect);
  32214. }
  32215. return this;
  32216. };
  32217. /**
  32218. * Registers for this mesh a javascript function called just before the rendering process.
  32219. * This function is passed the current mesh.
  32220. * Return the Mesh.
  32221. */
  32222. Mesh.prototype.registerBeforeRender = function (func) {
  32223. this.onBeforeRenderObservable.add(func);
  32224. return this;
  32225. };
  32226. /**
  32227. * Disposes a previously registered javascript function called before the rendering.
  32228. * This function is passed the current mesh.
  32229. * Returns the Mesh.
  32230. */
  32231. Mesh.prototype.unregisterBeforeRender = function (func) {
  32232. this.onBeforeRenderObservable.removeCallback(func);
  32233. return this;
  32234. };
  32235. /**
  32236. * Registers for this mesh a javascript function called just after the rendering is complete.
  32237. * This function is passed the current mesh.
  32238. * Returns the Mesh.
  32239. */
  32240. Mesh.prototype.registerAfterRender = function (func) {
  32241. this.onAfterRenderObservable.add(func);
  32242. return this;
  32243. };
  32244. /**
  32245. * Disposes a previously registered javascript function called after the rendering.
  32246. * This function is passed the current mesh.
  32247. * Return the Mesh.
  32248. */
  32249. Mesh.prototype.unregisterAfterRender = function (func) {
  32250. this.onAfterRenderObservable.removeCallback(func);
  32251. return this;
  32252. };
  32253. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32254. var scene = this.getScene();
  32255. this._batchCache.mustReturn = false;
  32256. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32257. this._batchCache.visibleInstances[subMeshId] = null;
  32258. if (this._visibleInstances) {
  32259. var currentRenderId = scene.getRenderId();
  32260. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32261. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32262. var selfRenderId = this._renderId;
  32263. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32264. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32265. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32266. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32267. }
  32268. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32269. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32270. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32271. this._batchCache.mustReturn = true;
  32272. return this._batchCache;
  32273. }
  32274. if (currentRenderId !== selfRenderId) {
  32275. this._batchCache.renderSelf[subMeshId] = false;
  32276. }
  32277. }
  32278. this._renderIdForInstances[subMeshId] = currentRenderId;
  32279. }
  32280. return this._batchCache;
  32281. };
  32282. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32283. var visibleInstances = batch.visibleInstances[subMesh._id];
  32284. if (!visibleInstances) {
  32285. return this;
  32286. }
  32287. var matricesCount = visibleInstances.length + 1;
  32288. var bufferSize = matricesCount * 16 * 4;
  32289. var currentInstancesBufferSize = this._instancesBufferSize;
  32290. var instancesBuffer = this._instancesBuffer;
  32291. while (this._instancesBufferSize < bufferSize) {
  32292. this._instancesBufferSize *= 2;
  32293. }
  32294. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32295. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32296. }
  32297. var offset = 0;
  32298. var instancesCount = 0;
  32299. var world = this.getWorldMatrix();
  32300. if (batch.renderSelf[subMesh._id]) {
  32301. world.copyToArray(this._instancesData, offset);
  32302. offset += 16;
  32303. instancesCount++;
  32304. }
  32305. if (visibleInstances) {
  32306. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32307. var instance = visibleInstances[instanceIndex];
  32308. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32309. offset += 16;
  32310. instancesCount++;
  32311. }
  32312. }
  32313. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32314. if (instancesBuffer) {
  32315. instancesBuffer.dispose();
  32316. }
  32317. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32318. this._instancesBuffer = instancesBuffer;
  32319. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32320. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32321. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32322. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32323. }
  32324. else {
  32325. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32326. }
  32327. this._bind(subMesh, effect, fillMode);
  32328. this._draw(subMesh, fillMode, instancesCount);
  32329. engine.unbindInstanceAttributes();
  32330. return this;
  32331. };
  32332. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32333. var scene = this.getScene();
  32334. var engine = scene.getEngine();
  32335. if (hardwareInstancedRendering) {
  32336. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32337. }
  32338. else {
  32339. if (batch.renderSelf[subMesh._id]) {
  32340. // Draw
  32341. if (onBeforeDraw) {
  32342. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32343. }
  32344. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32345. }
  32346. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32347. if (visibleInstancesForSubMesh) {
  32348. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32349. var instance = visibleInstancesForSubMesh[instanceIndex];
  32350. // World
  32351. var world = instance.getWorldMatrix();
  32352. if (onBeforeDraw) {
  32353. onBeforeDraw(true, world, effectiveMaterial);
  32354. }
  32355. // Draw
  32356. this._draw(subMesh, fillMode);
  32357. }
  32358. }
  32359. }
  32360. return this;
  32361. };
  32362. /**
  32363. * Triggers the draw call for the mesh.
  32364. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32365. * Returns the Mesh.
  32366. */
  32367. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32368. this._checkOcclusionQuery();
  32369. if (this._isOccluded) {
  32370. return this;
  32371. }
  32372. var scene = this.getScene();
  32373. // Managing instances
  32374. var batch = this._getInstancesRenderList(subMesh._id);
  32375. if (batch.mustReturn) {
  32376. return this;
  32377. }
  32378. // Checking geometry state
  32379. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32380. return this;
  32381. }
  32382. this.onBeforeRenderObservable.notifyObservers(this);
  32383. var engine = scene.getEngine();
  32384. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32385. // Material
  32386. var material = subMesh.getMaterial();
  32387. if (!material) {
  32388. return this;
  32389. }
  32390. this._effectiveMaterial = material;
  32391. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32392. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32393. return this;
  32394. }
  32395. }
  32396. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32397. return this;
  32398. }
  32399. // Alpha mode
  32400. if (enableAlphaMode) {
  32401. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32402. }
  32403. // Outline - step 1
  32404. var savedDepthWrite = engine.getDepthWrite();
  32405. if (this.renderOutline) {
  32406. engine.setDepthWrite(false);
  32407. scene.getOutlineRenderer().render(subMesh, batch);
  32408. engine.setDepthWrite(savedDepthWrite);
  32409. }
  32410. var effect;
  32411. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32412. effect = subMesh.effect;
  32413. }
  32414. else {
  32415. effect = this._effectiveMaterial.getEffect();
  32416. }
  32417. if (!effect) {
  32418. return this;
  32419. }
  32420. var sideOrientation = this.overrideMaterialSideOrientation;
  32421. if (sideOrientation == null) {
  32422. sideOrientation = this._effectiveMaterial.sideOrientation;
  32423. if (this._getWorldMatrixDeterminant() < 0) {
  32424. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32425. }
  32426. }
  32427. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32428. if (this._effectiveMaterial.forceDepthWrite) {
  32429. engine.setDepthWrite(true);
  32430. }
  32431. // Bind
  32432. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32433. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32434. this._bind(subMesh, effect, fillMode);
  32435. }
  32436. var world = this.getWorldMatrix();
  32437. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32438. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32439. }
  32440. else {
  32441. this._effectiveMaterial.bind(world, this);
  32442. }
  32443. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32444. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32445. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32446. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32447. }
  32448. // Draw
  32449. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32450. // Unbind
  32451. this._effectiveMaterial.unbind();
  32452. // Outline - step 2
  32453. if (this.renderOutline && savedDepthWrite) {
  32454. engine.setDepthWrite(true);
  32455. engine.setColorWrite(false);
  32456. scene.getOutlineRenderer().render(subMesh, batch);
  32457. engine.setColorWrite(true);
  32458. }
  32459. // Overlay
  32460. if (this.renderOverlay) {
  32461. var currentMode = engine.getAlphaMode();
  32462. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32463. scene.getOutlineRenderer().render(subMesh, batch, true);
  32464. engine.setAlphaMode(currentMode);
  32465. }
  32466. this.onAfterRenderObservable.notifyObservers(this);
  32467. return this;
  32468. };
  32469. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32470. if (isInstance && effectiveMaterial) {
  32471. effectiveMaterial.bindOnlyWorldMatrix(world);
  32472. }
  32473. };
  32474. /**
  32475. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32476. */
  32477. Mesh.prototype.getEmittedParticleSystems = function () {
  32478. var results = new Array();
  32479. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32480. var particleSystem = this.getScene().particleSystems[index];
  32481. if (particleSystem.emitter === this) {
  32482. results.push(particleSystem);
  32483. }
  32484. }
  32485. return results;
  32486. };
  32487. /**
  32488. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32489. */
  32490. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32491. var results = new Array();
  32492. var descendants = this.getDescendants();
  32493. descendants.push(this);
  32494. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32495. var particleSystem = this.getScene().particleSystems[index];
  32496. var emitter = particleSystem.emitter;
  32497. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32498. results.push(particleSystem);
  32499. }
  32500. }
  32501. return results;
  32502. };
  32503. /**
  32504. * Normalize matrix weights so that all vertices have a total weight set to 1
  32505. */
  32506. Mesh.prototype.cleanMatrixWeights = function () {
  32507. var epsilon = 1e-3;
  32508. var noInfluenceBoneIndex = 0.0;
  32509. if (this.skeleton) {
  32510. noInfluenceBoneIndex = this.skeleton.bones.length;
  32511. }
  32512. else {
  32513. return;
  32514. }
  32515. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32516. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32517. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32518. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32519. var influencers = this.numBoneInfluencers;
  32520. var size = matricesWeights.length;
  32521. for (var i = 0; i < size; i += 4) {
  32522. var weight = 0.0;
  32523. var firstZeroWeight = -1;
  32524. for (var j = 0; j < 4; j++) {
  32525. var w = matricesWeights[i + j];
  32526. weight += w;
  32527. if (w < epsilon && firstZeroWeight < 0) {
  32528. firstZeroWeight = j;
  32529. }
  32530. }
  32531. if (matricesWeightsExtra) {
  32532. for (var j = 0; j < 4; j++) {
  32533. var w = matricesWeightsExtra[i + j];
  32534. weight += w;
  32535. if (w < epsilon && firstZeroWeight < 0) {
  32536. firstZeroWeight = j + 4;
  32537. }
  32538. }
  32539. }
  32540. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32541. firstZeroWeight = influencers - 1;
  32542. }
  32543. if (weight > epsilon) {
  32544. var mweight = 1.0 / weight;
  32545. for (var j = 0; j < 4; j++) {
  32546. matricesWeights[i + j] *= mweight;
  32547. }
  32548. if (matricesWeightsExtra) {
  32549. for (var j = 0; j < 4; j++) {
  32550. matricesWeightsExtra[i + j] *= mweight;
  32551. }
  32552. }
  32553. }
  32554. else {
  32555. if (firstZeroWeight >= 4) {
  32556. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32557. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32558. }
  32559. else {
  32560. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32561. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32562. }
  32563. }
  32564. }
  32565. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32566. if (matricesIndicesExtra) {
  32567. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32568. }
  32569. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32570. if (matricesWeightsExtra) {
  32571. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32572. }
  32573. };
  32574. Mesh.prototype._checkDelayState = function () {
  32575. var scene = this.getScene();
  32576. if (this._geometry) {
  32577. this._geometry.load(scene);
  32578. }
  32579. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32580. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32581. this._queueLoad(scene);
  32582. }
  32583. return this;
  32584. };
  32585. Mesh.prototype._queueLoad = function (scene) {
  32586. var _this = this;
  32587. scene._addPendingData(this);
  32588. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32589. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32590. if (data instanceof ArrayBuffer) {
  32591. _this._delayLoadingFunction(data, _this);
  32592. }
  32593. else {
  32594. _this._delayLoadingFunction(JSON.parse(data), _this);
  32595. }
  32596. _this.instances.forEach(function (instance) {
  32597. instance._syncSubMeshes();
  32598. });
  32599. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32600. scene._removePendingData(_this);
  32601. }, function () { }, scene.database, getBinaryData);
  32602. return this;
  32603. };
  32604. /**
  32605. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32606. */
  32607. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32608. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32609. return false;
  32610. }
  32611. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32612. return false;
  32613. }
  32614. this._checkDelayState();
  32615. return true;
  32616. };
  32617. /**
  32618. * Sets the mesh material by the material or multiMaterial `id` property.
  32619. * The material `id` is a string identifying the material or the multiMaterial.
  32620. * This method returns the Mesh.
  32621. */
  32622. Mesh.prototype.setMaterialByID = function (id) {
  32623. var materials = this.getScene().materials;
  32624. var index;
  32625. for (index = materials.length - 1; index > -1; index--) {
  32626. if (materials[index].id === id) {
  32627. this.material = materials[index];
  32628. return this;
  32629. }
  32630. }
  32631. // Multi
  32632. var multiMaterials = this.getScene().multiMaterials;
  32633. for (index = multiMaterials.length - 1; index > -1; index--) {
  32634. if (multiMaterials[index].id === id) {
  32635. this.material = multiMaterials[index];
  32636. return this;
  32637. }
  32638. }
  32639. return this;
  32640. };
  32641. /**
  32642. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32643. */
  32644. Mesh.prototype.getAnimatables = function () {
  32645. var results = new Array();
  32646. if (this.material) {
  32647. results.push(this.material);
  32648. }
  32649. if (this.skeleton) {
  32650. results.push(this.skeleton);
  32651. }
  32652. return results;
  32653. };
  32654. /**
  32655. * Modifies the mesh geometry according to the passed transformation matrix.
  32656. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32657. * The mesh normals are modified accordingly the same transformation.
  32658. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32659. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32660. * Returns the Mesh.
  32661. */
  32662. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32663. // Position
  32664. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32665. return this;
  32666. }
  32667. var submeshes = this.subMeshes.splice(0);
  32668. this._resetPointsArrayCache();
  32669. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32670. var temp = new Array();
  32671. var index;
  32672. for (index = 0; index < data.length; index += 3) {
  32673. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32674. }
  32675. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32676. // Normals
  32677. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32678. return this;
  32679. }
  32680. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32681. temp = [];
  32682. for (index = 0; index < data.length; index += 3) {
  32683. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32684. }
  32685. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32686. // flip faces?
  32687. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32688. this.flipFaces();
  32689. }
  32690. // Restore submeshes
  32691. this.releaseSubMeshes();
  32692. this.subMeshes = submeshes;
  32693. return this;
  32694. };
  32695. /**
  32696. * Modifies the mesh geometry according to its own current World Matrix.
  32697. * The mesh World Matrix is then reset.
  32698. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32699. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32700. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32701. * Returns the Mesh.
  32702. */
  32703. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32704. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32705. this.scaling.copyFromFloats(1, 1, 1);
  32706. this.position.copyFromFloats(0, 0, 0);
  32707. this.rotation.copyFromFloats(0, 0, 0);
  32708. //only if quaternion is already set
  32709. if (this.rotationQuaternion) {
  32710. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32711. }
  32712. this._worldMatrix = BABYLON.Matrix.Identity();
  32713. return this;
  32714. };
  32715. Object.defineProperty(Mesh.prototype, "_positions", {
  32716. // Cache
  32717. get: function () {
  32718. if (this._geometry) {
  32719. return this._geometry._positions;
  32720. }
  32721. return null;
  32722. },
  32723. enumerable: true,
  32724. configurable: true
  32725. });
  32726. Mesh.prototype._resetPointsArrayCache = function () {
  32727. if (this._geometry) {
  32728. this._geometry._resetPointsArrayCache();
  32729. }
  32730. return this;
  32731. };
  32732. Mesh.prototype._generatePointsArray = function () {
  32733. if (this._geometry) {
  32734. return this._geometry._generatePointsArray();
  32735. }
  32736. return false;
  32737. };
  32738. /**
  32739. * Returns a new Mesh object generated from the current mesh properties.
  32740. * This method must not get confused with createInstance().
  32741. * The parameter `name` is a string, the name given to the new mesh.
  32742. * The optional parameter `newParent` can be any Node object (default `null`).
  32743. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32744. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  32745. */
  32746. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32747. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32748. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32749. };
  32750. /**
  32751. * Releases resources associated with this mesh.
  32752. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32753. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32754. */
  32755. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32756. var _this = this;
  32757. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32758. this.morphTargetManager = null;
  32759. if (this._geometry) {
  32760. this._geometry.releaseForMesh(this, true);
  32761. }
  32762. // Sources
  32763. var meshes = this.getScene().meshes;
  32764. meshes.forEach(function (abstractMesh) {
  32765. var mesh = abstractMesh;
  32766. if (mesh._source && mesh._source === _this) {
  32767. mesh._source = null;
  32768. }
  32769. });
  32770. this._source = null;
  32771. // Instances
  32772. if (this._instancesBuffer) {
  32773. this._instancesBuffer.dispose();
  32774. this._instancesBuffer = null;
  32775. }
  32776. while (this.instances.length) {
  32777. this.instances[0].dispose();
  32778. }
  32779. // Effect layers.
  32780. var effectLayers = this.getScene().effectLayers;
  32781. for (var i = 0; i < effectLayers.length; i++) {
  32782. var effectLayer = effectLayers[i];
  32783. if (effectLayer) {
  32784. effectLayer._disposeMesh(this);
  32785. }
  32786. }
  32787. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32788. };
  32789. /**
  32790. * Modifies the mesh geometry according to a displacement map.
  32791. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  32792. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32793. * This method returns nothing.
  32794. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32795. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32796. * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  32797. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32798. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32799. *
  32800. * Returns the Mesh.
  32801. */
  32802. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32803. var _this = this;
  32804. var scene = this.getScene();
  32805. var onload = function (img) {
  32806. // Getting height map data
  32807. var canvas = document.createElement("canvas");
  32808. var context = canvas.getContext("2d");
  32809. var heightMapWidth = img.width;
  32810. var heightMapHeight = img.height;
  32811. canvas.width = heightMapWidth;
  32812. canvas.height = heightMapHeight;
  32813. context.drawImage(img, 0, 0);
  32814. // Create VertexData from map data
  32815. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32816. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32817. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32818. //execute success callback, if set
  32819. if (onSuccess) {
  32820. onSuccess(_this);
  32821. }
  32822. };
  32823. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32824. return this;
  32825. };
  32826. /**
  32827. * Modifies the mesh geometry according to a displacementMap buffer.
  32828. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  32829. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32830. * This method returns nothing.
  32831. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32832. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32833. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32834. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32835. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32836. *
  32837. * Returns the Mesh.
  32838. */
  32839. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32840. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32841. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32842. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32843. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32844. return this;
  32845. }
  32846. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32847. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32848. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32849. var position = BABYLON.Vector3.Zero();
  32850. var normal = BABYLON.Vector3.Zero();
  32851. var uv = BABYLON.Vector2.Zero();
  32852. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32853. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32854. for (var index = 0; index < positions.length; index += 3) {
  32855. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32856. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32857. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32858. // Compute height
  32859. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32860. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32861. var pos = (u + v * heightMapWidth) * 4;
  32862. var r = buffer[pos] / 255.0;
  32863. var g = buffer[pos + 1] / 255.0;
  32864. var b = buffer[pos + 2] / 255.0;
  32865. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32866. normal.normalize();
  32867. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32868. position = position.add(normal);
  32869. position.toArray(positions, index);
  32870. }
  32871. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32872. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32873. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32874. return this;
  32875. };
  32876. /**
  32877. * Modify the mesh to get a flat shading rendering.
  32878. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32879. * This method returns the Mesh.
  32880. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32881. */
  32882. Mesh.prototype.convertToFlatShadedMesh = function () {
  32883. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32884. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32885. var kinds = this.getVerticesDataKinds();
  32886. var vbs = {};
  32887. var data = {};
  32888. var newdata = {};
  32889. var updatableNormals = false;
  32890. var kindIndex;
  32891. var kind;
  32892. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32893. kind = kinds[kindIndex];
  32894. var vertexBuffer = this.getVertexBuffer(kind);
  32895. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32896. updatableNormals = vertexBuffer.isUpdatable();
  32897. kinds.splice(kindIndex, 1);
  32898. kindIndex--;
  32899. continue;
  32900. }
  32901. vbs[kind] = vertexBuffer;
  32902. data[kind] = vbs[kind].getData();
  32903. newdata[kind] = [];
  32904. }
  32905. // Save previous submeshes
  32906. var previousSubmeshes = this.subMeshes.slice(0);
  32907. var indices = this.getIndices();
  32908. var totalIndices = this.getTotalIndices();
  32909. // Generating unique vertices per face
  32910. var index;
  32911. for (index = 0; index < totalIndices; index++) {
  32912. var vertexIndex = indices[index];
  32913. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32914. kind = kinds[kindIndex];
  32915. var stride = vbs[kind].getStrideSize();
  32916. for (var offset = 0; offset < stride; offset++) {
  32917. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32918. }
  32919. }
  32920. }
  32921. // Updating faces & normal
  32922. var normals = [];
  32923. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32924. for (index = 0; index < totalIndices; index += 3) {
  32925. indices[index] = index;
  32926. indices[index + 1] = index + 1;
  32927. indices[index + 2] = index + 2;
  32928. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32929. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32930. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32931. var p1p2 = p1.subtract(p2);
  32932. var p3p2 = p3.subtract(p2);
  32933. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32934. // Store same normals for every vertex
  32935. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32936. normals.push(normal.x);
  32937. normals.push(normal.y);
  32938. normals.push(normal.z);
  32939. }
  32940. }
  32941. this.setIndices(indices);
  32942. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32943. // Updating vertex buffers
  32944. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32945. kind = kinds[kindIndex];
  32946. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32947. }
  32948. // Updating submeshes
  32949. this.releaseSubMeshes();
  32950. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32951. var previousOne = previousSubmeshes[submeshIndex];
  32952. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32953. }
  32954. this.synchronizeInstances();
  32955. return this;
  32956. };
  32957. /**
  32958. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32959. * In other words, more vertices, no more indices and a single bigger VBO.
  32960. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32961. * Returns the Mesh.
  32962. */
  32963. Mesh.prototype.convertToUnIndexedMesh = function () {
  32964. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32965. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32966. var kinds = this.getVerticesDataKinds();
  32967. var vbs = {};
  32968. var data = {};
  32969. var newdata = {};
  32970. var kindIndex;
  32971. var kind;
  32972. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32973. kind = kinds[kindIndex];
  32974. var vertexBuffer = this.getVertexBuffer(kind);
  32975. vbs[kind] = vertexBuffer;
  32976. data[kind] = vbs[kind].getData();
  32977. newdata[kind] = [];
  32978. }
  32979. // Save previous submeshes
  32980. var previousSubmeshes = this.subMeshes.slice(0);
  32981. var indices = this.getIndices();
  32982. var totalIndices = this.getTotalIndices();
  32983. // Generating unique vertices per face
  32984. var index;
  32985. for (index = 0; index < totalIndices; index++) {
  32986. var vertexIndex = indices[index];
  32987. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32988. kind = kinds[kindIndex];
  32989. var stride = vbs[kind].getStrideSize();
  32990. for (var offset = 0; offset < stride; offset++) {
  32991. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32992. }
  32993. }
  32994. }
  32995. // Updating indices
  32996. for (index = 0; index < totalIndices; index += 3) {
  32997. indices[index] = index;
  32998. indices[index + 1] = index + 1;
  32999. indices[index + 2] = index + 2;
  33000. }
  33001. this.setIndices(indices);
  33002. // Updating vertex buffers
  33003. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33004. kind = kinds[kindIndex];
  33005. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33006. }
  33007. // Updating submeshes
  33008. this.releaseSubMeshes();
  33009. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33010. var previousOne = previousSubmeshes[submeshIndex];
  33011. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33012. }
  33013. this._unIndexed = true;
  33014. this.synchronizeInstances();
  33015. return this;
  33016. };
  33017. /**
  33018. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33019. * This method returns the Mesh.
  33020. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33021. */
  33022. Mesh.prototype.flipFaces = function (flipNormals) {
  33023. if (flipNormals === void 0) { flipNormals = false; }
  33024. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33025. var i;
  33026. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33027. for (i = 0; i < vertex_data.normals.length; i++) {
  33028. vertex_data.normals[i] *= -1;
  33029. }
  33030. }
  33031. if (vertex_data.indices) {
  33032. var temp;
  33033. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33034. // reassign indices
  33035. temp = vertex_data.indices[i + 1];
  33036. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33037. vertex_data.indices[i + 2] = temp;
  33038. }
  33039. }
  33040. vertex_data.applyToMesh(this);
  33041. return this;
  33042. };
  33043. // Instances
  33044. /**
  33045. * Creates a new InstancedMesh object from the mesh model.
  33046. * An instance shares the same properties and the same material than its model.
  33047. * Only these properties of each instance can then be set individually :
  33048. * - position
  33049. * - rotation
  33050. * - rotationQuaternion
  33051. * - setPivotMatrix
  33052. * - scaling
  33053. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33054. * Warning : this method is not supported for Line mesh and LineSystem
  33055. */
  33056. Mesh.prototype.createInstance = function (name) {
  33057. return new BABYLON.InstancedMesh(name, this);
  33058. };
  33059. /**
  33060. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33061. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33062. * This method returns the Mesh.
  33063. */
  33064. Mesh.prototype.synchronizeInstances = function () {
  33065. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33066. var instance = this.instances[instanceIndex];
  33067. instance._syncSubMeshes();
  33068. }
  33069. return this;
  33070. };
  33071. /**
  33072. * Simplify the mesh according to the given array of settings.
  33073. * Function will return immediately and will simplify async. It returns the Mesh.
  33074. * @param settings a collection of simplification settings.
  33075. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33076. * @param type the type of simplification to run.
  33077. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33078. */
  33079. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33080. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33081. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33082. this.getScene().simplificationQueue.addTask({
  33083. settings: settings,
  33084. parallelProcessing: parallelProcessing,
  33085. mesh: this,
  33086. simplificationType: simplificationType,
  33087. successCallback: successCallback
  33088. });
  33089. return this;
  33090. };
  33091. /**
  33092. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33093. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33094. * This should be used together with the simplification to avoid disappearing triangles.
  33095. * Returns the Mesh.
  33096. * @param successCallback an optional success callback to be called after the optimization finished.
  33097. */
  33098. Mesh.prototype.optimizeIndices = function (successCallback) {
  33099. var _this = this;
  33100. var indices = this.getIndices();
  33101. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33102. if (!positions || !indices) {
  33103. return this;
  33104. }
  33105. var vectorPositions = new Array();
  33106. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33107. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33108. }
  33109. var dupes = new Array();
  33110. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33111. var realPos = vectorPositions.length - 1 - iteration;
  33112. var testedPosition = vectorPositions[realPos];
  33113. for (var j = 0; j < realPos; ++j) {
  33114. var againstPosition = vectorPositions[j];
  33115. if (testedPosition.equals(againstPosition)) {
  33116. dupes[realPos] = j;
  33117. break;
  33118. }
  33119. }
  33120. }, function () {
  33121. for (var i = 0; i < indices.length; ++i) {
  33122. indices[i] = dupes[indices[i]] || indices[i];
  33123. }
  33124. //indices are now reordered
  33125. var originalSubMeshes = _this.subMeshes.slice(0);
  33126. _this.setIndices(indices);
  33127. _this.subMeshes = originalSubMeshes;
  33128. if (successCallback) {
  33129. successCallback(_this);
  33130. }
  33131. });
  33132. return this;
  33133. };
  33134. Mesh.prototype.serialize = function (serializationObject) {
  33135. serializationObject.name = this.name;
  33136. serializationObject.id = this.id;
  33137. serializationObject.type = this.getClassName();
  33138. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33139. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33140. }
  33141. serializationObject.position = this.position.asArray();
  33142. if (this.rotationQuaternion) {
  33143. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33144. }
  33145. else if (this.rotation) {
  33146. serializationObject.rotation = this.rotation.asArray();
  33147. }
  33148. serializationObject.scaling = this.scaling.asArray();
  33149. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33150. serializationObject.isEnabled = this.isEnabled(false);
  33151. serializationObject.isVisible = this.isVisible;
  33152. serializationObject.infiniteDistance = this.infiniteDistance;
  33153. serializationObject.pickable = this.isPickable;
  33154. serializationObject.receiveShadows = this.receiveShadows;
  33155. serializationObject.billboardMode = this.billboardMode;
  33156. serializationObject.visibility = this.visibility;
  33157. serializationObject.checkCollisions = this.checkCollisions;
  33158. serializationObject.isBlocker = this.isBlocker;
  33159. // Parent
  33160. if (this.parent) {
  33161. serializationObject.parentId = this.parent.id;
  33162. }
  33163. // Geometry
  33164. serializationObject.isUnIndexed = this.isUnIndexed;
  33165. var geometry = this._geometry;
  33166. if (geometry) {
  33167. var geometryId = geometry.id;
  33168. serializationObject.geometryId = geometryId;
  33169. // SubMeshes
  33170. serializationObject.subMeshes = [];
  33171. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33172. var subMesh = this.subMeshes[subIndex];
  33173. serializationObject.subMeshes.push({
  33174. materialIndex: subMesh.materialIndex,
  33175. verticesStart: subMesh.verticesStart,
  33176. verticesCount: subMesh.verticesCount,
  33177. indexStart: subMesh.indexStart,
  33178. indexCount: subMesh.indexCount
  33179. });
  33180. }
  33181. }
  33182. // Material
  33183. if (this.material) {
  33184. serializationObject.materialId = this.material.id;
  33185. }
  33186. else {
  33187. this.material = null;
  33188. }
  33189. // Morph targets
  33190. if (this.morphTargetManager) {
  33191. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33192. }
  33193. // Skeleton
  33194. if (this.skeleton) {
  33195. serializationObject.skeletonId = this.skeleton.id;
  33196. }
  33197. // Physics
  33198. //TODO implement correct serialization for physics impostors.
  33199. var impostor = this.getPhysicsImpostor();
  33200. if (impostor) {
  33201. serializationObject.physicsMass = impostor.getParam("mass");
  33202. serializationObject.physicsFriction = impostor.getParam("friction");
  33203. serializationObject.physicsRestitution = impostor.getParam("mass");
  33204. serializationObject.physicsImpostor = impostor.type;
  33205. }
  33206. // Metadata
  33207. if (this.metadata) {
  33208. serializationObject.metadata = this.metadata;
  33209. }
  33210. // Instances
  33211. serializationObject.instances = [];
  33212. for (var index = 0; index < this.instances.length; index++) {
  33213. var instance = this.instances[index];
  33214. var serializationInstance = {
  33215. name: instance.name,
  33216. id: instance.id,
  33217. position: instance.position.asArray(),
  33218. scaling: instance.scaling.asArray()
  33219. };
  33220. if (instance.rotationQuaternion) {
  33221. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33222. }
  33223. else if (instance.rotation) {
  33224. serializationInstance.rotation = instance.rotation.asArray();
  33225. }
  33226. serializationObject.instances.push(serializationInstance);
  33227. // Animations
  33228. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33229. serializationInstance.ranges = instance.serializeAnimationRanges();
  33230. }
  33231. //
  33232. // Animations
  33233. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33234. serializationObject.ranges = this.serializeAnimationRanges();
  33235. // Layer mask
  33236. serializationObject.layerMask = this.layerMask;
  33237. // Alpha
  33238. serializationObject.alphaIndex = this.alphaIndex;
  33239. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33240. // Overlay
  33241. serializationObject.overlayAlpha = this.overlayAlpha;
  33242. serializationObject.overlayColor = this.overlayColor.asArray();
  33243. serializationObject.renderOverlay = this.renderOverlay;
  33244. // Fog
  33245. serializationObject.applyFog = this.applyFog;
  33246. // Action Manager
  33247. if (this.actionManager) {
  33248. serializationObject.actions = this.actionManager.serialize(this.name);
  33249. }
  33250. };
  33251. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33252. if (!this.geometry) {
  33253. return;
  33254. }
  33255. this._markSubMeshesAsAttributesDirty();
  33256. var morphTargetManager = this._morphTargetManager;
  33257. if (morphTargetManager && morphTargetManager.vertexCount) {
  33258. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33259. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33260. this.morphTargetManager = null;
  33261. return;
  33262. }
  33263. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33264. var morphTarget = morphTargetManager.getActiveTarget(index);
  33265. var positions = morphTarget.getPositions();
  33266. if (!positions) {
  33267. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33268. return;
  33269. }
  33270. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33271. var normals = morphTarget.getNormals();
  33272. if (normals) {
  33273. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33274. }
  33275. var tangents = morphTarget.getTangents();
  33276. if (tangents) {
  33277. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33278. }
  33279. }
  33280. }
  33281. else {
  33282. var index = 0;
  33283. // Positions
  33284. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33285. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33286. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33287. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33288. }
  33289. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33290. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33291. }
  33292. index++;
  33293. }
  33294. }
  33295. };
  33296. // Statics
  33297. /**
  33298. * Returns a new Mesh object parsed from the source provided.
  33299. * The parameter `parsedMesh` is the source.
  33300. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33301. */
  33302. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33303. var mesh;
  33304. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33305. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33306. }
  33307. else {
  33308. mesh = new Mesh(parsedMesh.name, scene);
  33309. }
  33310. mesh.id = parsedMesh.id;
  33311. if (BABYLON.Tags) {
  33312. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33313. }
  33314. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33315. if (parsedMesh.metadata !== undefined) {
  33316. mesh.metadata = parsedMesh.metadata;
  33317. }
  33318. if (parsedMesh.rotationQuaternion) {
  33319. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33320. }
  33321. else if (parsedMesh.rotation) {
  33322. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33323. }
  33324. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33325. if (parsedMesh.localMatrix) {
  33326. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33327. }
  33328. else if (parsedMesh.pivotMatrix) {
  33329. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33330. }
  33331. mesh.setEnabled(parsedMesh.isEnabled);
  33332. mesh.isVisible = parsedMesh.isVisible;
  33333. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33334. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33335. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33336. if (parsedMesh.applyFog !== undefined) {
  33337. mesh.applyFog = parsedMesh.applyFog;
  33338. }
  33339. if (parsedMesh.pickable !== undefined) {
  33340. mesh.isPickable = parsedMesh.pickable;
  33341. }
  33342. if (parsedMesh.alphaIndex !== undefined) {
  33343. mesh.alphaIndex = parsedMesh.alphaIndex;
  33344. }
  33345. mesh.receiveShadows = parsedMesh.receiveShadows;
  33346. mesh.billboardMode = parsedMesh.billboardMode;
  33347. if (parsedMesh.visibility !== undefined) {
  33348. mesh.visibility = parsedMesh.visibility;
  33349. }
  33350. mesh.checkCollisions = parsedMesh.checkCollisions;
  33351. if (parsedMesh.isBlocker !== undefined) {
  33352. mesh.isBlocker = parsedMesh.isBlocker;
  33353. }
  33354. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33355. // freezeWorldMatrix
  33356. if (parsedMesh.freezeWorldMatrix) {
  33357. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33358. }
  33359. // Parent
  33360. if (parsedMesh.parentId) {
  33361. mesh._waitingParentId = parsedMesh.parentId;
  33362. }
  33363. // Actions
  33364. if (parsedMesh.actions !== undefined) {
  33365. mesh._waitingActions = parsedMesh.actions;
  33366. }
  33367. // Overlay
  33368. if (parsedMesh.overlayAlpha !== undefined) {
  33369. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33370. }
  33371. if (parsedMesh.overlayColor !== undefined) {
  33372. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33373. }
  33374. if (parsedMesh.renderOverlay !== undefined) {
  33375. mesh.renderOverlay = parsedMesh.renderOverlay;
  33376. }
  33377. // Geometry
  33378. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33379. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33380. if (parsedMesh.delayLoadingFile) {
  33381. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33382. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33383. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33384. if (parsedMesh._binaryInfo) {
  33385. mesh._binaryInfo = parsedMesh._binaryInfo;
  33386. }
  33387. mesh._delayInfo = [];
  33388. if (parsedMesh.hasUVs) {
  33389. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33390. }
  33391. if (parsedMesh.hasUVs2) {
  33392. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33393. }
  33394. if (parsedMesh.hasUVs3) {
  33395. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33396. }
  33397. if (parsedMesh.hasUVs4) {
  33398. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33399. }
  33400. if (parsedMesh.hasUVs5) {
  33401. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33402. }
  33403. if (parsedMesh.hasUVs6) {
  33404. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33405. }
  33406. if (parsedMesh.hasColors) {
  33407. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33408. }
  33409. if (parsedMesh.hasMatricesIndices) {
  33410. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33411. }
  33412. if (parsedMesh.hasMatricesWeights) {
  33413. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33414. }
  33415. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33416. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33417. mesh._checkDelayState();
  33418. }
  33419. }
  33420. else {
  33421. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33422. }
  33423. // Material
  33424. if (parsedMesh.materialId) {
  33425. mesh.setMaterialByID(parsedMesh.materialId);
  33426. }
  33427. else {
  33428. mesh.material = null;
  33429. }
  33430. // Morph targets
  33431. if (parsedMesh.morphTargetManagerId > -1) {
  33432. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33433. }
  33434. // Skeleton
  33435. if (parsedMesh.skeletonId > -1) {
  33436. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33437. if (parsedMesh.numBoneInfluencers) {
  33438. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33439. }
  33440. }
  33441. // Animations
  33442. if (parsedMesh.animations) {
  33443. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33444. var parsedAnimation = parsedMesh.animations[animationIndex];
  33445. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33446. }
  33447. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33448. }
  33449. if (parsedMesh.autoAnimate) {
  33450. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33451. }
  33452. // Layer Mask
  33453. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33454. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33455. }
  33456. else {
  33457. mesh.layerMask = 0x0FFFFFFF;
  33458. }
  33459. // Physics
  33460. if (parsedMesh.physicsImpostor) {
  33461. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33462. mass: parsedMesh.physicsMass,
  33463. friction: parsedMesh.physicsFriction,
  33464. restitution: parsedMesh.physicsRestitution
  33465. }, scene);
  33466. }
  33467. // Instances
  33468. if (parsedMesh.instances) {
  33469. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33470. var parsedInstance = parsedMesh.instances[index];
  33471. var instance = mesh.createInstance(parsedInstance.name);
  33472. if (parsedInstance.id) {
  33473. instance.id = parsedInstance.id;
  33474. }
  33475. if (BABYLON.Tags) {
  33476. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33477. }
  33478. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33479. if (parsedInstance.parentId) {
  33480. instance._waitingParentId = parsedInstance.parentId;
  33481. }
  33482. if (parsedInstance.rotationQuaternion) {
  33483. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33484. }
  33485. else if (parsedInstance.rotation) {
  33486. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33487. }
  33488. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33489. instance.checkCollisions = mesh.checkCollisions;
  33490. if (parsedMesh.animations) {
  33491. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33492. parsedAnimation = parsedMesh.animations[animationIndex];
  33493. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33494. }
  33495. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33496. }
  33497. }
  33498. }
  33499. return mesh;
  33500. };
  33501. /**
  33502. * Creates a ribbon mesh.
  33503. * Please consider using the same method from the MeshBuilder class instead.
  33504. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33505. *
  33506. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33507. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33508. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33509. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33510. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  33511. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  33512. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  33513. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33514. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33515. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33516. */
  33517. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33518. if (closeArray === void 0) { closeArray = false; }
  33519. if (updatable === void 0) { updatable = false; }
  33520. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33521. pathArray: pathArray,
  33522. closeArray: closeArray,
  33523. closePath: closePath,
  33524. offset: offset,
  33525. updatable: updatable,
  33526. sideOrientation: sideOrientation,
  33527. instance: instance
  33528. }, scene);
  33529. };
  33530. /**
  33531. * Creates a plane polygonal mesh. By default, this is a disc.
  33532. * Please consider using the same method from the MeshBuilder class instead.
  33533. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33534. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  33535. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33536. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33537. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33538. */
  33539. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33540. if (scene === void 0) { scene = null; }
  33541. var options = {
  33542. radius: radius,
  33543. tessellation: tessellation,
  33544. sideOrientation: sideOrientation,
  33545. updatable: updatable
  33546. };
  33547. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33548. };
  33549. /**
  33550. * Creates a box mesh.
  33551. * Please consider using the same method from the MeshBuilder class instead.
  33552. * The parameter `size` sets the size (float) of each box side (default 1).
  33553. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33554. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33555. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33556. */
  33557. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33558. if (scene === void 0) { scene = null; }
  33559. var options = {
  33560. size: size,
  33561. sideOrientation: sideOrientation,
  33562. updatable: updatable
  33563. };
  33564. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33565. };
  33566. /**
  33567. * Creates a sphere mesh.
  33568. * Please consider using the same method from the MeshBuilder class instead.
  33569. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33570. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33571. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33572. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33573. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33574. */
  33575. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33576. var options = {
  33577. segments: segments,
  33578. diameterX: diameter,
  33579. diameterY: diameter,
  33580. diameterZ: diameter,
  33581. sideOrientation: sideOrientation,
  33582. updatable: updatable
  33583. };
  33584. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33585. };
  33586. /**
  33587. * Creates a cylinder or a cone mesh.
  33588. * Please consider using the same method from the MeshBuilder class instead.
  33589. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33590. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33591. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  33592. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33593. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33594. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33595. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33596. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33597. */
  33598. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33599. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33600. if (scene !== undefined) {
  33601. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33602. updatable = scene;
  33603. }
  33604. scene = subdivisions;
  33605. subdivisions = 1;
  33606. }
  33607. var options = {
  33608. height: height,
  33609. diameterTop: diameterTop,
  33610. diameterBottom: diameterBottom,
  33611. tessellation: tessellation,
  33612. subdivisions: subdivisions,
  33613. sideOrientation: sideOrientation,
  33614. updatable: updatable
  33615. };
  33616. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33617. };
  33618. // Torus (Code from SharpDX.org)
  33619. /**
  33620. * Creates a torus mesh.
  33621. * Please consider using the same method from the MeshBuilder class instead.
  33622. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33623. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33624. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33625. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33626. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33627. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33628. */
  33629. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33630. var options = {
  33631. diameter: diameter,
  33632. thickness: thickness,
  33633. tessellation: tessellation,
  33634. sideOrientation: sideOrientation,
  33635. updatable: updatable
  33636. };
  33637. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33638. };
  33639. /**
  33640. * Creates a torus knot mesh.
  33641. * Please consider using the same method from the MeshBuilder class instead.
  33642. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33643. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33644. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33645. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33646. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33647. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33648. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33649. */
  33650. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33651. var options = {
  33652. radius: radius,
  33653. tube: tube,
  33654. radialSegments: radialSegments,
  33655. tubularSegments: tubularSegments,
  33656. p: p,
  33657. q: q,
  33658. sideOrientation: sideOrientation,
  33659. updatable: updatable
  33660. };
  33661. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33662. };
  33663. /**
  33664. * Creates a line mesh.
  33665. * Please consider using the same method from the MeshBuilder class instead.
  33666. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  33667. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33668. * The parameter `points` is an array successive Vector3.
  33669. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  33670. * When updating an instance, remember that only point positions can change, not the number of points.
  33671. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33672. */
  33673. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33674. if (scene === void 0) { scene = null; }
  33675. if (updatable === void 0) { updatable = false; }
  33676. if (instance === void 0) { instance = null; }
  33677. var options = {
  33678. points: points,
  33679. updatable: updatable,
  33680. instance: instance
  33681. };
  33682. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33683. };
  33684. /**
  33685. * Creates a dashed line mesh.
  33686. * Please consider using the same method from the MeshBuilder class instead.
  33687. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  33688. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33689. * The parameter `points` is an array successive Vector3.
  33690. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33691. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33692. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33693. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  33694. * When updating an instance, remember that only point positions can change, not the number of points.
  33695. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33696. */
  33697. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33698. if (scene === void 0) { scene = null; }
  33699. var options = {
  33700. points: points,
  33701. dashSize: dashSize,
  33702. gapSize: gapSize,
  33703. dashNb: dashNb,
  33704. updatable: updatable,
  33705. instance: instance
  33706. };
  33707. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33708. };
  33709. /**
  33710. * Creates a polygon mesh.
  33711. * Please consider using the same method from the MeshBuilder class instead.
  33712. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33713. * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors.
  33714. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33715. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33716. * Remember you can only change the shape positions, not their number when updating a polygon.
  33717. */
  33718. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33719. var options = {
  33720. shape: shape,
  33721. holes: holes,
  33722. updatable: updatable,
  33723. sideOrientation: sideOrientation
  33724. };
  33725. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33726. };
  33727. /**
  33728. * Creates an extruded polygon mesh, with depth in the Y direction.
  33729. * Please consider using the same method from the MeshBuilder class instead.
  33730. */
  33731. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33732. var options = {
  33733. shape: shape,
  33734. holes: holes,
  33735. depth: depth,
  33736. updatable: updatable,
  33737. sideOrientation: sideOrientation
  33738. };
  33739. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33740. };
  33741. /**
  33742. * Creates an extruded shape mesh.
  33743. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33744. * Please consider using the same method from the MeshBuilder class instead.
  33745. *
  33746. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33747. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  33748. * extruded along the Z axis.
  33749. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33750. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  33751. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33752. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  33753. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  33754. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33755. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33756. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33757. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33758. */
  33759. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33760. if (scene === void 0) { scene = null; }
  33761. var options = {
  33762. shape: shape,
  33763. path: path,
  33764. scale: scale,
  33765. rotation: rotation,
  33766. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33767. sideOrientation: sideOrientation,
  33768. instance: instance,
  33769. updatable: updatable
  33770. };
  33771. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33772. };
  33773. /**
  33774. * Creates an custom extruded shape mesh.
  33775. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33776. * Please consider using the same method from the MeshBuilder class instead.
  33777. *
  33778. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33779. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  33780. * extruded along the Z axis.
  33781. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33782. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  33783. * and the distance of this point from the begining of the path :
  33784. * ```javascript
  33785. * var rotationFunction = function(i, distance) {
  33786. * // do things
  33787. * return rotationValue; }
  33788. * ```
  33789. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33790. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  33791. * and the distance of this point from the begining of the path :
  33792. * ```javascript
  33793. * var scaleFunction = function(i, distance) {
  33794. * // do things
  33795. * return scaleValue;}
  33796. * ```
  33797. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33798. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33799. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33800. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  33801. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  33802. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33803. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33804. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33805. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33806. */
  33807. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33808. var options = {
  33809. shape: shape,
  33810. path: path,
  33811. scaleFunction: scaleFunction,
  33812. rotationFunction: rotationFunction,
  33813. ribbonCloseArray: ribbonCloseArray,
  33814. ribbonClosePath: ribbonClosePath,
  33815. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33816. sideOrientation: sideOrientation,
  33817. instance: instance,
  33818. updatable: updatable
  33819. };
  33820. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33821. };
  33822. /**
  33823. * Creates lathe mesh.
  33824. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33825. * Please consider using the same method from the MeshBuilder class instead.
  33826. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  33827. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33828. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33829. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33830. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33831. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33832. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33833. */
  33834. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33835. var options = {
  33836. shape: shape,
  33837. radius: radius,
  33838. tessellation: tessellation,
  33839. sideOrientation: sideOrientation,
  33840. updatable: updatable
  33841. };
  33842. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33843. };
  33844. /**
  33845. * Creates a plane mesh.
  33846. * Please consider using the same method from the MeshBuilder class instead.
  33847. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33848. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33849. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33850. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33851. */
  33852. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33853. var options = {
  33854. size: size,
  33855. width: size,
  33856. height: size,
  33857. sideOrientation: sideOrientation,
  33858. updatable: updatable
  33859. };
  33860. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33861. };
  33862. /**
  33863. * Creates a ground mesh.
  33864. * Please consider using the same method from the MeshBuilder class instead.
  33865. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33866. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33867. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33868. */
  33869. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33870. var options = {
  33871. width: width,
  33872. height: height,
  33873. subdivisions: subdivisions,
  33874. updatable: updatable
  33875. };
  33876. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33877. };
  33878. /**
  33879. * Creates a tiled ground mesh.
  33880. * Please consider using the same method from the MeshBuilder class instead.
  33881. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33882. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33883. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33884. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33885. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33886. * numbers of subdivisions on the ground width and height of each tile.
  33887. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33888. */
  33889. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33890. var options = {
  33891. xmin: xmin,
  33892. zmin: zmin,
  33893. xmax: xmax,
  33894. zmax: zmax,
  33895. subdivisions: subdivisions,
  33896. precision: precision,
  33897. updatable: updatable
  33898. };
  33899. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33900. };
  33901. /**
  33902. * Creates a ground mesh from a height map.
  33903. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33904. * Please consider using the same method from the MeshBuilder class instead.
  33905. * The parameter `url` sets the URL of the height map image resource.
  33906. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33907. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33908. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33909. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33910. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  33911. * This function is passed the newly built mesh :
  33912. * ```javascript
  33913. * function(mesh) { // do things
  33914. * return; }
  33915. * ```
  33916. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33917. */
  33918. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33919. var options = {
  33920. width: width,
  33921. height: height,
  33922. subdivisions: subdivisions,
  33923. minHeight: minHeight,
  33924. maxHeight: maxHeight,
  33925. updatable: updatable,
  33926. onReady: onReady
  33927. };
  33928. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33929. };
  33930. /**
  33931. * Creates a tube mesh.
  33932. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33933. * Please consider using the same method from the MeshBuilder class instead.
  33934. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33935. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33936. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33937. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33938. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  33939. * It must return a radius value (positive float) :
  33940. * ```javascript
  33941. * var radiusFunction = function(i, distance) {
  33942. * // do things
  33943. * return radius; }
  33944. * ```
  33945. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  33946. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  33947. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33948. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33949. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33950. */
  33951. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33952. var options = {
  33953. path: path,
  33954. radius: radius,
  33955. tessellation: tessellation,
  33956. radiusFunction: radiusFunction,
  33957. arc: 1,
  33958. cap: cap,
  33959. updatable: updatable,
  33960. sideOrientation: sideOrientation,
  33961. instance: instance
  33962. };
  33963. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33964. };
  33965. /**
  33966. * Creates a polyhedron mesh.
  33967. * Please consider using the same method from the MeshBuilder class instead.
  33968. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  33969. * to choose the wanted type.
  33970. * The parameter `size` (positive float, default 1) sets the polygon size.
  33971. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33972. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  33973. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  33974. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`).
  33975. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  33976. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  33977. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33978. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33979. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33980. */
  33981. Mesh.CreatePolyhedron = function (name, options, scene) {
  33982. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33983. };
  33984. /**
  33985. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33986. * Please consider using the same method from the MeshBuilder class instead.
  33987. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33988. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  33989. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33990. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  33991. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33992. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33993. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33994. */
  33995. Mesh.CreateIcoSphere = function (name, options, scene) {
  33996. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33997. };
  33998. /**
  33999. * Creates a decal mesh.
  34000. * Please consider using the same method from the MeshBuilder class instead.
  34001. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  34002. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34003. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34004. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34005. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34006. */
  34007. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34008. var options = {
  34009. position: position,
  34010. normal: normal,
  34011. size: size,
  34012. angle: angle
  34013. };
  34014. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34015. };
  34016. // Skeletons
  34017. /**
  34018. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34019. */
  34020. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34021. if (!this._sourcePositions) {
  34022. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34023. if (!source) {
  34024. return this._sourcePositions;
  34025. }
  34026. this._sourcePositions = new Float32Array(source);
  34027. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34028. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34029. }
  34030. }
  34031. return this._sourcePositions;
  34032. };
  34033. /**
  34034. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34035. */
  34036. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34037. if (!this._sourceNormals) {
  34038. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34039. if (!source) {
  34040. return this._sourceNormals;
  34041. }
  34042. this._sourceNormals = new Float32Array(source);
  34043. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34044. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34045. }
  34046. }
  34047. return this._sourceNormals;
  34048. };
  34049. /**
  34050. * Updates the vertex buffer by applying transformation from the bones.
  34051. * Returns the Mesh.
  34052. *
  34053. * @param {skeleton} skeleton to apply
  34054. */
  34055. Mesh.prototype.applySkeleton = function (skeleton) {
  34056. if (!this.geometry) {
  34057. return this;
  34058. }
  34059. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34060. return this;
  34061. }
  34062. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34063. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34064. return this;
  34065. }
  34066. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34067. return this;
  34068. }
  34069. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34070. return this;
  34071. }
  34072. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34073. return this;
  34074. }
  34075. if (!this._sourcePositions) {
  34076. var submeshes = this.subMeshes.slice();
  34077. this.setPositionsForCPUSkinning();
  34078. this.subMeshes = submeshes;
  34079. }
  34080. if (!this._sourceNormals) {
  34081. this.setNormalsForCPUSkinning();
  34082. }
  34083. // positionsData checks for not being Float32Array will only pass at most once
  34084. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34085. if (!positionsData) {
  34086. return this;
  34087. }
  34088. if (!(positionsData instanceof Float32Array)) {
  34089. positionsData = new Float32Array(positionsData);
  34090. }
  34091. // normalsData checks for not being Float32Array will only pass at most once
  34092. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34093. if (!normalsData) {
  34094. return this;
  34095. }
  34096. if (!(normalsData instanceof Float32Array)) {
  34097. normalsData = new Float32Array(normalsData);
  34098. }
  34099. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34100. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34101. if (!matricesWeightsData || !matricesIndicesData) {
  34102. return this;
  34103. }
  34104. var needExtras = this.numBoneInfluencers > 4;
  34105. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34106. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34107. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34108. var tempVector3 = BABYLON.Vector3.Zero();
  34109. var finalMatrix = new BABYLON.Matrix();
  34110. var tempMatrix = new BABYLON.Matrix();
  34111. var matWeightIdx = 0;
  34112. var inf;
  34113. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34114. var weight;
  34115. for (inf = 0; inf < 4; inf++) {
  34116. weight = matricesWeightsData[matWeightIdx + inf];
  34117. if (weight > 0) {
  34118. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34119. finalMatrix.addToSelf(tempMatrix);
  34120. }
  34121. else
  34122. break;
  34123. }
  34124. if (needExtras) {
  34125. for (inf = 0; inf < 4; inf++) {
  34126. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34127. if (weight > 0) {
  34128. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34129. finalMatrix.addToSelf(tempMatrix);
  34130. }
  34131. else
  34132. break;
  34133. }
  34134. }
  34135. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34136. tempVector3.toArray(positionsData, index);
  34137. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34138. tempVector3.toArray(normalsData, index);
  34139. finalMatrix.reset();
  34140. }
  34141. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34142. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34143. return this;
  34144. };
  34145. // Tools
  34146. /**
  34147. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34148. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34149. */
  34150. Mesh.MinMax = function (meshes) {
  34151. var minVector = null;
  34152. var maxVector = null;
  34153. meshes.forEach(function (mesh, index, array) {
  34154. var boundingInfo = mesh.getBoundingInfo();
  34155. var boundingBox = boundingInfo.boundingBox;
  34156. if (!minVector || !maxVector) {
  34157. minVector = boundingBox.minimumWorld;
  34158. maxVector = boundingBox.maximumWorld;
  34159. }
  34160. else {
  34161. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34162. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34163. }
  34164. });
  34165. if (!minVector || !maxVector) {
  34166. return {
  34167. min: BABYLON.Vector3.Zero(),
  34168. max: BABYLON.Vector3.Zero()
  34169. };
  34170. }
  34171. return {
  34172. min: minVector,
  34173. max: maxVector
  34174. };
  34175. };
  34176. /**
  34177. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34178. */
  34179. Mesh.Center = function (meshesOrMinMaxVector) {
  34180. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34181. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34182. };
  34183. /**
  34184. * Merge the array of meshes into a single mesh for performance reasons.
  34185. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34186. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34187. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34188. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34189. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34190. */
  34191. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34192. if (disposeSource === void 0) { disposeSource = true; }
  34193. var index;
  34194. if (!allow32BitsIndices) {
  34195. var totalVertices = 0;
  34196. // Counting vertices
  34197. for (index = 0; index < meshes.length; index++) {
  34198. if (meshes[index]) {
  34199. totalVertices += meshes[index].getTotalVertices();
  34200. if (totalVertices > 65536) {
  34201. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34202. return null;
  34203. }
  34204. }
  34205. }
  34206. }
  34207. // Merge
  34208. var vertexData = null;
  34209. var otherVertexData;
  34210. var indiceArray = new Array();
  34211. var source = null;
  34212. for (index = 0; index < meshes.length; index++) {
  34213. if (meshes[index]) {
  34214. meshes[index].computeWorldMatrix(true);
  34215. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  34216. otherVertexData.transform(meshes[index].getWorldMatrix());
  34217. if (vertexData) {
  34218. vertexData.merge(otherVertexData);
  34219. }
  34220. else {
  34221. vertexData = otherVertexData;
  34222. source = meshes[index];
  34223. }
  34224. if (subdivideWithSubMeshes) {
  34225. indiceArray.push(meshes[index].getTotalIndices());
  34226. }
  34227. }
  34228. }
  34229. source = source;
  34230. if (!meshSubclass) {
  34231. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34232. }
  34233. vertexData.applyToMesh(meshSubclass);
  34234. // Setting properties
  34235. meshSubclass.material = source.material;
  34236. meshSubclass.checkCollisions = source.checkCollisions;
  34237. // Cleaning
  34238. if (disposeSource) {
  34239. for (index = 0; index < meshes.length; index++) {
  34240. if (meshes[index]) {
  34241. meshes[index].dispose();
  34242. }
  34243. }
  34244. }
  34245. // Subdivide
  34246. if (subdivideWithSubMeshes) {
  34247. //-- Suppresions du submesh global
  34248. meshSubclass.releaseSubMeshes();
  34249. index = 0;
  34250. var offset = 0;
  34251. //-- aplique la subdivision en fonction du tableau d'indices
  34252. while (index < indiceArray.length) {
  34253. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34254. offset += indiceArray[index];
  34255. index++;
  34256. }
  34257. }
  34258. return meshSubclass;
  34259. };
  34260. // Consts
  34261. Mesh._FRONTSIDE = 0;
  34262. Mesh._BACKSIDE = 1;
  34263. Mesh._DOUBLESIDE = 2;
  34264. Mesh._DEFAULTSIDE = 0;
  34265. Mesh._NO_CAP = 0;
  34266. Mesh._CAP_START = 1;
  34267. Mesh._CAP_END = 2;
  34268. Mesh._CAP_ALL = 3;
  34269. return Mesh;
  34270. }(BABYLON.AbstractMesh));
  34271. BABYLON.Mesh = Mesh;
  34272. })(BABYLON || (BABYLON = {}));
  34273. //# sourceMappingURL=babylon.mesh.js.map
  34274. var BABYLON;
  34275. (function (BABYLON) {
  34276. var BaseSubMesh = /** @class */ (function () {
  34277. function BaseSubMesh() {
  34278. }
  34279. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34280. get: function () {
  34281. return this._materialEffect;
  34282. },
  34283. enumerable: true,
  34284. configurable: true
  34285. });
  34286. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34287. if (defines === void 0) { defines = null; }
  34288. if (this._materialEffect === effect) {
  34289. if (!effect) {
  34290. this._materialDefines = null;
  34291. }
  34292. return;
  34293. }
  34294. this._materialDefines = defines;
  34295. this._materialEffect = effect;
  34296. };
  34297. return BaseSubMesh;
  34298. }());
  34299. BABYLON.BaseSubMesh = BaseSubMesh;
  34300. var SubMesh = /** @class */ (function (_super) {
  34301. __extends(SubMesh, _super);
  34302. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34303. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34304. var _this = _super.call(this) || this;
  34305. _this.materialIndex = materialIndex;
  34306. _this.verticesStart = verticesStart;
  34307. _this.verticesCount = verticesCount;
  34308. _this.indexStart = indexStart;
  34309. _this.indexCount = indexCount;
  34310. _this._renderId = 0;
  34311. _this._mesh = mesh;
  34312. _this._renderingMesh = renderingMesh || mesh;
  34313. mesh.subMeshes.push(_this);
  34314. _this._trianglePlanes = [];
  34315. _this._id = mesh.subMeshes.length - 1;
  34316. if (createBoundingBox) {
  34317. _this.refreshBoundingInfo();
  34318. mesh.computeWorldMatrix(true);
  34319. }
  34320. return _this;
  34321. }
  34322. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34323. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34324. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34325. };
  34326. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34327. get: function () {
  34328. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34329. },
  34330. enumerable: true,
  34331. configurable: true
  34332. });
  34333. /**
  34334. * Returns the submesh BoudingInfo object.
  34335. */
  34336. SubMesh.prototype.getBoundingInfo = function () {
  34337. if (this.IsGlobal) {
  34338. return this._mesh.getBoundingInfo();
  34339. }
  34340. return this._boundingInfo;
  34341. };
  34342. /**
  34343. * Sets the submesh BoundingInfo.
  34344. * Return the SubMesh.
  34345. */
  34346. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34347. this._boundingInfo = boundingInfo;
  34348. return this;
  34349. };
  34350. /**
  34351. * Returns the mesh of the current submesh.
  34352. */
  34353. SubMesh.prototype.getMesh = function () {
  34354. return this._mesh;
  34355. };
  34356. /**
  34357. * Returns the rendering mesh of the submesh.
  34358. */
  34359. SubMesh.prototype.getRenderingMesh = function () {
  34360. return this._renderingMesh;
  34361. };
  34362. /**
  34363. * Returns the submesh material.
  34364. */
  34365. SubMesh.prototype.getMaterial = function () {
  34366. var rootMaterial = this._renderingMesh.material;
  34367. if (rootMaterial === null || rootMaterial === undefined) {
  34368. return this._mesh.getScene().defaultMaterial;
  34369. }
  34370. else if (rootMaterial.getSubMaterial) {
  34371. var multiMaterial = rootMaterial;
  34372. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34373. if (this._currentMaterial !== effectiveMaterial) {
  34374. this._currentMaterial = effectiveMaterial;
  34375. this._materialDefines = null;
  34376. }
  34377. return effectiveMaterial;
  34378. }
  34379. return rootMaterial;
  34380. };
  34381. // Methods
  34382. /**
  34383. * Sets a new updated BoundingInfo object to the submesh.
  34384. * Returns the SubMesh.
  34385. */
  34386. SubMesh.prototype.refreshBoundingInfo = function () {
  34387. this._lastColliderWorldVertices = null;
  34388. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34389. return this;
  34390. }
  34391. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34392. if (!data) {
  34393. this._boundingInfo = this._mesh.getBoundingInfo();
  34394. return this;
  34395. }
  34396. var indices = this._renderingMesh.getIndices();
  34397. var extend;
  34398. //is this the only submesh?
  34399. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34400. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34401. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34402. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34403. }
  34404. else {
  34405. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34406. }
  34407. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34408. return this;
  34409. };
  34410. SubMesh.prototype._checkCollision = function (collider) {
  34411. var boundingInfo = this.getBoundingInfo();
  34412. return boundingInfo._checkCollision(collider);
  34413. };
  34414. /**
  34415. * Updates the submesh BoundingInfo.
  34416. * Returns the Submesh.
  34417. */
  34418. SubMesh.prototype.updateBoundingInfo = function (world) {
  34419. var boundingInfo = this.getBoundingInfo();
  34420. if (!boundingInfo) {
  34421. this.refreshBoundingInfo();
  34422. boundingInfo = this.getBoundingInfo();
  34423. }
  34424. boundingInfo.update(world);
  34425. return this;
  34426. };
  34427. /**
  34428. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34429. * Boolean returned.
  34430. */
  34431. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34432. var boundingInfo = this.getBoundingInfo();
  34433. if (!boundingInfo) {
  34434. return false;
  34435. }
  34436. return boundingInfo.isInFrustum(frustumPlanes);
  34437. };
  34438. /**
  34439. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34440. * Boolean returned.
  34441. */
  34442. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34443. var boundingInfo = this.getBoundingInfo();
  34444. if (!boundingInfo) {
  34445. return false;
  34446. }
  34447. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34448. };
  34449. /**
  34450. * Renders the submesh.
  34451. * Returns it.
  34452. */
  34453. SubMesh.prototype.render = function (enableAlphaMode) {
  34454. this._renderingMesh.render(this, enableAlphaMode);
  34455. return this;
  34456. };
  34457. /**
  34458. * Returns a new Index Buffer.
  34459. * Type returned : WebGLBuffer.
  34460. */
  34461. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34462. if (!this._linesIndexBuffer) {
  34463. var linesIndices = [];
  34464. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34465. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34466. }
  34467. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34468. this.linesIndexCount = linesIndices.length;
  34469. }
  34470. return this._linesIndexBuffer;
  34471. };
  34472. /**
  34473. * True is the passed Ray intersects the submesh bounding box.
  34474. * Boolean returned.
  34475. */
  34476. SubMesh.prototype.canIntersects = function (ray) {
  34477. var boundingInfo = this.getBoundingInfo();
  34478. if (!boundingInfo) {
  34479. return false;
  34480. }
  34481. return ray.intersectsBox(boundingInfo.boundingBox);
  34482. };
  34483. /**
  34484. * Returns an object IntersectionInfo.
  34485. */
  34486. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34487. var intersectInfo = null;
  34488. var material = this.getMaterial();
  34489. if (!material) {
  34490. return null;
  34491. }
  34492. switch (material.fillMode) {
  34493. case BABYLON.Material.PointListDrawMode:
  34494. case BABYLON.Material.LineListDrawMode:
  34495. case BABYLON.Material.LineLoopDrawMode:
  34496. case BABYLON.Material.LineStripDrawMode:
  34497. case BABYLON.Material.TriangleFanDrawMode:
  34498. case BABYLON.Material.TriangleStripDrawMode:
  34499. return null;
  34500. }
  34501. // LineMesh first as it's also a Mesh...
  34502. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34503. var lineMesh = this._mesh;
  34504. // Line test
  34505. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34506. var p0 = positions[indices[index]];
  34507. var p1 = positions[indices[index + 1]];
  34508. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34509. if (length < 0) {
  34510. continue;
  34511. }
  34512. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34513. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34514. if (fastCheck) {
  34515. break;
  34516. }
  34517. }
  34518. }
  34519. }
  34520. else {
  34521. // Triangles test
  34522. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34523. var p0 = positions[indices[index]];
  34524. var p1 = positions[indices[index + 1]];
  34525. var p2 = positions[indices[index + 2]];
  34526. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34527. if (currentIntersectInfo) {
  34528. if (currentIntersectInfo.distance < 0) {
  34529. continue;
  34530. }
  34531. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34532. intersectInfo = currentIntersectInfo;
  34533. intersectInfo.faceId = index / 3;
  34534. if (fastCheck) {
  34535. break;
  34536. }
  34537. }
  34538. }
  34539. }
  34540. }
  34541. return intersectInfo;
  34542. };
  34543. SubMesh.prototype._rebuild = function () {
  34544. if (this._linesIndexBuffer) {
  34545. this._linesIndexBuffer = null;
  34546. }
  34547. };
  34548. // Clone
  34549. /**
  34550. * Creates a new Submesh from the passed Mesh.
  34551. */
  34552. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34553. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34554. if (!this.IsGlobal) {
  34555. var boundingInfo = this.getBoundingInfo();
  34556. if (!boundingInfo) {
  34557. return result;
  34558. }
  34559. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34560. }
  34561. return result;
  34562. };
  34563. // Dispose
  34564. /**
  34565. * Disposes the Submesh.
  34566. * Returns nothing.
  34567. */
  34568. SubMesh.prototype.dispose = function () {
  34569. if (this._linesIndexBuffer) {
  34570. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34571. this._linesIndexBuffer = null;
  34572. }
  34573. // Remove from mesh
  34574. var index = this._mesh.subMeshes.indexOf(this);
  34575. this._mesh.subMeshes.splice(index, 1);
  34576. };
  34577. // Statics
  34578. /**
  34579. * Creates a new Submesh from the passed parameters :
  34580. * - materialIndex (integer) : the index of the main mesh material.
  34581. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34582. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34583. * - mesh (Mesh) : the main mesh to create the submesh from.
  34584. * - renderingMesh (optional Mesh) : rendering mesh.
  34585. */
  34586. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34587. var minVertexIndex = Number.MAX_VALUE;
  34588. var maxVertexIndex = -Number.MAX_VALUE;
  34589. renderingMesh = (renderingMesh || mesh);
  34590. var indices = renderingMesh.getIndices();
  34591. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34592. var vertexIndex = indices[index];
  34593. if (vertexIndex < minVertexIndex)
  34594. minVertexIndex = vertexIndex;
  34595. if (vertexIndex > maxVertexIndex)
  34596. maxVertexIndex = vertexIndex;
  34597. }
  34598. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34599. };
  34600. return SubMesh;
  34601. }(BaseSubMesh));
  34602. BABYLON.SubMesh = SubMesh;
  34603. })(BABYLON || (BABYLON = {}));
  34604. //# sourceMappingURL=babylon.subMesh.js.map
  34605. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34606. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34607. s = arguments[i];
  34608. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34609. t[p] = s[p];
  34610. }
  34611. return t;
  34612. };
  34613. var BABYLON;
  34614. (function (BABYLON) {
  34615. /**
  34616. * Manages the defines for the Material
  34617. */
  34618. var MaterialDefines = /** @class */ (function () {
  34619. function MaterialDefines() {
  34620. this._isDirty = true;
  34621. /** @hidden */
  34622. this._areLightsDirty = true;
  34623. /** @hidden */
  34624. this._areAttributesDirty = true;
  34625. /** @hidden */
  34626. this._areTexturesDirty = true;
  34627. /** @hidden */
  34628. this._areFresnelDirty = true;
  34629. /** @hidden */
  34630. this._areMiscDirty = true;
  34631. /** @hidden */
  34632. this._areImageProcessingDirty = true;
  34633. /** @hidden */
  34634. this._normals = false;
  34635. /** @hidden */
  34636. this._uvs = false;
  34637. /** @hidden */
  34638. this._needNormals = false;
  34639. /** @hidden */
  34640. this._needUVs = false;
  34641. }
  34642. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34643. /**
  34644. * Specifies if the material needs to be re-calculated
  34645. */
  34646. get: function () {
  34647. return this._isDirty;
  34648. },
  34649. enumerable: true,
  34650. configurable: true
  34651. });
  34652. /**
  34653. * Marks the material to indicate that it has been re-calculated
  34654. */
  34655. MaterialDefines.prototype.markAsProcessed = function () {
  34656. this._isDirty = false;
  34657. this._areAttributesDirty = false;
  34658. this._areTexturesDirty = false;
  34659. this._areFresnelDirty = false;
  34660. this._areLightsDirty = false;
  34661. this._areMiscDirty = false;
  34662. this._areImageProcessingDirty = false;
  34663. };
  34664. /**
  34665. * Marks the material to indicate that it needs to be re-calculated
  34666. */
  34667. MaterialDefines.prototype.markAsUnprocessed = function () {
  34668. this._isDirty = true;
  34669. };
  34670. /**
  34671. * Marks the material to indicate all of its defines need to be re-calculated
  34672. */
  34673. MaterialDefines.prototype.markAllAsDirty = function () {
  34674. this._areTexturesDirty = true;
  34675. this._areAttributesDirty = true;
  34676. this._areLightsDirty = true;
  34677. this._areFresnelDirty = true;
  34678. this._areMiscDirty = true;
  34679. this._areImageProcessingDirty = true;
  34680. this._isDirty = true;
  34681. };
  34682. /**
  34683. * Marks the material to indicate that image processing needs to be re-calculated
  34684. */
  34685. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34686. this._areImageProcessingDirty = true;
  34687. this._isDirty = true;
  34688. };
  34689. /**
  34690. * Marks the material to indicate the lights need to be re-calculated
  34691. */
  34692. MaterialDefines.prototype.markAsLightDirty = function () {
  34693. this._areLightsDirty = true;
  34694. this._isDirty = true;
  34695. };
  34696. /**
  34697. * Marks the attribute state as changed
  34698. */
  34699. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34700. this._areAttributesDirty = true;
  34701. this._isDirty = true;
  34702. };
  34703. /**
  34704. * Marks the texture state as changed
  34705. */
  34706. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34707. this._areTexturesDirty = true;
  34708. this._isDirty = true;
  34709. };
  34710. /**
  34711. * Marks the fresnel state as changed
  34712. */
  34713. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34714. this._areFresnelDirty = true;
  34715. this._isDirty = true;
  34716. };
  34717. /**
  34718. * Marks the misc state as changed
  34719. */
  34720. MaterialDefines.prototype.markAsMiscDirty = function () {
  34721. this._areMiscDirty = true;
  34722. this._isDirty = true;
  34723. };
  34724. /**
  34725. * Rebuilds the material defines
  34726. */
  34727. MaterialDefines.prototype.rebuild = function () {
  34728. if (this._keys) {
  34729. delete this._keys;
  34730. }
  34731. this._keys = [];
  34732. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34733. var key = _a[_i];
  34734. if (key[0] === "_") {
  34735. continue;
  34736. }
  34737. this._keys.push(key);
  34738. }
  34739. };
  34740. /**
  34741. * Specifies if two material defines are equal
  34742. * @param other - A material define instance to compare to
  34743. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34744. */
  34745. MaterialDefines.prototype.isEqual = function (other) {
  34746. if (this._keys.length !== other._keys.length) {
  34747. return false;
  34748. }
  34749. for (var index = 0; index < this._keys.length; index++) {
  34750. var prop = this._keys[index];
  34751. if (this[prop] !== other[prop]) {
  34752. return false;
  34753. }
  34754. }
  34755. return true;
  34756. };
  34757. /**
  34758. * Clones this instance's defines to another instance
  34759. * @param other - material defines to clone values to
  34760. */
  34761. MaterialDefines.prototype.cloneTo = function (other) {
  34762. if (this._keys.length !== other._keys.length) {
  34763. other._keys = this._keys.slice(0);
  34764. }
  34765. for (var index = 0; index < this._keys.length; index++) {
  34766. var prop = this._keys[index];
  34767. other[prop] = this[prop];
  34768. }
  34769. };
  34770. /**
  34771. * Resets the material define values
  34772. */
  34773. MaterialDefines.prototype.reset = function () {
  34774. for (var index = 0; index < this._keys.length; index++) {
  34775. var prop = this._keys[index];
  34776. var type = typeof this[prop];
  34777. switch (type) {
  34778. case "number":
  34779. this[prop] = 0;
  34780. break;
  34781. case "string":
  34782. this[prop] = "";
  34783. break;
  34784. default:
  34785. this[prop] = false;
  34786. break;
  34787. }
  34788. }
  34789. };
  34790. /**
  34791. * Converts the material define values to a string
  34792. * @returns - String of material define information
  34793. */
  34794. MaterialDefines.prototype.toString = function () {
  34795. var result = "";
  34796. for (var index = 0; index < this._keys.length; index++) {
  34797. var prop = this._keys[index];
  34798. var value = this[prop];
  34799. var type = typeof value;
  34800. switch (type) {
  34801. case "number":
  34802. case "string":
  34803. result += "#define " + prop + " " + value + "\n";
  34804. break;
  34805. default:
  34806. if (value) {
  34807. result += "#define " + prop + "\n";
  34808. }
  34809. break;
  34810. }
  34811. }
  34812. return result;
  34813. };
  34814. return MaterialDefines;
  34815. }());
  34816. BABYLON.MaterialDefines = MaterialDefines;
  34817. /**
  34818. * Base class for the main features of a material in Babylon.js
  34819. */
  34820. var Material = /** @class */ (function () {
  34821. /**
  34822. * Creates a material instance
  34823. * @param name defines the name of the material
  34824. * @param scene defines the scene to reference
  34825. * @param doNotAdd specifies if the material should be added to the scene
  34826. */
  34827. function Material(name, scene, doNotAdd) {
  34828. /**
  34829. * Specifies if the ready state should be checked on each call
  34830. */
  34831. this.checkReadyOnEveryCall = false;
  34832. /**
  34833. * Specifies if the ready state should be checked once
  34834. */
  34835. this.checkReadyOnlyOnce = false;
  34836. /**
  34837. * The state of the material
  34838. */
  34839. this.state = "";
  34840. /**
  34841. * The alpha value of the material
  34842. */
  34843. this._alpha = 1.0;
  34844. /**
  34845. * Specifies if back face culling is enabled
  34846. */
  34847. this._backFaceCulling = true;
  34848. /**
  34849. * Specifies if the material should be serialized
  34850. */
  34851. this.doNotSerialize = false;
  34852. /**
  34853. * Specifies if the effect should be stored on sub meshes
  34854. */
  34855. this.storeEffectOnSubMeshes = false;
  34856. /**
  34857. * An event triggered when the material is disposed
  34858. */
  34859. this.onDisposeObservable = new BABYLON.Observable();
  34860. /**
  34861. * An event triggered when the material is bound
  34862. */
  34863. this.onBindObservable = new BABYLON.Observable();
  34864. /**
  34865. * An event triggered when the material is unbound
  34866. */
  34867. this.onUnBindObservable = new BABYLON.Observable();
  34868. /**
  34869. * Stores the value of the alpha mode
  34870. */
  34871. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34872. /**
  34873. * Stores the state of the need depth pre-pass value
  34874. */
  34875. this._needDepthPrePass = false;
  34876. /**
  34877. * Specifies if depth writing should be disabled
  34878. */
  34879. this.disableDepthWrite = false;
  34880. /**
  34881. * Specifies if depth writing should be forced
  34882. */
  34883. this.forceDepthWrite = false;
  34884. /**
  34885. * Specifies if there should be a separate pass for culling
  34886. */
  34887. this.separateCullingPass = false;
  34888. /**
  34889. * Stores the state specifing if fog should be enabled
  34890. */
  34891. this._fogEnabled = true;
  34892. /**
  34893. * Stores the size of points
  34894. */
  34895. this.pointSize = 1.0;
  34896. /**
  34897. * Stores the z offset value
  34898. */
  34899. this.zOffset = 0;
  34900. /**
  34901. * Specifies if the material was previously ready
  34902. */
  34903. this._wasPreviouslyReady = false;
  34904. /**
  34905. * Stores the fill mode state
  34906. */
  34907. this._fillMode = Material.TriangleFillMode;
  34908. this.name = name;
  34909. this.id = name || BABYLON.Tools.RandomId();
  34910. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34911. if (this._scene.useRightHandedSystem) {
  34912. this.sideOrientation = Material.ClockWiseSideOrientation;
  34913. }
  34914. else {
  34915. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34916. }
  34917. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34918. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34919. if (!doNotAdd) {
  34920. this._scene.materials.push(this);
  34921. }
  34922. }
  34923. Object.defineProperty(Material, "TriangleFillMode", {
  34924. /**
  34925. * Returns the triangle fill mode
  34926. */
  34927. get: function () {
  34928. return Material._TriangleFillMode;
  34929. },
  34930. enumerable: true,
  34931. configurable: true
  34932. });
  34933. Object.defineProperty(Material, "WireFrameFillMode", {
  34934. /**
  34935. * Returns the wireframe mode
  34936. */
  34937. get: function () {
  34938. return Material._WireFrameFillMode;
  34939. },
  34940. enumerable: true,
  34941. configurable: true
  34942. });
  34943. Object.defineProperty(Material, "PointFillMode", {
  34944. /**
  34945. * Returns the point fill mode
  34946. */
  34947. get: function () {
  34948. return Material._PointFillMode;
  34949. },
  34950. enumerable: true,
  34951. configurable: true
  34952. });
  34953. Object.defineProperty(Material, "PointListDrawMode", {
  34954. /**
  34955. * Returns the point list draw mode
  34956. */
  34957. get: function () {
  34958. return Material._PointListDrawMode;
  34959. },
  34960. enumerable: true,
  34961. configurable: true
  34962. });
  34963. Object.defineProperty(Material, "LineListDrawMode", {
  34964. /**
  34965. * Returns the line list draw mode
  34966. */
  34967. get: function () {
  34968. return Material._LineListDrawMode;
  34969. },
  34970. enumerable: true,
  34971. configurable: true
  34972. });
  34973. Object.defineProperty(Material, "LineLoopDrawMode", {
  34974. /**
  34975. * Returns the line loop draw mode
  34976. */
  34977. get: function () {
  34978. return Material._LineLoopDrawMode;
  34979. },
  34980. enumerable: true,
  34981. configurable: true
  34982. });
  34983. Object.defineProperty(Material, "LineStripDrawMode", {
  34984. /**
  34985. * Returns the line strip draw mode
  34986. */
  34987. get: function () {
  34988. return Material._LineStripDrawMode;
  34989. },
  34990. enumerable: true,
  34991. configurable: true
  34992. });
  34993. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34994. /**
  34995. * Returns the triangle strip draw mode
  34996. */
  34997. get: function () {
  34998. return Material._TriangleStripDrawMode;
  34999. },
  35000. enumerable: true,
  35001. configurable: true
  35002. });
  35003. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35004. /**
  35005. * Returns the triangle fan draw mode
  35006. */
  35007. get: function () {
  35008. return Material._TriangleFanDrawMode;
  35009. },
  35010. enumerable: true,
  35011. configurable: true
  35012. });
  35013. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35014. /**
  35015. * Returns the clock-wise side orientation
  35016. */
  35017. get: function () {
  35018. return Material._ClockWiseSideOrientation;
  35019. },
  35020. enumerable: true,
  35021. configurable: true
  35022. });
  35023. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35024. /**
  35025. * Returns the counter clock-wise side orientation
  35026. */
  35027. get: function () {
  35028. return Material._CounterClockWiseSideOrientation;
  35029. },
  35030. enumerable: true,
  35031. configurable: true
  35032. });
  35033. Object.defineProperty(Material, "TextureDirtyFlag", {
  35034. /**
  35035. * Returns the dirty texture flag value
  35036. */
  35037. get: function () {
  35038. return Material._TextureDirtyFlag;
  35039. },
  35040. enumerable: true,
  35041. configurable: true
  35042. });
  35043. Object.defineProperty(Material, "LightDirtyFlag", {
  35044. /**
  35045. * Returns the dirty light flag value
  35046. */
  35047. get: function () {
  35048. return Material._LightDirtyFlag;
  35049. },
  35050. enumerable: true,
  35051. configurable: true
  35052. });
  35053. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35054. /**
  35055. * Returns the dirty fresnel flag value
  35056. */
  35057. get: function () {
  35058. return Material._FresnelDirtyFlag;
  35059. },
  35060. enumerable: true,
  35061. configurable: true
  35062. });
  35063. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35064. /**
  35065. * Returns the dirty attributes flag value
  35066. */
  35067. get: function () {
  35068. return Material._AttributesDirtyFlag;
  35069. },
  35070. enumerable: true,
  35071. configurable: true
  35072. });
  35073. Object.defineProperty(Material, "MiscDirtyFlag", {
  35074. /**
  35075. * Returns the dirty misc flag value
  35076. */
  35077. get: function () {
  35078. return Material._MiscDirtyFlag;
  35079. },
  35080. enumerable: true,
  35081. configurable: true
  35082. });
  35083. Object.defineProperty(Material.prototype, "alpha", {
  35084. /**
  35085. * Gets the alpha value of the material
  35086. */
  35087. get: function () {
  35088. return this._alpha;
  35089. },
  35090. /**
  35091. * Sets the alpha value of the material
  35092. */
  35093. set: function (value) {
  35094. if (this._alpha === value) {
  35095. return;
  35096. }
  35097. this._alpha = value;
  35098. this.markAsDirty(Material.MiscDirtyFlag);
  35099. },
  35100. enumerable: true,
  35101. configurable: true
  35102. });
  35103. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35104. /**
  35105. * Gets the back-face culling state
  35106. */
  35107. get: function () {
  35108. return this._backFaceCulling;
  35109. },
  35110. /**
  35111. * Sets the back-face culling state
  35112. */
  35113. set: function (value) {
  35114. if (this._backFaceCulling === value) {
  35115. return;
  35116. }
  35117. this._backFaceCulling = value;
  35118. this.markAsDirty(Material.TextureDirtyFlag);
  35119. },
  35120. enumerable: true,
  35121. configurable: true
  35122. });
  35123. Object.defineProperty(Material.prototype, "onDispose", {
  35124. /**
  35125. * Called during a dispose event
  35126. */
  35127. set: function (callback) {
  35128. if (this._onDisposeObserver) {
  35129. this.onDisposeObservable.remove(this._onDisposeObserver);
  35130. }
  35131. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35132. },
  35133. enumerable: true,
  35134. configurable: true
  35135. });
  35136. Object.defineProperty(Material.prototype, "onBind", {
  35137. /**
  35138. * Called during a bind event
  35139. */
  35140. set: function (callback) {
  35141. if (this._onBindObserver) {
  35142. this.onBindObservable.remove(this._onBindObserver);
  35143. }
  35144. this._onBindObserver = this.onBindObservable.add(callback);
  35145. },
  35146. enumerable: true,
  35147. configurable: true
  35148. });
  35149. Object.defineProperty(Material.prototype, "alphaMode", {
  35150. /**
  35151. * Gets the value of the alpha mode
  35152. */
  35153. get: function () {
  35154. return this._alphaMode;
  35155. },
  35156. /**
  35157. * Sets the value of the alpha mode.
  35158. *
  35159. * | Value | Type | Description |
  35160. * | --- | --- | --- |
  35161. * | 0 | ALPHA_DISABLE | |
  35162. * | 1 | ALPHA_ADD | |
  35163. * | 2 | ALPHA_COMBINE | |
  35164. * | 3 | ALPHA_SUBTRACT | |
  35165. * | 4 | ALPHA_MULTIPLY | |
  35166. * | 5 | ALPHA_MAXIMIZED | |
  35167. * | 6 | ALPHA_ONEONE | |
  35168. * | 7 | ALPHA_PREMULTIPLIED | |
  35169. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35170. * | 9 | ALPHA_INTERPOLATE | |
  35171. * | 10 | ALPHA_SCREENMODE | |
  35172. *
  35173. */
  35174. set: function (value) {
  35175. if (this._alphaMode === value) {
  35176. return;
  35177. }
  35178. this._alphaMode = value;
  35179. this.markAsDirty(Material.TextureDirtyFlag);
  35180. },
  35181. enumerable: true,
  35182. configurable: true
  35183. });
  35184. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35185. /**
  35186. * Gets the depth pre-pass value
  35187. */
  35188. get: function () {
  35189. return this._needDepthPrePass;
  35190. },
  35191. /**
  35192. * Sets the need depth pre-pass value
  35193. */
  35194. set: function (value) {
  35195. if (this._needDepthPrePass === value) {
  35196. return;
  35197. }
  35198. this._needDepthPrePass = value;
  35199. if (this._needDepthPrePass) {
  35200. this.checkReadyOnEveryCall = true;
  35201. }
  35202. },
  35203. enumerable: true,
  35204. configurable: true
  35205. });
  35206. Object.defineProperty(Material.prototype, "fogEnabled", {
  35207. /**
  35208. * Gets the value of the fog enabled state
  35209. */
  35210. get: function () {
  35211. return this._fogEnabled;
  35212. },
  35213. /**
  35214. * Sets the state for enabling fog
  35215. */
  35216. set: function (value) {
  35217. if (this._fogEnabled === value) {
  35218. return;
  35219. }
  35220. this._fogEnabled = value;
  35221. this.markAsDirty(Material.MiscDirtyFlag);
  35222. },
  35223. enumerable: true,
  35224. configurable: true
  35225. });
  35226. Object.defineProperty(Material.prototype, "wireframe", {
  35227. /**
  35228. * Gets a value specifying if wireframe mode is enabled
  35229. */
  35230. get: function () {
  35231. switch (this._fillMode) {
  35232. case Material.WireFrameFillMode:
  35233. case Material.LineListDrawMode:
  35234. case Material.LineLoopDrawMode:
  35235. case Material.LineStripDrawMode:
  35236. return true;
  35237. }
  35238. return this._scene.forceWireframe;
  35239. },
  35240. /**
  35241. * Sets the state of wireframe mode
  35242. */
  35243. set: function (value) {
  35244. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35245. },
  35246. enumerable: true,
  35247. configurable: true
  35248. });
  35249. Object.defineProperty(Material.prototype, "pointsCloud", {
  35250. /**
  35251. * Gets the value specifying if point clouds are enabled
  35252. */
  35253. get: function () {
  35254. switch (this._fillMode) {
  35255. case Material.PointFillMode:
  35256. case Material.PointListDrawMode:
  35257. return true;
  35258. }
  35259. return this._scene.forcePointsCloud;
  35260. },
  35261. /**
  35262. * Sets the state of point cloud mode
  35263. */
  35264. set: function (value) {
  35265. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35266. },
  35267. enumerable: true,
  35268. configurable: true
  35269. });
  35270. Object.defineProperty(Material.prototype, "fillMode", {
  35271. /**
  35272. * Gets the material fill mode
  35273. */
  35274. get: function () {
  35275. return this._fillMode;
  35276. },
  35277. /**
  35278. * Sets the material fill mode
  35279. */
  35280. set: function (value) {
  35281. if (this._fillMode === value) {
  35282. return;
  35283. }
  35284. this._fillMode = value;
  35285. this.markAsDirty(Material.MiscDirtyFlag);
  35286. },
  35287. enumerable: true,
  35288. configurable: true
  35289. });
  35290. /**
  35291. * Returns a string representation of the current material
  35292. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35293. * @returns a string with material information
  35294. */
  35295. Material.prototype.toString = function (fullDetails) {
  35296. var ret = "Name: " + this.name;
  35297. if (fullDetails) {
  35298. }
  35299. return ret;
  35300. };
  35301. /**
  35302. * Gets the class name of the material
  35303. * @returns a string with the class name of the material
  35304. */
  35305. Material.prototype.getClassName = function () {
  35306. return "Material";
  35307. };
  35308. Object.defineProperty(Material.prototype, "isFrozen", {
  35309. /**
  35310. * Specifies if updates for the material been locked
  35311. */
  35312. get: function () {
  35313. return this.checkReadyOnlyOnce;
  35314. },
  35315. enumerable: true,
  35316. configurable: true
  35317. });
  35318. /**
  35319. * Locks updates for the material
  35320. */
  35321. Material.prototype.freeze = function () {
  35322. this.checkReadyOnlyOnce = true;
  35323. };
  35324. /**
  35325. * Unlocks updates for the material
  35326. */
  35327. Material.prototype.unfreeze = function () {
  35328. this.checkReadyOnlyOnce = false;
  35329. };
  35330. /**
  35331. * Specifies if the material is ready to be used
  35332. * @param mesh defines the mesh to check
  35333. * @param useInstances specifies if instances should be used
  35334. * @returns a boolean indicating if the material is ready to be used
  35335. */
  35336. Material.prototype.isReady = function (mesh, useInstances) {
  35337. return true;
  35338. };
  35339. /**
  35340. * Specifies that the submesh is ready to be used
  35341. * @param mesh defines the mesh to check
  35342. * @param subMesh defines which submesh to check
  35343. * @param useInstances specifies that instances should be used
  35344. * @returns a boolean indicating that the submesh is ready or not
  35345. */
  35346. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35347. return false;
  35348. };
  35349. /**
  35350. * Returns the material effect
  35351. * @returns the effect associated with the material
  35352. */
  35353. Material.prototype.getEffect = function () {
  35354. return this._effect;
  35355. };
  35356. /**
  35357. * Returns the current scene
  35358. * @returns a Scene
  35359. */
  35360. Material.prototype.getScene = function () {
  35361. return this._scene;
  35362. };
  35363. /**
  35364. * Specifies if the material will require alpha blending
  35365. * @returns a boolean specifying if alpha blending is needed
  35366. */
  35367. Material.prototype.needAlphaBlending = function () {
  35368. return (this.alpha < 1.0);
  35369. };
  35370. /**
  35371. * Specifies if the mesh will require alpha blending
  35372. * @param mesh defines the mesh to check
  35373. * @returns a boolean specifying if alpha blending is needed for the mesh
  35374. */
  35375. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35376. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35377. };
  35378. /**
  35379. * Specifies if this material should be rendered in alpha test mode
  35380. * @returns a boolean specifying if an alpha test is needed.
  35381. */
  35382. Material.prototype.needAlphaTesting = function () {
  35383. return false;
  35384. };
  35385. /**
  35386. * Gets the texture used for the alpha test
  35387. * @returns the texture to use for alpha testing
  35388. */
  35389. Material.prototype.getAlphaTestTexture = function () {
  35390. return null;
  35391. };
  35392. /**
  35393. * Marks the material to indicate that it needs to be re-calculated
  35394. */
  35395. Material.prototype.markDirty = function () {
  35396. this._wasPreviouslyReady = false;
  35397. };
  35398. /** @hidden */
  35399. Material.prototype._preBind = function (effect, overrideOrientation) {
  35400. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35401. var engine = this._scene.getEngine();
  35402. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35403. var reverse = orientation === Material.ClockWiseSideOrientation;
  35404. engine.enableEffect(effect ? effect : this._effect);
  35405. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35406. return reverse;
  35407. };
  35408. /**
  35409. * Binds the material to the mesh
  35410. * @param world defines the world transformation matrix
  35411. * @param mesh defines the mesh to bind the material to
  35412. */
  35413. Material.prototype.bind = function (world, mesh) {
  35414. };
  35415. /**
  35416. * Binds the submesh to the material
  35417. * @param world defines the world transformation matrix
  35418. * @param mesh defines the mesh containing the submesh
  35419. * @param subMesh defines the submesh to bind the material to
  35420. */
  35421. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35422. };
  35423. /**
  35424. * Binds the world matrix to the material
  35425. * @param world defines the world transformation matrix
  35426. */
  35427. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35428. };
  35429. /**
  35430. * Binds the scene's uniform buffer to the effect.
  35431. * @param effect defines the effect to bind to the scene uniform buffer
  35432. * @param sceneUbo defines the uniform buffer storing scene data
  35433. */
  35434. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35435. sceneUbo.bindToEffect(effect, "Scene");
  35436. };
  35437. /**
  35438. * Binds the view matrix to the effect
  35439. * @param effect defines the effect to bind the view matrix to
  35440. */
  35441. Material.prototype.bindView = function (effect) {
  35442. if (!this._useUBO) {
  35443. effect.setMatrix("view", this.getScene().getViewMatrix());
  35444. }
  35445. else {
  35446. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35447. }
  35448. };
  35449. /**
  35450. * Binds the view projection matrix to the effect
  35451. * @param effect defines the effect to bind the view projection matrix to
  35452. */
  35453. Material.prototype.bindViewProjection = function (effect) {
  35454. if (!this._useUBO) {
  35455. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35456. }
  35457. else {
  35458. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35459. }
  35460. };
  35461. /**
  35462. * Specifies if material alpha testing should be turned on for the mesh
  35463. * @param mesh defines the mesh to check
  35464. */
  35465. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35466. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35467. };
  35468. /**
  35469. * Processes to execute after binding the material to a mesh
  35470. * @param mesh defines the rendered mesh
  35471. */
  35472. Material.prototype._afterBind = function (mesh) {
  35473. this._scene._cachedMaterial = this;
  35474. if (mesh) {
  35475. this._scene._cachedVisibility = mesh.visibility;
  35476. }
  35477. else {
  35478. this._scene._cachedVisibility = 1;
  35479. }
  35480. if (mesh) {
  35481. this.onBindObservable.notifyObservers(mesh);
  35482. }
  35483. if (this.disableDepthWrite) {
  35484. var engine = this._scene.getEngine();
  35485. this._cachedDepthWriteState = engine.getDepthWrite();
  35486. engine.setDepthWrite(false);
  35487. }
  35488. };
  35489. /**
  35490. * Unbinds the material from the mesh
  35491. */
  35492. Material.prototype.unbind = function () {
  35493. this.onUnBindObservable.notifyObservers(this);
  35494. if (this.disableDepthWrite) {
  35495. var engine = this._scene.getEngine();
  35496. engine.setDepthWrite(this._cachedDepthWriteState);
  35497. }
  35498. };
  35499. /**
  35500. * Gets the active textures from the material
  35501. * @returns an array of textures
  35502. */
  35503. Material.prototype.getActiveTextures = function () {
  35504. return [];
  35505. };
  35506. /**
  35507. * Specifies if the material uses a texture
  35508. * @param texture defines the texture to check against the material
  35509. * @returns a boolean specifying if the material uses the texture
  35510. */
  35511. Material.prototype.hasTexture = function (texture) {
  35512. return false;
  35513. };
  35514. /**
  35515. * Makes a duplicate of the material, and gives it a new name
  35516. * @param name defines the new name for the duplicated material
  35517. * @returns the cloned material
  35518. */
  35519. Material.prototype.clone = function (name) {
  35520. return null;
  35521. };
  35522. /**
  35523. * Gets the meshes bound to the material
  35524. * @returns an array of meshes bound to the material
  35525. */
  35526. Material.prototype.getBindedMeshes = function () {
  35527. var result = new Array();
  35528. for (var index = 0; index < this._scene.meshes.length; index++) {
  35529. var mesh = this._scene.meshes[index];
  35530. if (mesh.material === this) {
  35531. result.push(mesh);
  35532. }
  35533. }
  35534. return result;
  35535. };
  35536. /**
  35537. * Force shader compilation
  35538. * @param mesh defines the mesh associated with this material
  35539. * @param onCompiled defines a function to execute once the material is compiled
  35540. * @param options defines the options to configure the compilation
  35541. */
  35542. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35543. var _this = this;
  35544. var localOptions = __assign({ clipPlane: false }, options);
  35545. var subMesh = new BABYLON.BaseSubMesh();
  35546. var scene = this.getScene();
  35547. var checkReady = function () {
  35548. if (!_this._scene || !_this._scene.getEngine()) {
  35549. return;
  35550. }
  35551. if (subMesh._materialDefines) {
  35552. subMesh._materialDefines._renderId = -1;
  35553. }
  35554. var clipPlaneState = scene.clipPlane;
  35555. if (localOptions.clipPlane) {
  35556. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35557. }
  35558. if (_this.storeEffectOnSubMeshes) {
  35559. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35560. if (onCompiled) {
  35561. onCompiled(_this);
  35562. }
  35563. }
  35564. else {
  35565. setTimeout(checkReady, 16);
  35566. }
  35567. }
  35568. else {
  35569. if (_this.isReady(mesh)) {
  35570. if (onCompiled) {
  35571. onCompiled(_this);
  35572. }
  35573. }
  35574. else {
  35575. setTimeout(checkReady, 16);
  35576. }
  35577. }
  35578. if (localOptions.clipPlane) {
  35579. scene.clipPlane = clipPlaneState;
  35580. }
  35581. };
  35582. checkReady();
  35583. };
  35584. /**
  35585. * Force shader compilation
  35586. * @param mesh defines the mesh that will use this material
  35587. * @param options defines additional options for compiling the shaders
  35588. * @returns a promise that resolves when the compilation completes
  35589. */
  35590. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35591. var _this = this;
  35592. return new Promise(function (resolve) {
  35593. _this.forceCompilation(mesh, function () {
  35594. resolve();
  35595. }, options);
  35596. });
  35597. };
  35598. /**
  35599. * Marks a define in the material to indicate that it needs to be re-computed
  35600. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35601. */
  35602. Material.prototype.markAsDirty = function (flag) {
  35603. if (flag & Material.TextureDirtyFlag) {
  35604. this._markAllSubMeshesAsTexturesDirty();
  35605. }
  35606. if (flag & Material.LightDirtyFlag) {
  35607. this._markAllSubMeshesAsLightsDirty();
  35608. }
  35609. if (flag & Material.FresnelDirtyFlag) {
  35610. this._markAllSubMeshesAsFresnelDirty();
  35611. }
  35612. if (flag & Material.AttributesDirtyFlag) {
  35613. this._markAllSubMeshesAsAttributesDirty();
  35614. }
  35615. if (flag & Material.MiscDirtyFlag) {
  35616. this._markAllSubMeshesAsMiscDirty();
  35617. }
  35618. this.getScene().resetCachedMaterial();
  35619. };
  35620. /**
  35621. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35622. * @param func defines a function which checks material defines against the submeshes
  35623. */
  35624. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35625. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35626. var mesh = _a[_i];
  35627. if (!mesh.subMeshes) {
  35628. continue;
  35629. }
  35630. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35631. var subMesh = _c[_b];
  35632. if (subMesh.getMaterial() !== this) {
  35633. continue;
  35634. }
  35635. if (!subMesh._materialDefines) {
  35636. continue;
  35637. }
  35638. func(subMesh._materialDefines);
  35639. }
  35640. }
  35641. };
  35642. /**
  35643. * Indicates that image processing needs to be re-calculated for all submeshes
  35644. */
  35645. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35646. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35647. };
  35648. /**
  35649. * Indicates that textures need to be re-calculated for all submeshes
  35650. */
  35651. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35652. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35653. };
  35654. /**
  35655. * Indicates that fresnel needs to be re-calculated for all submeshes
  35656. */
  35657. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35658. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35659. };
  35660. /**
  35661. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35662. */
  35663. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35664. this._markAllSubMeshesAsDirty(function (defines) {
  35665. defines.markAsFresnelDirty();
  35666. defines.markAsMiscDirty();
  35667. });
  35668. };
  35669. /**
  35670. * Indicates that lights need to be re-calculated for all submeshes
  35671. */
  35672. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35673. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35674. };
  35675. /**
  35676. * Indicates that attributes need to be re-calculated for all submeshes
  35677. */
  35678. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35679. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35680. };
  35681. /**
  35682. * Indicates that misc needs to be re-calculated for all submeshes
  35683. */
  35684. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35685. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35686. };
  35687. /**
  35688. * Indicates that textures and misc need to be re-calculated for all submeshes
  35689. */
  35690. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35691. this._markAllSubMeshesAsDirty(function (defines) {
  35692. defines.markAsTexturesDirty();
  35693. defines.markAsMiscDirty();
  35694. });
  35695. };
  35696. /**
  35697. * Disposes the material
  35698. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35699. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35700. */
  35701. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35702. // Animations
  35703. this.getScene().stopAnimation(this);
  35704. this.getScene().freeProcessedMaterials();
  35705. // Remove from scene
  35706. var index = this._scene.materials.indexOf(this);
  35707. if (index >= 0) {
  35708. this._scene.materials.splice(index, 1);
  35709. }
  35710. // Remove from meshes
  35711. for (index = 0; index < this._scene.meshes.length; index++) {
  35712. var mesh = this._scene.meshes[index];
  35713. if (mesh.material === this) {
  35714. mesh.material = null;
  35715. if (mesh.geometry) {
  35716. var geometry = (mesh.geometry);
  35717. if (this.storeEffectOnSubMeshes) {
  35718. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35719. var subMesh = _a[_i];
  35720. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35721. if (forceDisposeEffect && subMesh._materialEffect) {
  35722. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35723. }
  35724. }
  35725. }
  35726. else {
  35727. geometry._releaseVertexArrayObject(this._effect);
  35728. }
  35729. }
  35730. }
  35731. }
  35732. this._uniformBuffer.dispose();
  35733. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35734. if (forceDisposeEffect && this._effect) {
  35735. if (!this.storeEffectOnSubMeshes) {
  35736. this._scene.getEngine()._releaseEffect(this._effect);
  35737. }
  35738. this._effect = null;
  35739. }
  35740. // Callback
  35741. this.onDisposeObservable.notifyObservers(this);
  35742. this.onDisposeObservable.clear();
  35743. this.onBindObservable.clear();
  35744. this.onUnBindObservable.clear();
  35745. };
  35746. /**
  35747. * Serializes this material
  35748. * @returns the serialized material object
  35749. */
  35750. Material.prototype.serialize = function () {
  35751. return BABYLON.SerializationHelper.Serialize(this);
  35752. };
  35753. /**
  35754. * Creates a MultiMaterial from parsed MultiMaterial data.
  35755. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35756. * @param scene defines the hosting scene
  35757. * @returns a new MultiMaterial
  35758. */
  35759. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35760. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35761. multiMaterial.id = parsedMultiMaterial.id;
  35762. if (BABYLON.Tags) {
  35763. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35764. }
  35765. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35766. var subMatId = parsedMultiMaterial.materials[matIndex];
  35767. if (subMatId) {
  35768. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35769. }
  35770. else {
  35771. multiMaterial.subMaterials.push(null);
  35772. }
  35773. }
  35774. return multiMaterial;
  35775. };
  35776. /**
  35777. * Creates a material from parsed material data
  35778. * @param parsedMaterial defines parsed material data
  35779. * @param scene defines the hosting scene
  35780. * @param rootUrl defines the root URL to use to load textures
  35781. * @returns a new material
  35782. */
  35783. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35784. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35785. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35786. }
  35787. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35788. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35789. if (!BABYLON.LegacyPBRMaterial) {
  35790. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35791. return;
  35792. }
  35793. }
  35794. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35795. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35796. };
  35797. // Triangle views
  35798. Material._TriangleFillMode = 0;
  35799. Material._WireFrameFillMode = 1;
  35800. Material._PointFillMode = 2;
  35801. // Draw modes
  35802. Material._PointListDrawMode = 3;
  35803. Material._LineListDrawMode = 4;
  35804. Material._LineLoopDrawMode = 5;
  35805. Material._LineStripDrawMode = 6;
  35806. Material._TriangleStripDrawMode = 7;
  35807. Material._TriangleFanDrawMode = 8;
  35808. /**
  35809. * Stores the clock-wise side orientation
  35810. */
  35811. Material._ClockWiseSideOrientation = 0;
  35812. /**
  35813. * Stores the counter clock-wise side orientation
  35814. */
  35815. Material._CounterClockWiseSideOrientation = 1;
  35816. /**
  35817. * The dirty texture flag value
  35818. */
  35819. Material._TextureDirtyFlag = 1;
  35820. /**
  35821. * The dirty light flag value
  35822. */
  35823. Material._LightDirtyFlag = 2;
  35824. /**
  35825. * The dirty fresnel flag value
  35826. */
  35827. Material._FresnelDirtyFlag = 4;
  35828. /**
  35829. * The dirty attribute flag value
  35830. */
  35831. Material._AttributesDirtyFlag = 8;
  35832. /**
  35833. * The dirty misc flag value
  35834. */
  35835. Material._MiscDirtyFlag = 16;
  35836. __decorate([
  35837. BABYLON.serialize()
  35838. ], Material.prototype, "id", void 0);
  35839. __decorate([
  35840. BABYLON.serialize()
  35841. ], Material.prototype, "name", void 0);
  35842. __decorate([
  35843. BABYLON.serialize()
  35844. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35845. __decorate([
  35846. BABYLON.serialize()
  35847. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35848. __decorate([
  35849. BABYLON.serialize()
  35850. ], Material.prototype, "state", void 0);
  35851. __decorate([
  35852. BABYLON.serialize("alpha")
  35853. ], Material.prototype, "_alpha", void 0);
  35854. __decorate([
  35855. BABYLON.serialize("backFaceCulling")
  35856. ], Material.prototype, "_backFaceCulling", void 0);
  35857. __decorate([
  35858. BABYLON.serialize()
  35859. ], Material.prototype, "sideOrientation", void 0);
  35860. __decorate([
  35861. BABYLON.serialize("alphaMode")
  35862. ], Material.prototype, "_alphaMode", void 0);
  35863. __decorate([
  35864. BABYLON.serialize()
  35865. ], Material.prototype, "_needDepthPrePass", void 0);
  35866. __decorate([
  35867. BABYLON.serialize()
  35868. ], Material.prototype, "disableDepthWrite", void 0);
  35869. __decorate([
  35870. BABYLON.serialize()
  35871. ], Material.prototype, "forceDepthWrite", void 0);
  35872. __decorate([
  35873. BABYLON.serialize()
  35874. ], Material.prototype, "separateCullingPass", void 0);
  35875. __decorate([
  35876. BABYLON.serialize("fogEnabled")
  35877. ], Material.prototype, "_fogEnabled", void 0);
  35878. __decorate([
  35879. BABYLON.serialize()
  35880. ], Material.prototype, "pointSize", void 0);
  35881. __decorate([
  35882. BABYLON.serialize()
  35883. ], Material.prototype, "zOffset", void 0);
  35884. __decorate([
  35885. BABYLON.serialize()
  35886. ], Material.prototype, "wireframe", null);
  35887. __decorate([
  35888. BABYLON.serialize()
  35889. ], Material.prototype, "pointsCloud", null);
  35890. __decorate([
  35891. BABYLON.serialize()
  35892. ], Material.prototype, "fillMode", null);
  35893. return Material;
  35894. }());
  35895. BABYLON.Material = Material;
  35896. })(BABYLON || (BABYLON = {}));
  35897. //# sourceMappingURL=babylon.material.js.map
  35898. var BABYLON;
  35899. (function (BABYLON) {
  35900. var UniformBuffer = /** @class */ (function () {
  35901. /**
  35902. * Uniform buffer objects.
  35903. *
  35904. * Handles blocks of uniform on the GPU.
  35905. *
  35906. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35907. *
  35908. * For more information, please refer to :
  35909. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35910. */
  35911. function UniformBuffer(engine, data, dynamic) {
  35912. this._engine = engine;
  35913. this._noUBO = !engine.supportsUniformBuffers;
  35914. this._dynamic = dynamic;
  35915. this._data = data || [];
  35916. this._uniformLocations = {};
  35917. this._uniformSizes = {};
  35918. this._uniformLocationPointer = 0;
  35919. this._needSync = false;
  35920. if (this._noUBO) {
  35921. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35922. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35923. this.updateFloat = this._updateFloatForEffect;
  35924. this.updateFloat2 = this._updateFloat2ForEffect;
  35925. this.updateFloat3 = this._updateFloat3ForEffect;
  35926. this.updateFloat4 = this._updateFloat4ForEffect;
  35927. this.updateMatrix = this._updateMatrixForEffect;
  35928. this.updateVector3 = this._updateVector3ForEffect;
  35929. this.updateVector4 = this._updateVector4ForEffect;
  35930. this.updateColor3 = this._updateColor3ForEffect;
  35931. this.updateColor4 = this._updateColor4ForEffect;
  35932. }
  35933. else {
  35934. this._engine._uniformBuffers.push(this);
  35935. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35936. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35937. this.updateFloat = this._updateFloatForUniform;
  35938. this.updateFloat2 = this._updateFloat2ForUniform;
  35939. this.updateFloat3 = this._updateFloat3ForUniform;
  35940. this.updateFloat4 = this._updateFloat4ForUniform;
  35941. this.updateMatrix = this._updateMatrixForUniform;
  35942. this.updateVector3 = this._updateVector3ForUniform;
  35943. this.updateVector4 = this._updateVector4ForUniform;
  35944. this.updateColor3 = this._updateColor3ForUniform;
  35945. this.updateColor4 = this._updateColor4ForUniform;
  35946. }
  35947. }
  35948. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35949. // Properties
  35950. /**
  35951. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35952. * or just falling back on setUniformXXX calls.
  35953. */
  35954. get: function () {
  35955. return !this._noUBO;
  35956. },
  35957. enumerable: true,
  35958. configurable: true
  35959. });
  35960. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35961. /**
  35962. * Indicates if the WebGL underlying uniform buffer is in sync
  35963. * with the javascript cache data.
  35964. */
  35965. get: function () {
  35966. return !this._needSync;
  35967. },
  35968. enumerable: true,
  35969. configurable: true
  35970. });
  35971. /**
  35972. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35973. * Also, a dynamic UniformBuffer will disable cache verification and always
  35974. * update the underlying WebGL uniform buffer to the GPU.
  35975. */
  35976. UniformBuffer.prototype.isDynamic = function () {
  35977. return this._dynamic !== undefined;
  35978. };
  35979. /**
  35980. * The data cache on JS side.
  35981. */
  35982. UniformBuffer.prototype.getData = function () {
  35983. return this._bufferData;
  35984. };
  35985. /**
  35986. * The underlying WebGL Uniform buffer.
  35987. */
  35988. UniformBuffer.prototype.getBuffer = function () {
  35989. return this._buffer;
  35990. };
  35991. /**
  35992. * std140 layout specifies how to align data within an UBO structure.
  35993. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35994. * for specs.
  35995. */
  35996. UniformBuffer.prototype._fillAlignment = function (size) {
  35997. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35998. // and 4x4 matrices
  35999. // TODO : change if other types are used
  36000. var alignment;
  36001. if (size <= 2) {
  36002. alignment = size;
  36003. }
  36004. else {
  36005. alignment = 4;
  36006. }
  36007. if ((this._uniformLocationPointer % alignment) !== 0) {
  36008. var oldPointer = this._uniformLocationPointer;
  36009. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36010. var diff = this._uniformLocationPointer - oldPointer;
  36011. for (var i = 0; i < diff; i++) {
  36012. this._data.push(0);
  36013. }
  36014. }
  36015. };
  36016. /**
  36017. * Adds an uniform in the buffer.
  36018. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36019. * for the layout to be correct !
  36020. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36021. * @param {number|number[]} size Data size, or data directly.
  36022. */
  36023. UniformBuffer.prototype.addUniform = function (name, size) {
  36024. if (this._noUBO) {
  36025. return;
  36026. }
  36027. if (this._uniformLocations[name] !== undefined) {
  36028. // Already existing uniform
  36029. return;
  36030. }
  36031. // This function must be called in the order of the shader layout !
  36032. // size can be the size of the uniform, or data directly
  36033. var data;
  36034. if (size instanceof Array) {
  36035. data = size;
  36036. size = data.length;
  36037. }
  36038. else {
  36039. size = size;
  36040. data = [];
  36041. // Fill with zeros
  36042. for (var i = 0; i < size; i++) {
  36043. data.push(0);
  36044. }
  36045. }
  36046. this._fillAlignment(size);
  36047. this._uniformSizes[name] = size;
  36048. this._uniformLocations[name] = this._uniformLocationPointer;
  36049. this._uniformLocationPointer += size;
  36050. for (var i = 0; i < size; i++) {
  36051. this._data.push(data[i]);
  36052. }
  36053. this._needSync = true;
  36054. };
  36055. /**
  36056. * Wrapper for addUniform.
  36057. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36058. * @param {Matrix} mat A 4x4 matrix.
  36059. */
  36060. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36061. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36062. };
  36063. /**
  36064. * Wrapper for addUniform.
  36065. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36066. * @param {number} x
  36067. * @param {number} y
  36068. */
  36069. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36070. var temp = [x, y];
  36071. this.addUniform(name, temp);
  36072. };
  36073. /**
  36074. * Wrapper for addUniform.
  36075. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36076. * @param {number} x
  36077. * @param {number} y
  36078. * @param {number} z
  36079. */
  36080. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36081. var temp = [x, y, z];
  36082. this.addUniform(name, temp);
  36083. };
  36084. /**
  36085. * Wrapper for addUniform.
  36086. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36087. * @param {Color3} color
  36088. */
  36089. UniformBuffer.prototype.addColor3 = function (name, color) {
  36090. var temp = new Array();
  36091. color.toArray(temp);
  36092. this.addUniform(name, temp);
  36093. };
  36094. /**
  36095. * Wrapper for addUniform.
  36096. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36097. * @param {Color3} color
  36098. * @param {number} alpha
  36099. */
  36100. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36101. var temp = new Array();
  36102. color.toArray(temp);
  36103. temp.push(alpha);
  36104. this.addUniform(name, temp);
  36105. };
  36106. /**
  36107. * Wrapper for addUniform.
  36108. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36109. * @param {Vector3} vector
  36110. */
  36111. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36112. var temp = new Array();
  36113. vector.toArray(temp);
  36114. this.addUniform(name, temp);
  36115. };
  36116. /**
  36117. * Wrapper for addUniform.
  36118. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36119. */
  36120. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36121. this.addUniform(name, 12);
  36122. };
  36123. /**
  36124. * Wrapper for addUniform.
  36125. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36126. */
  36127. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36128. this.addUniform(name, 8);
  36129. };
  36130. /**
  36131. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36132. */
  36133. UniformBuffer.prototype.create = function () {
  36134. if (this._noUBO) {
  36135. return;
  36136. }
  36137. if (this._buffer) {
  36138. return; // nothing to do
  36139. }
  36140. // See spec, alignment must be filled as a vec4
  36141. this._fillAlignment(4);
  36142. this._bufferData = new Float32Array(this._data);
  36143. this._rebuild();
  36144. this._needSync = true;
  36145. };
  36146. UniformBuffer.prototype._rebuild = function () {
  36147. if (this._noUBO) {
  36148. return;
  36149. }
  36150. if (this._dynamic) {
  36151. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36152. }
  36153. else {
  36154. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36155. }
  36156. };
  36157. /**
  36158. * Updates the WebGL Uniform Buffer on the GPU.
  36159. * If the `dynamic` flag is set to true, no cache comparison is done.
  36160. * Otherwise, the buffer will be updated only if the cache differs.
  36161. */
  36162. UniformBuffer.prototype.update = function () {
  36163. if (!this._buffer) {
  36164. this.create();
  36165. return;
  36166. }
  36167. if (!this._dynamic && !this._needSync) {
  36168. return;
  36169. }
  36170. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36171. this._needSync = false;
  36172. };
  36173. /**
  36174. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36175. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36176. * @param {number[]|Float32Array} data Flattened data
  36177. * @param {number} size Size of the data.
  36178. */
  36179. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36180. var location = this._uniformLocations[uniformName];
  36181. if (location === undefined) {
  36182. if (this._buffer) {
  36183. // Cannot add an uniform if the buffer is already created
  36184. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36185. return;
  36186. }
  36187. this.addUniform(uniformName, size);
  36188. location = this._uniformLocations[uniformName];
  36189. }
  36190. if (!this._buffer) {
  36191. this.create();
  36192. }
  36193. if (!this._dynamic) {
  36194. // Cache for static uniform buffers
  36195. var changed = false;
  36196. for (var i = 0; i < size; i++) {
  36197. if (this._bufferData[location + i] !== data[i]) {
  36198. changed = true;
  36199. this._bufferData[location + i] = data[i];
  36200. }
  36201. }
  36202. this._needSync = this._needSync || changed;
  36203. }
  36204. else {
  36205. // No cache for dynamic
  36206. for (var i = 0; i < size; i++) {
  36207. this._bufferData[location + i] = data[i];
  36208. }
  36209. }
  36210. };
  36211. // Update methods
  36212. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36213. // To match std140, matrix must be realigned
  36214. for (var i = 0; i < 3; i++) {
  36215. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36216. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36217. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36218. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36219. }
  36220. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36221. };
  36222. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36223. this._currentEffect.setMatrix3x3(name, matrix);
  36224. };
  36225. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36226. this._currentEffect.setMatrix2x2(name, matrix);
  36227. };
  36228. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36229. // To match std140, matrix must be realigned
  36230. for (var i = 0; i < 2; i++) {
  36231. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36232. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36233. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36234. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36235. }
  36236. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36237. };
  36238. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36239. this._currentEffect.setFloat(name, x);
  36240. };
  36241. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36242. UniformBuffer._tempBuffer[0] = x;
  36243. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36244. };
  36245. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36246. if (suffix === void 0) { suffix = ""; }
  36247. this._currentEffect.setFloat2(name + suffix, x, y);
  36248. };
  36249. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36250. if (suffix === void 0) { suffix = ""; }
  36251. UniformBuffer._tempBuffer[0] = x;
  36252. UniformBuffer._tempBuffer[1] = y;
  36253. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36254. };
  36255. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36256. if (suffix === void 0) { suffix = ""; }
  36257. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36258. };
  36259. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36260. if (suffix === void 0) { suffix = ""; }
  36261. UniformBuffer._tempBuffer[0] = x;
  36262. UniformBuffer._tempBuffer[1] = y;
  36263. UniformBuffer._tempBuffer[2] = z;
  36264. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36265. };
  36266. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36267. if (suffix === void 0) { suffix = ""; }
  36268. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36269. };
  36270. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36271. if (suffix === void 0) { suffix = ""; }
  36272. UniformBuffer._tempBuffer[0] = x;
  36273. UniformBuffer._tempBuffer[1] = y;
  36274. UniformBuffer._tempBuffer[2] = z;
  36275. UniformBuffer._tempBuffer[3] = w;
  36276. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36277. };
  36278. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36279. this._currentEffect.setMatrix(name, mat);
  36280. };
  36281. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36282. this.updateUniform(name, mat.toArray(), 16);
  36283. };
  36284. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36285. this._currentEffect.setVector3(name, vector);
  36286. };
  36287. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36288. vector.toArray(UniformBuffer._tempBuffer);
  36289. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36290. };
  36291. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36292. this._currentEffect.setVector4(name, vector);
  36293. };
  36294. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36295. vector.toArray(UniformBuffer._tempBuffer);
  36296. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36297. };
  36298. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36299. if (suffix === void 0) { suffix = ""; }
  36300. this._currentEffect.setColor3(name + suffix, color);
  36301. };
  36302. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36303. if (suffix === void 0) { suffix = ""; }
  36304. color.toArray(UniformBuffer._tempBuffer);
  36305. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36306. };
  36307. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36308. if (suffix === void 0) { suffix = ""; }
  36309. this._currentEffect.setColor4(name + suffix, color, alpha);
  36310. };
  36311. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36312. if (suffix === void 0) { suffix = ""; }
  36313. color.toArray(UniformBuffer._tempBuffer);
  36314. UniformBuffer._tempBuffer[3] = alpha;
  36315. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36316. };
  36317. /**
  36318. * Sets a sampler uniform on the effect.
  36319. * @param {string} name Name of the sampler.
  36320. * @param {Texture} texture
  36321. */
  36322. UniformBuffer.prototype.setTexture = function (name, texture) {
  36323. this._currentEffect.setTexture(name, texture);
  36324. };
  36325. /**
  36326. * Directly updates the value of the uniform in the cache AND on the GPU.
  36327. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36328. * @param {number[]|Float32Array} data Flattened data
  36329. */
  36330. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36331. this.updateUniform(uniformName, data, data.length);
  36332. this.update();
  36333. };
  36334. /**
  36335. * Binds this uniform buffer to an effect.
  36336. * @param {Effect} effect
  36337. * @param {string} name Name of the uniform block in the shader.
  36338. */
  36339. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36340. this._currentEffect = effect;
  36341. if (this._noUBO || !this._buffer) {
  36342. return;
  36343. }
  36344. effect.bindUniformBuffer(this._buffer, name);
  36345. };
  36346. /**
  36347. * Disposes the uniform buffer.
  36348. */
  36349. UniformBuffer.prototype.dispose = function () {
  36350. if (this._noUBO) {
  36351. return;
  36352. }
  36353. var index = this._engine._uniformBuffers.indexOf(this);
  36354. if (index !== -1) {
  36355. this._engine._uniformBuffers.splice(index, 1);
  36356. }
  36357. if (!this._buffer) {
  36358. return;
  36359. }
  36360. if (this._engine._releaseBuffer(this._buffer)) {
  36361. this._buffer = null;
  36362. }
  36363. };
  36364. // Pool for avoiding memory leaks
  36365. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36366. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36367. return UniformBuffer;
  36368. }());
  36369. BABYLON.UniformBuffer = UniformBuffer;
  36370. })(BABYLON || (BABYLON = {}));
  36371. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36372. var BABYLON;
  36373. (function (BABYLON) {
  36374. /**
  36375. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36376. */
  36377. var VertexData = /** @class */ (function () {
  36378. function VertexData() {
  36379. }
  36380. /**
  36381. * Uses the passed data array to set the set the values for the specified kind of data
  36382. * @param data a linear array of floating numbers
  36383. * @param kind the type of data that is being set, eg positions, colors etc
  36384. */
  36385. VertexData.prototype.set = function (data, kind) {
  36386. switch (kind) {
  36387. case BABYLON.VertexBuffer.PositionKind:
  36388. this.positions = data;
  36389. break;
  36390. case BABYLON.VertexBuffer.NormalKind:
  36391. this.normals = data;
  36392. break;
  36393. case BABYLON.VertexBuffer.TangentKind:
  36394. this.tangents = data;
  36395. break;
  36396. case BABYLON.VertexBuffer.UVKind:
  36397. this.uvs = data;
  36398. break;
  36399. case BABYLON.VertexBuffer.UV2Kind:
  36400. this.uvs2 = data;
  36401. break;
  36402. case BABYLON.VertexBuffer.UV3Kind:
  36403. this.uvs3 = data;
  36404. break;
  36405. case BABYLON.VertexBuffer.UV4Kind:
  36406. this.uvs4 = data;
  36407. break;
  36408. case BABYLON.VertexBuffer.UV5Kind:
  36409. this.uvs5 = data;
  36410. break;
  36411. case BABYLON.VertexBuffer.UV6Kind:
  36412. this.uvs6 = data;
  36413. break;
  36414. case BABYLON.VertexBuffer.ColorKind:
  36415. this.colors = data;
  36416. break;
  36417. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36418. this.matricesIndices = data;
  36419. break;
  36420. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36421. this.matricesWeights = data;
  36422. break;
  36423. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36424. this.matricesIndicesExtra = data;
  36425. break;
  36426. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36427. this.matricesWeightsExtra = data;
  36428. break;
  36429. }
  36430. };
  36431. /**
  36432. * Associates the vertexData to the passed Mesh.
  36433. * Sets it as updatable or not (default `false`)
  36434. * @param mesh the mesh the vertexData is applied to
  36435. * @param updatable when used and having the value true allows new data to update the vertexData
  36436. * @returns the VertexData
  36437. */
  36438. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36439. this._applyTo(mesh, updatable);
  36440. return this;
  36441. };
  36442. /**
  36443. * Associates the vertexData to the passed Geometry.
  36444. * Sets it as updatable or not (default `false`)
  36445. * @param geometry the geometry the vertexData is applied to
  36446. * @param updatable when used and having the value true allows new data to update the vertexData
  36447. * @returns VertexData
  36448. */
  36449. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36450. this._applyTo(geometry, updatable);
  36451. return this;
  36452. };
  36453. /**
  36454. * Updates the associated mesh
  36455. * @param mesh the mesh to be updated
  36456. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36457. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36458. * @returns VertexData
  36459. */
  36460. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36461. this._update(mesh);
  36462. return this;
  36463. };
  36464. /**
  36465. * Updates the associated geometry
  36466. * @param geometry the geometry to be updated
  36467. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36468. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36469. * @returns VertexData.
  36470. */
  36471. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36472. this._update(geometry);
  36473. return this;
  36474. };
  36475. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36476. if (updatable === void 0) { updatable = false; }
  36477. if (this.positions) {
  36478. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36479. }
  36480. if (this.normals) {
  36481. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36482. }
  36483. if (this.tangents) {
  36484. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36485. }
  36486. if (this.uvs) {
  36487. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36488. }
  36489. if (this.uvs2) {
  36490. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36491. }
  36492. if (this.uvs3) {
  36493. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36494. }
  36495. if (this.uvs4) {
  36496. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36497. }
  36498. if (this.uvs5) {
  36499. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36500. }
  36501. if (this.uvs6) {
  36502. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36503. }
  36504. if (this.colors) {
  36505. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36506. }
  36507. if (this.matricesIndices) {
  36508. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36509. }
  36510. if (this.matricesWeights) {
  36511. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36512. }
  36513. if (this.matricesIndicesExtra) {
  36514. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36515. }
  36516. if (this.matricesWeightsExtra) {
  36517. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36518. }
  36519. if (this.indices) {
  36520. meshOrGeometry.setIndices(this.indices, null, updatable);
  36521. }
  36522. return this;
  36523. };
  36524. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36525. if (this.positions) {
  36526. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36527. }
  36528. if (this.normals) {
  36529. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36530. }
  36531. if (this.tangents) {
  36532. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36533. }
  36534. if (this.uvs) {
  36535. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36536. }
  36537. if (this.uvs2) {
  36538. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36539. }
  36540. if (this.uvs3) {
  36541. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36542. }
  36543. if (this.uvs4) {
  36544. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36545. }
  36546. if (this.uvs5) {
  36547. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36548. }
  36549. if (this.uvs6) {
  36550. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36551. }
  36552. if (this.colors) {
  36553. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36554. }
  36555. if (this.matricesIndices) {
  36556. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36557. }
  36558. if (this.matricesWeights) {
  36559. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36560. }
  36561. if (this.matricesIndicesExtra) {
  36562. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36563. }
  36564. if (this.matricesWeightsExtra) {
  36565. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36566. }
  36567. if (this.indices) {
  36568. meshOrGeometry.setIndices(this.indices, null);
  36569. }
  36570. return this;
  36571. };
  36572. /**
  36573. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36574. * @param matrix the transforming matrix
  36575. * @returns the VertexData
  36576. */
  36577. VertexData.prototype.transform = function (matrix) {
  36578. var transformed = BABYLON.Vector3.Zero();
  36579. var index;
  36580. if (this.positions) {
  36581. var position = BABYLON.Vector3.Zero();
  36582. for (index = 0; index < this.positions.length; index += 3) {
  36583. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36584. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36585. this.positions[index] = transformed.x;
  36586. this.positions[index + 1] = transformed.y;
  36587. this.positions[index + 2] = transformed.z;
  36588. }
  36589. }
  36590. if (this.normals) {
  36591. var normal = BABYLON.Vector3.Zero();
  36592. for (index = 0; index < this.normals.length; index += 3) {
  36593. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36594. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36595. this.normals[index] = transformed.x;
  36596. this.normals[index + 1] = transformed.y;
  36597. this.normals[index + 2] = transformed.z;
  36598. }
  36599. }
  36600. if (this.tangents) {
  36601. var tangent = BABYLON.Vector4.Zero();
  36602. var tangentTransformed = BABYLON.Vector4.Zero();
  36603. for (index = 0; index < this.tangents.length; index += 4) {
  36604. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36605. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36606. this.tangents[index] = tangentTransformed.x;
  36607. this.tangents[index + 1] = tangentTransformed.y;
  36608. this.tangents[index + 2] = tangentTransformed.z;
  36609. this.tangents[index + 3] = tangentTransformed.w;
  36610. }
  36611. }
  36612. return this;
  36613. };
  36614. /**
  36615. * Merges the passed VertexData into the current one
  36616. * @param other the VertexData to be merged into the current one
  36617. * @returns the modified VertexData
  36618. */
  36619. VertexData.prototype.merge = function (other) {
  36620. this._validate();
  36621. other._validate();
  36622. if (!this.normals !== !other.normals ||
  36623. !this.tangents !== !other.tangents ||
  36624. !this.uvs !== !other.uvs ||
  36625. !this.uvs2 !== !other.uvs2 ||
  36626. !this.uvs3 !== !other.uvs3 ||
  36627. !this.uvs4 !== !other.uvs4 ||
  36628. !this.uvs5 !== !other.uvs5 ||
  36629. !this.uvs6 !== !other.uvs6 ||
  36630. !this.colors !== !other.colors ||
  36631. !this.matricesIndices !== !other.matricesIndices ||
  36632. !this.matricesWeights !== !other.matricesWeights ||
  36633. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36634. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36635. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36636. }
  36637. if (other.indices) {
  36638. if (!this.indices) {
  36639. this.indices = [];
  36640. }
  36641. var offset = this.positions ? this.positions.length / 3 : 0;
  36642. for (var index = 0; index < other.indices.length; index++) {
  36643. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36644. this.indices.push(other.indices[index] + offset);
  36645. }
  36646. }
  36647. this.positions = this._mergeElement(this.positions, other.positions);
  36648. this.normals = this._mergeElement(this.normals, other.normals);
  36649. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36650. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36651. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36652. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36653. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36654. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36655. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36656. this.colors = this._mergeElement(this.colors, other.colors);
  36657. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36658. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36659. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36660. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36661. return this;
  36662. };
  36663. VertexData.prototype._mergeElement = function (source, other) {
  36664. if (!source) {
  36665. return other;
  36666. }
  36667. if (!other) {
  36668. return source;
  36669. }
  36670. var len = other.length + source.length;
  36671. var isSrcTypedArray = source instanceof Float32Array;
  36672. var isOthTypedArray = other instanceof Float32Array;
  36673. // use non-loop method when the source is Float32Array
  36674. if (isSrcTypedArray) {
  36675. var ret32 = new Float32Array(len);
  36676. ret32.set(source);
  36677. ret32.set(other, source.length);
  36678. return ret32;
  36679. // source is number[], when other is also use concat
  36680. }
  36681. else if (!isOthTypedArray) {
  36682. return source.concat(other);
  36683. // source is a number[], but other is a Float32Array, loop required
  36684. }
  36685. else {
  36686. var ret = source.slice(0); // copy source to a separate array
  36687. for (var i = 0, len = other.length; i < len; i++) {
  36688. ret.push(other[i]);
  36689. }
  36690. return ret;
  36691. }
  36692. };
  36693. VertexData.prototype._validate = function () {
  36694. if (!this.positions) {
  36695. throw new Error("Positions are required");
  36696. }
  36697. var getElementCount = function (kind, values) {
  36698. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36699. if ((values.length % stride) !== 0) {
  36700. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36701. }
  36702. return values.length / stride;
  36703. };
  36704. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36705. var validateElementCount = function (kind, values) {
  36706. var elementCount = getElementCount(kind, values);
  36707. if (elementCount !== positionsElementCount) {
  36708. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36709. }
  36710. };
  36711. if (this.normals)
  36712. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36713. if (this.tangents)
  36714. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36715. if (this.uvs)
  36716. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36717. if (this.uvs2)
  36718. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36719. if (this.uvs3)
  36720. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36721. if (this.uvs4)
  36722. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36723. if (this.uvs5)
  36724. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36725. if (this.uvs6)
  36726. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36727. if (this.colors)
  36728. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36729. if (this.matricesIndices)
  36730. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36731. if (this.matricesWeights)
  36732. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36733. if (this.matricesIndicesExtra)
  36734. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36735. if (this.matricesWeightsExtra)
  36736. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36737. };
  36738. /**
  36739. * Serializes the VertexData
  36740. * @returns a serialized object
  36741. */
  36742. VertexData.prototype.serialize = function () {
  36743. var serializationObject = this.serialize();
  36744. if (this.positions) {
  36745. serializationObject.positions = this.positions;
  36746. }
  36747. if (this.normals) {
  36748. serializationObject.normals = this.normals;
  36749. }
  36750. if (this.tangents) {
  36751. serializationObject.tangents = this.tangents;
  36752. }
  36753. if (this.uvs) {
  36754. serializationObject.uvs = this.uvs;
  36755. }
  36756. if (this.uvs2) {
  36757. serializationObject.uvs2 = this.uvs2;
  36758. }
  36759. if (this.uvs3) {
  36760. serializationObject.uvs3 = this.uvs3;
  36761. }
  36762. if (this.uvs4) {
  36763. serializationObject.uvs4 = this.uvs4;
  36764. }
  36765. if (this.uvs5) {
  36766. serializationObject.uvs5 = this.uvs5;
  36767. }
  36768. if (this.uvs6) {
  36769. serializationObject.uvs6 = this.uvs6;
  36770. }
  36771. if (this.colors) {
  36772. serializationObject.colors = this.colors;
  36773. }
  36774. if (this.matricesIndices) {
  36775. serializationObject.matricesIndices = this.matricesIndices;
  36776. serializationObject.matricesIndices._isExpanded = true;
  36777. }
  36778. if (this.matricesWeights) {
  36779. serializationObject.matricesWeights = this.matricesWeights;
  36780. }
  36781. if (this.matricesIndicesExtra) {
  36782. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36783. serializationObject.matricesIndicesExtra._isExpanded = true;
  36784. }
  36785. if (this.matricesWeightsExtra) {
  36786. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36787. }
  36788. serializationObject.indices = this.indices;
  36789. return serializationObject;
  36790. };
  36791. // Statics
  36792. /**
  36793. * Extracts the vertexData from a mesh
  36794. * @param mesh the mesh from which to extract the VertexData
  36795. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36796. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36797. * @returns the object VertexData associated to the passed mesh
  36798. */
  36799. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36800. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36801. };
  36802. /**
  36803. * Extracts the vertexData from the geometry
  36804. * @param geometry the geometry from which to extract the VertexData
  36805. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36806. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36807. * @returns the object VertexData associated to the passed mesh
  36808. */
  36809. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36810. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36811. };
  36812. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36813. var result = new VertexData();
  36814. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36815. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36816. }
  36817. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36818. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36819. }
  36820. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36821. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36822. }
  36823. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36824. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36825. }
  36826. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36827. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36828. }
  36829. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36830. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36831. }
  36832. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36833. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36834. }
  36835. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36836. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36837. }
  36838. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36839. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36840. }
  36841. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36842. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36843. }
  36844. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36845. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36846. }
  36847. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36848. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36849. }
  36850. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36851. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36852. }
  36853. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36854. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36855. }
  36856. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36857. return result;
  36858. };
  36859. /**
  36860. * Creates the VertexData for a Ribbon
  36861. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36862. * * pathArray array of paths, each of which an array of successive Vector3
  36863. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36864. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36865. * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length
  36866. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36867. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36868. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36869. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36870. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36871. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36872. * @returns the VertexData of the ribbon
  36873. */
  36874. VertexData.CreateRibbon = function (options) {
  36875. var pathArray = options.pathArray;
  36876. var closeArray = options.closeArray || false;
  36877. var closePath = options.closePath || false;
  36878. var invertUV = options.invertUV || false;
  36879. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36880. var offset = options.offset || defaultOffset;
  36881. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36882. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36883. var customUV = options.uvs;
  36884. var customColors = options.colors;
  36885. var positions = [];
  36886. var indices = [];
  36887. var normals = [];
  36888. var uvs = [];
  36889. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36890. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36891. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36892. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36893. var minlg; // minimal length among all paths from pathArray
  36894. var lg = []; // array of path lengths : nb of vertex per path
  36895. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36896. var p; // path iterator
  36897. var i; // point iterator
  36898. var j; // point iterator
  36899. // if single path in pathArray
  36900. if (pathArray.length < 2) {
  36901. var ar1 = [];
  36902. var ar2 = [];
  36903. for (i = 0; i < pathArray[0].length - offset; i++) {
  36904. ar1.push(pathArray[0][i]);
  36905. ar2.push(pathArray[0][i + offset]);
  36906. }
  36907. pathArray = [ar1, ar2];
  36908. }
  36909. // positions and horizontal distances (u)
  36910. var idc = 0;
  36911. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36912. var path;
  36913. var l;
  36914. minlg = pathArray[0].length;
  36915. var vectlg;
  36916. var dist;
  36917. for (p = 0; p < pathArray.length; p++) {
  36918. uTotalDistance[p] = 0;
  36919. us[p] = [0];
  36920. path = pathArray[p];
  36921. l = path.length;
  36922. minlg = (minlg < l) ? minlg : l;
  36923. j = 0;
  36924. while (j < l) {
  36925. positions.push(path[j].x, path[j].y, path[j].z);
  36926. if (j > 0) {
  36927. vectlg = path[j].subtract(path[j - 1]).length();
  36928. dist = vectlg + uTotalDistance[p];
  36929. us[p].push(dist);
  36930. uTotalDistance[p] = dist;
  36931. }
  36932. j++;
  36933. }
  36934. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36935. j--;
  36936. positions.push(path[0].x, path[0].y, path[0].z);
  36937. vectlg = path[j].subtract(path[0]).length();
  36938. dist = vectlg + uTotalDistance[p];
  36939. us[p].push(dist);
  36940. uTotalDistance[p] = dist;
  36941. }
  36942. lg[p] = l + closePathCorr;
  36943. idx[p] = idc;
  36944. idc += (l + closePathCorr);
  36945. }
  36946. // vertical distances (v)
  36947. var path1;
  36948. var path2;
  36949. var vertex1 = null;
  36950. var vertex2 = null;
  36951. for (i = 0; i < minlg + closePathCorr; i++) {
  36952. vTotalDistance[i] = 0;
  36953. vs[i] = [0];
  36954. for (p = 0; p < pathArray.length - 1; p++) {
  36955. path1 = pathArray[p];
  36956. path2 = pathArray[p + 1];
  36957. if (i === minlg) { // closePath
  36958. vertex1 = path1[0];
  36959. vertex2 = path2[0];
  36960. }
  36961. else {
  36962. vertex1 = path1[i];
  36963. vertex2 = path2[i];
  36964. }
  36965. vectlg = vertex2.subtract(vertex1).length();
  36966. dist = vectlg + vTotalDistance[i];
  36967. vs[i].push(dist);
  36968. vTotalDistance[i] = dist;
  36969. }
  36970. if (closeArray && vertex2 && vertex1) {
  36971. path1 = pathArray[p];
  36972. path2 = pathArray[0];
  36973. if (i === minlg) { // closePath
  36974. vertex2 = path2[0];
  36975. }
  36976. vectlg = vertex2.subtract(vertex1).length();
  36977. dist = vectlg + vTotalDistance[i];
  36978. vTotalDistance[i] = dist;
  36979. }
  36980. }
  36981. // uvs
  36982. var u;
  36983. var v;
  36984. if (customUV) {
  36985. for (p = 0; p < customUV.length; p++) {
  36986. uvs.push(customUV[p].x, customUV[p].y);
  36987. }
  36988. }
  36989. else {
  36990. for (p = 0; p < pathArray.length; p++) {
  36991. for (i = 0; i < minlg + closePathCorr; i++) {
  36992. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36993. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36994. if (invertUV) {
  36995. uvs.push(v, u);
  36996. }
  36997. else {
  36998. uvs.push(u, v);
  36999. }
  37000. }
  37001. }
  37002. }
  37003. // indices
  37004. p = 0; // path index
  37005. var pi = 0; // positions array index
  37006. var l1 = lg[p] - 1; // path1 length
  37007. var l2 = lg[p + 1] - 1; // path2 length
  37008. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37009. var shft = idx[1] - idx[0]; // shift
  37010. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37011. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37012. // 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
  37013. indices.push(pi, pi + shft, pi + 1);
  37014. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37015. pi += 1;
  37016. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37017. p++;
  37018. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37019. shft = idx[0] - idx[p];
  37020. l1 = lg[p] - 1;
  37021. l2 = lg[0] - 1;
  37022. }
  37023. else {
  37024. shft = idx[p + 1] - idx[p];
  37025. l1 = lg[p] - 1;
  37026. l2 = lg[p + 1] - 1;
  37027. }
  37028. pi = idx[p];
  37029. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37030. }
  37031. }
  37032. // normals
  37033. VertexData.ComputeNormals(positions, indices, normals);
  37034. if (closePath) { // update both the first and last vertex normals to their average value
  37035. var indexFirst = 0;
  37036. var indexLast = 0;
  37037. for (p = 0; p < pathArray.length; p++) {
  37038. indexFirst = idx[p] * 3;
  37039. if (p + 1 < pathArray.length) {
  37040. indexLast = (idx[p + 1] - 1) * 3;
  37041. }
  37042. else {
  37043. indexLast = normals.length - 3;
  37044. }
  37045. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37046. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37047. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37048. normals[indexLast] = normals[indexFirst];
  37049. normals[indexLast + 1] = normals[indexFirst + 1];
  37050. normals[indexLast + 2] = normals[indexFirst + 2];
  37051. }
  37052. }
  37053. // sides
  37054. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37055. // Colors
  37056. var colors = null;
  37057. if (customColors) {
  37058. colors = new Float32Array(customColors.length * 4);
  37059. for (var c = 0; c < customColors.length; c++) {
  37060. colors[c * 4] = customColors[c].r;
  37061. colors[c * 4 + 1] = customColors[c].g;
  37062. colors[c * 4 + 2] = customColors[c].b;
  37063. colors[c * 4 + 3] = customColors[c].a;
  37064. }
  37065. }
  37066. // Result
  37067. var vertexData = new VertexData();
  37068. var positions32 = new Float32Array(positions);
  37069. var normals32 = new Float32Array(normals);
  37070. var uvs32 = new Float32Array(uvs);
  37071. vertexData.indices = indices;
  37072. vertexData.positions = positions32;
  37073. vertexData.normals = normals32;
  37074. vertexData.uvs = uvs32;
  37075. if (colors) {
  37076. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37077. }
  37078. if (closePath) {
  37079. vertexData._idx = idx;
  37080. }
  37081. return vertexData;
  37082. };
  37083. /**
  37084. * Creates the VertexData for a box
  37085. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37086. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37087. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37088. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37089. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37090. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37091. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37092. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37093. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37094. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37095. * @returns the VertexData of the box
  37096. */
  37097. VertexData.CreateBox = function (options) {
  37098. var normalsSource = [
  37099. new BABYLON.Vector3(0, 0, 1),
  37100. new BABYLON.Vector3(0, 0, -1),
  37101. new BABYLON.Vector3(1, 0, 0),
  37102. new BABYLON.Vector3(-1, 0, 0),
  37103. new BABYLON.Vector3(0, 1, 0),
  37104. new BABYLON.Vector3(0, -1, 0)
  37105. ];
  37106. var indices = [];
  37107. var positions = [];
  37108. var normals = [];
  37109. var uvs = [];
  37110. var width = options.width || options.size || 1;
  37111. var height = options.height || options.size || 1;
  37112. var depth = options.depth || options.size || 1;
  37113. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37114. var faceUV = options.faceUV || new Array(6);
  37115. var faceColors = options.faceColors;
  37116. var colors = [];
  37117. // default face colors and UV if undefined
  37118. for (var f = 0; f < 6; f++) {
  37119. if (faceUV[f] === undefined) {
  37120. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37121. }
  37122. if (faceColors && faceColors[f] === undefined) {
  37123. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37124. }
  37125. }
  37126. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37127. // Create each face in turn.
  37128. for (var index = 0; index < normalsSource.length; index++) {
  37129. var normal = normalsSource[index];
  37130. // Get two vectors perpendicular to the face normal and to each other.
  37131. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37132. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37133. // Six indices (two triangles) per face.
  37134. var verticesLength = positions.length / 3;
  37135. indices.push(verticesLength);
  37136. indices.push(verticesLength + 1);
  37137. indices.push(verticesLength + 2);
  37138. indices.push(verticesLength);
  37139. indices.push(verticesLength + 2);
  37140. indices.push(verticesLength + 3);
  37141. // Four vertices per face.
  37142. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37143. positions.push(vertex.x, vertex.y, vertex.z);
  37144. normals.push(normal.x, normal.y, normal.z);
  37145. uvs.push(faceUV[index].z, faceUV[index].w);
  37146. if (faceColors) {
  37147. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37148. }
  37149. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37150. positions.push(vertex.x, vertex.y, vertex.z);
  37151. normals.push(normal.x, normal.y, normal.z);
  37152. uvs.push(faceUV[index].x, faceUV[index].w);
  37153. if (faceColors) {
  37154. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37155. }
  37156. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37157. positions.push(vertex.x, vertex.y, vertex.z);
  37158. normals.push(normal.x, normal.y, normal.z);
  37159. uvs.push(faceUV[index].x, faceUV[index].y);
  37160. if (faceColors) {
  37161. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37162. }
  37163. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37164. positions.push(vertex.x, vertex.y, vertex.z);
  37165. normals.push(normal.x, normal.y, normal.z);
  37166. uvs.push(faceUV[index].z, faceUV[index].y);
  37167. if (faceColors) {
  37168. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37169. }
  37170. }
  37171. // sides
  37172. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37173. // Result
  37174. var vertexData = new VertexData();
  37175. vertexData.indices = indices;
  37176. vertexData.positions = positions;
  37177. vertexData.normals = normals;
  37178. vertexData.uvs = uvs;
  37179. if (faceColors) {
  37180. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37181. vertexData.colors = totalColors;
  37182. }
  37183. return vertexData;
  37184. };
  37185. /**
  37186. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37187. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37188. * * segments sets the number of horizontal strips optional, default 32
  37189. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37190. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37191. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37192. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37193. * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1
  37194. * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1
  37195. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37196. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37197. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37198. * @returns the VertexData of the ellipsoid
  37199. */
  37200. VertexData.CreateSphere = function (options) {
  37201. var segments = options.segments || 32;
  37202. var diameterX = options.diameterX || options.diameter || 1;
  37203. var diameterY = options.diameterY || options.diameter || 1;
  37204. var diameterZ = options.diameterZ || options.diameter || 1;
  37205. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37206. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37207. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37208. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37209. var totalZRotationSteps = 2 + segments;
  37210. var totalYRotationSteps = 2 * totalZRotationSteps;
  37211. var indices = [];
  37212. var positions = [];
  37213. var normals = [];
  37214. var uvs = [];
  37215. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37216. var normalizedZ = zRotationStep / totalZRotationSteps;
  37217. var angleZ = normalizedZ * Math.PI * slice;
  37218. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37219. var normalizedY = yRotationStep / totalYRotationSteps;
  37220. var angleY = normalizedY * Math.PI * 2 * arc;
  37221. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37222. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37223. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37224. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37225. var vertex = complete.multiply(radius);
  37226. var normal = complete.divide(radius).normalize();
  37227. positions.push(vertex.x, vertex.y, vertex.z);
  37228. normals.push(normal.x, normal.y, normal.z);
  37229. uvs.push(normalizedY, normalizedZ);
  37230. }
  37231. if (zRotationStep > 0) {
  37232. var verticesCount = positions.length / 3;
  37233. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37234. indices.push((firstIndex));
  37235. indices.push((firstIndex + 1));
  37236. indices.push(firstIndex + totalYRotationSteps + 1);
  37237. indices.push((firstIndex + totalYRotationSteps + 1));
  37238. indices.push((firstIndex + 1));
  37239. indices.push((firstIndex + totalYRotationSteps + 2));
  37240. }
  37241. }
  37242. }
  37243. // Sides
  37244. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37245. // Result
  37246. var vertexData = new VertexData();
  37247. vertexData.indices = indices;
  37248. vertexData.positions = positions;
  37249. vertexData.normals = normals;
  37250. vertexData.uvs = uvs;
  37251. return vertexData;
  37252. };
  37253. /**
  37254. * Creates the VertexData for a cylinder, cone or prism
  37255. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37256. * * height sets the height (y direction) of the cylinder, optional, default 2
  37257. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37258. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37259. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37260. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37261. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37262. * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1
  37263. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37264. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37265. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37266. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37267. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37268. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37269. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37270. * @returns the VertexData of the cylinder, cone or prism
  37271. */
  37272. VertexData.CreateCylinder = function (options) {
  37273. var height = options.height || 2;
  37274. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37275. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37276. var tessellation = options.tessellation || 24;
  37277. var subdivisions = options.subdivisions || 1;
  37278. var hasRings = options.hasRings ? true : false;
  37279. var enclose = options.enclose ? true : false;
  37280. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37281. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37282. var faceUV = options.faceUV || new Array(3);
  37283. var faceColors = options.faceColors;
  37284. // default face colors and UV if undefined
  37285. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37286. var ringNb = (hasRings) ? subdivisions : 1;
  37287. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37288. var f;
  37289. for (f = 0; f < surfaceNb; f++) {
  37290. if (faceColors && faceColors[f] === undefined) {
  37291. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37292. }
  37293. }
  37294. for (f = 0; f < surfaceNb; f++) {
  37295. if (faceUV && faceUV[f] === undefined) {
  37296. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37297. }
  37298. }
  37299. var indices = new Array();
  37300. var positions = new Array();
  37301. var normals = new Array();
  37302. var uvs = new Array();
  37303. var colors = new Array();
  37304. var angle_step = Math.PI * 2 * arc / tessellation;
  37305. var angle;
  37306. var h;
  37307. var radius;
  37308. var tan = (diameterBottom - diameterTop) / 2 / height;
  37309. var ringVertex = BABYLON.Vector3.Zero();
  37310. var ringNormal = BABYLON.Vector3.Zero();
  37311. var ringFirstVertex = BABYLON.Vector3.Zero();
  37312. var ringFirstNormal = BABYLON.Vector3.Zero();
  37313. var quadNormal = BABYLON.Vector3.Zero();
  37314. var Y = BABYLON.Axis.Y;
  37315. // positions, normals, uvs
  37316. var i;
  37317. var j;
  37318. var r;
  37319. var ringIdx = 1;
  37320. var s = 1; // surface index
  37321. var cs = 0;
  37322. var v = 0;
  37323. for (i = 0; i <= subdivisions; i++) {
  37324. h = i / subdivisions;
  37325. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37326. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37327. for (r = 0; r < ringIdx; r++) {
  37328. if (hasRings) {
  37329. s += r;
  37330. }
  37331. if (enclose) {
  37332. s += 2 * r;
  37333. }
  37334. for (j = 0; j <= tessellation; j++) {
  37335. angle = j * angle_step;
  37336. // position
  37337. ringVertex.x = Math.cos(-angle) * radius;
  37338. ringVertex.y = -height / 2 + h * height;
  37339. ringVertex.z = Math.sin(-angle) * radius;
  37340. // normal
  37341. if (diameterTop === 0 && i === subdivisions) {
  37342. // if no top cap, reuse former normals
  37343. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37344. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37345. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37346. }
  37347. else {
  37348. ringNormal.x = ringVertex.x;
  37349. ringNormal.z = ringVertex.z;
  37350. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37351. ringNormal.normalize();
  37352. }
  37353. // keep first ring vertex values for enclose
  37354. if (j === 0) {
  37355. ringFirstVertex.copyFrom(ringVertex);
  37356. ringFirstNormal.copyFrom(ringNormal);
  37357. }
  37358. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37359. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37360. if (hasRings) {
  37361. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37362. }
  37363. else {
  37364. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37365. }
  37366. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37367. if (faceColors) {
  37368. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37369. }
  37370. }
  37371. // if enclose, add four vertices and their dedicated normals
  37372. if (arc !== 1 && enclose) {
  37373. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37374. positions.push(0, ringVertex.y, 0);
  37375. positions.push(0, ringVertex.y, 0);
  37376. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37377. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37378. quadNormal.normalize();
  37379. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37380. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37381. quadNormal.normalize();
  37382. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37383. if (hasRings) {
  37384. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37385. }
  37386. else {
  37387. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37388. }
  37389. uvs.push(faceUV[s + 1].x, v);
  37390. uvs.push(faceUV[s + 1].z, v);
  37391. if (hasRings) {
  37392. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37393. }
  37394. else {
  37395. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37396. }
  37397. uvs.push(faceUV[s + 2].x, v);
  37398. uvs.push(faceUV[s + 2].z, v);
  37399. if (faceColors) {
  37400. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37401. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37402. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37403. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37404. }
  37405. }
  37406. if (cs !== s) {
  37407. cs = s;
  37408. }
  37409. }
  37410. }
  37411. // indices
  37412. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37413. var s;
  37414. i = 0;
  37415. for (s = 0; s < subdivisions; s++) {
  37416. var i0 = 0;
  37417. var i1 = 0;
  37418. var i2 = 0;
  37419. var i3 = 0;
  37420. for (j = 0; j < tessellation; j++) {
  37421. i0 = i * (e + 1) + j;
  37422. i1 = (i + 1) * (e + 1) + j;
  37423. i2 = i * (e + 1) + (j + 1);
  37424. i3 = (i + 1) * (e + 1) + (j + 1);
  37425. indices.push(i0, i1, i2);
  37426. indices.push(i3, i2, i1);
  37427. }
  37428. if (arc !== 1 && enclose) { // if enclose, add two quads
  37429. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37430. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37431. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37432. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37433. }
  37434. i = (hasRings) ? (i + 2) : (i + 1);
  37435. }
  37436. // Caps
  37437. var createCylinderCap = function (isTop) {
  37438. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37439. if (radius === 0) {
  37440. return;
  37441. }
  37442. // Cap positions, normals & uvs
  37443. var angle;
  37444. var circleVector;
  37445. var i;
  37446. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37447. var c = null;
  37448. if (faceColors) {
  37449. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37450. }
  37451. // cap center
  37452. var vbase = positions.length / 3;
  37453. var offset = isTop ? height / 2 : -height / 2;
  37454. var center = new BABYLON.Vector3(0, offset, 0);
  37455. positions.push(center.x, center.y, center.z);
  37456. normals.push(0, isTop ? 1 : -1, 0);
  37457. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37458. if (c) {
  37459. colors.push(c.r, c.g, c.b, c.a);
  37460. }
  37461. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37462. for (i = 0; i <= tessellation; i++) {
  37463. angle = Math.PI * 2 * i * arc / tessellation;
  37464. var cos = Math.cos(-angle);
  37465. var sin = Math.sin(-angle);
  37466. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37467. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37468. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37469. normals.push(0, isTop ? 1 : -1, 0);
  37470. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37471. if (c) {
  37472. colors.push(c.r, c.g, c.b, c.a);
  37473. }
  37474. }
  37475. // Cap indices
  37476. for (i = 0; i < tessellation; i++) {
  37477. if (!isTop) {
  37478. indices.push(vbase);
  37479. indices.push(vbase + (i + 1));
  37480. indices.push(vbase + (i + 2));
  37481. }
  37482. else {
  37483. indices.push(vbase);
  37484. indices.push(vbase + (i + 2));
  37485. indices.push(vbase + (i + 1));
  37486. }
  37487. }
  37488. };
  37489. // add caps to geometry
  37490. createCylinderCap(false);
  37491. createCylinderCap(true);
  37492. // Sides
  37493. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37494. var vertexData = new VertexData();
  37495. vertexData.indices = indices;
  37496. vertexData.positions = positions;
  37497. vertexData.normals = normals;
  37498. vertexData.uvs = uvs;
  37499. if (faceColors) {
  37500. vertexData.colors = colors;
  37501. }
  37502. return vertexData;
  37503. };
  37504. /**
  37505. * Creates the VertexData for a torus
  37506. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37507. * * diameter the diameter of the torus, optional default 1
  37508. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37509. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37510. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37511. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37512. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37513. * @returns the VertexData of the torus
  37514. */
  37515. VertexData.CreateTorus = function (options) {
  37516. var indices = [];
  37517. var positions = [];
  37518. var normals = [];
  37519. var uvs = [];
  37520. var diameter = options.diameter || 1;
  37521. var thickness = options.thickness || 0.5;
  37522. var tessellation = options.tessellation || 16;
  37523. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37524. var stride = tessellation + 1;
  37525. for (var i = 0; i <= tessellation; i++) {
  37526. var u = i / tessellation;
  37527. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37528. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37529. for (var j = 0; j <= tessellation; j++) {
  37530. var v = 1 - j / tessellation;
  37531. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37532. var dx = Math.cos(innerAngle);
  37533. var dy = Math.sin(innerAngle);
  37534. // Create a vertex.
  37535. var normal = new BABYLON.Vector3(dx, dy, 0);
  37536. var position = normal.scale(thickness / 2);
  37537. var textureCoordinate = new BABYLON.Vector2(u, v);
  37538. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37539. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37540. positions.push(position.x, position.y, position.z);
  37541. normals.push(normal.x, normal.y, normal.z);
  37542. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37543. // And create indices for two triangles.
  37544. var nextI = (i + 1) % stride;
  37545. var nextJ = (j + 1) % stride;
  37546. indices.push(i * stride + j);
  37547. indices.push(i * stride + nextJ);
  37548. indices.push(nextI * stride + j);
  37549. indices.push(i * stride + nextJ);
  37550. indices.push(nextI * stride + nextJ);
  37551. indices.push(nextI * stride + j);
  37552. }
  37553. }
  37554. // Sides
  37555. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37556. // Result
  37557. var vertexData = new VertexData();
  37558. vertexData.indices = indices;
  37559. vertexData.positions = positions;
  37560. vertexData.normals = normals;
  37561. vertexData.uvs = uvs;
  37562. return vertexData;
  37563. };
  37564. /**
  37565. * Creates the VertexData of the LineSystem
  37566. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37567. * - lines an array of lines, each line being an array of successive Vector3
  37568. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37569. * @returns the VertexData of the LineSystem
  37570. */
  37571. VertexData.CreateLineSystem = function (options) {
  37572. var indices = [];
  37573. var positions = [];
  37574. var lines = options.lines;
  37575. var colors = options.colors;
  37576. var vertexColors = [];
  37577. var idx = 0;
  37578. for (var l = 0; l < lines.length; l++) {
  37579. var points = lines[l];
  37580. for (var index = 0; index < points.length; index++) {
  37581. positions.push(points[index].x, points[index].y, points[index].z);
  37582. if (colors) {
  37583. var color = colors[l];
  37584. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37585. }
  37586. if (index > 0) {
  37587. indices.push(idx - 1);
  37588. indices.push(idx);
  37589. }
  37590. idx++;
  37591. }
  37592. }
  37593. var vertexData = new VertexData();
  37594. vertexData.indices = indices;
  37595. vertexData.positions = positions;
  37596. if (colors) {
  37597. vertexData.colors = vertexColors;
  37598. }
  37599. return vertexData;
  37600. };
  37601. /**
  37602. * Create the VertexData for a DashedLines
  37603. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37604. * - points an array successive Vector3
  37605. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37606. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37607. * - dashNb the intended total number of dashes, optional, default 200
  37608. * @returns the VertexData for the DashedLines
  37609. */
  37610. VertexData.CreateDashedLines = function (options) {
  37611. var dashSize = options.dashSize || 3;
  37612. var gapSize = options.gapSize || 1;
  37613. var dashNb = options.dashNb || 200;
  37614. var points = options.points;
  37615. var positions = new Array();
  37616. var indices = new Array();
  37617. var curvect = BABYLON.Vector3.Zero();
  37618. var lg = 0;
  37619. var nb = 0;
  37620. var shft = 0;
  37621. var dashshft = 0;
  37622. var curshft = 0;
  37623. var idx = 0;
  37624. var i = 0;
  37625. for (i = 0; i < points.length - 1; i++) {
  37626. points[i + 1].subtractToRef(points[i], curvect);
  37627. lg += curvect.length();
  37628. }
  37629. shft = lg / dashNb;
  37630. dashshft = dashSize * shft / (dashSize + gapSize);
  37631. for (i = 0; i < points.length - 1; i++) {
  37632. points[i + 1].subtractToRef(points[i], curvect);
  37633. nb = Math.floor(curvect.length() / shft);
  37634. curvect.normalize();
  37635. for (var j = 0; j < nb; j++) {
  37636. curshft = shft * j;
  37637. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37638. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37639. indices.push(idx, idx + 1);
  37640. idx += 2;
  37641. }
  37642. }
  37643. // Result
  37644. var vertexData = new VertexData();
  37645. vertexData.positions = positions;
  37646. vertexData.indices = indices;
  37647. return vertexData;
  37648. };
  37649. /**
  37650. * Creates the VertexData for a Ground
  37651. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37652. * - width the width (x direction) of the ground, optional, default 1
  37653. * - height the height (z direction) of the ground, optional, default 1
  37654. * - subdivisions the number of subdivisions per side, optional, default 1
  37655. * @returns the VertexData of the Ground
  37656. */
  37657. VertexData.CreateGround = function (options) {
  37658. var indices = [];
  37659. var positions = [];
  37660. var normals = [];
  37661. var uvs = [];
  37662. var row, col;
  37663. var width = options.width || 1;
  37664. var height = options.height || 1;
  37665. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37666. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37667. for (row = 0; row <= subdivisionsY; row++) {
  37668. for (col = 0; col <= subdivisionsX; col++) {
  37669. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37670. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37671. positions.push(position.x, position.y, position.z);
  37672. normals.push(normal.x, normal.y, normal.z);
  37673. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37674. }
  37675. }
  37676. for (row = 0; row < subdivisionsY; row++) {
  37677. for (col = 0; col < subdivisionsX; col++) {
  37678. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37679. indices.push(col + 1 + row * (subdivisionsX + 1));
  37680. indices.push(col + row * (subdivisionsX + 1));
  37681. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37682. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37683. indices.push(col + row * (subdivisionsX + 1));
  37684. }
  37685. }
  37686. // Result
  37687. var vertexData = new VertexData();
  37688. vertexData.indices = indices;
  37689. vertexData.positions = positions;
  37690. vertexData.normals = normals;
  37691. vertexData.uvs = uvs;
  37692. return vertexData;
  37693. };
  37694. /**
  37695. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37696. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37697. * * xmin the ground minimum X coordinate, optional, default -1
  37698. * * zmin the ground minimum Z coordinate, optional, default -1
  37699. * * xmax the ground maximum X coordinate, optional, default 1
  37700. * * zmax the ground maximum Z coordinate, optional, default 1
  37701. * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6}
  37702. * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2}
  37703. * @returns the VertexData of the TiledGround
  37704. */
  37705. VertexData.CreateTiledGround = function (options) {
  37706. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37707. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37708. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37709. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37710. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37711. var precision = options.precision || { w: 1, h: 1 };
  37712. var indices = new Array();
  37713. var positions = new Array();
  37714. var normals = new Array();
  37715. var uvs = new Array();
  37716. var row, col, tileRow, tileCol;
  37717. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37718. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37719. precision.w = (precision.w < 1) ? 1 : precision.w;
  37720. precision.h = (precision.h < 1) ? 1 : precision.h;
  37721. var tileSize = {
  37722. 'w': (xmax - xmin) / subdivisions.w,
  37723. 'h': (zmax - zmin) / subdivisions.h
  37724. };
  37725. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37726. // Indices
  37727. var base = positions.length / 3;
  37728. var rowLength = precision.w + 1;
  37729. for (row = 0; row < precision.h; row++) {
  37730. for (col = 0; col < precision.w; col++) {
  37731. var square = [
  37732. base + col + row * rowLength,
  37733. base + (col + 1) + row * rowLength,
  37734. base + (col + 1) + (row + 1) * rowLength,
  37735. base + col + (row + 1) * rowLength
  37736. ];
  37737. indices.push(square[1]);
  37738. indices.push(square[2]);
  37739. indices.push(square[3]);
  37740. indices.push(square[0]);
  37741. indices.push(square[1]);
  37742. indices.push(square[3]);
  37743. }
  37744. }
  37745. // Position, normals and uvs
  37746. var position = BABYLON.Vector3.Zero();
  37747. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37748. for (row = 0; row <= precision.h; row++) {
  37749. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37750. for (col = 0; col <= precision.w; col++) {
  37751. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37752. position.y = 0;
  37753. positions.push(position.x, position.y, position.z);
  37754. normals.push(normal.x, normal.y, normal.z);
  37755. uvs.push(col / precision.w, row / precision.h);
  37756. }
  37757. }
  37758. }
  37759. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37760. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37761. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37762. }
  37763. }
  37764. // Result
  37765. var vertexData = new VertexData();
  37766. vertexData.indices = indices;
  37767. vertexData.positions = positions;
  37768. vertexData.normals = normals;
  37769. vertexData.uvs = uvs;
  37770. return vertexData;
  37771. };
  37772. /**
  37773. * Creates the VertexData of the Ground designed from a heightmap
  37774. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37775. * * width the width (x direction) of the ground
  37776. * * height the height (z direction) of the ground
  37777. * * subdivisions the number of subdivisions per side
  37778. * * minHeight the minimum altitude on the ground, optional, default 0
  37779. * * maxHeight the maximum altitude on the ground, optional default 1
  37780. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37781. * * buffer the array holding the image color data
  37782. * * bufferWidth the width of image
  37783. * * bufferHeight the height of image
  37784. * @returns the VertexData of the Ground designed from a heightmap
  37785. */
  37786. VertexData.CreateGroundFromHeightMap = function (options) {
  37787. var indices = [];
  37788. var positions = [];
  37789. var normals = [];
  37790. var uvs = [];
  37791. var row, col;
  37792. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37793. // Vertices
  37794. for (row = 0; row <= options.subdivisions; row++) {
  37795. for (col = 0; col <= options.subdivisions; col++) {
  37796. var position = new BABYLON.Vector3((col * options.width) / options.subdivisions - (options.width / 2.0), 0, ((options.subdivisions - row) * options.height) / options.subdivisions - (options.height / 2.0));
  37797. // Compute height
  37798. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37799. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37800. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37801. var r = options.buffer[pos] / 255.0;
  37802. var g = options.buffer[pos + 1] / 255.0;
  37803. var b = options.buffer[pos + 2] / 255.0;
  37804. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37805. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37806. // Add vertex
  37807. positions.push(position.x, position.y, position.z);
  37808. normals.push(0, 0, 0);
  37809. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37810. }
  37811. }
  37812. // Indices
  37813. for (row = 0; row < options.subdivisions; row++) {
  37814. for (col = 0; col < options.subdivisions; col++) {
  37815. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37816. indices.push(col + 1 + row * (options.subdivisions + 1));
  37817. indices.push(col + row * (options.subdivisions + 1));
  37818. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37819. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37820. indices.push(col + row * (options.subdivisions + 1));
  37821. }
  37822. }
  37823. // Normals
  37824. VertexData.ComputeNormals(positions, indices, normals);
  37825. // Result
  37826. var vertexData = new VertexData();
  37827. vertexData.indices = indices;
  37828. vertexData.positions = positions;
  37829. vertexData.normals = normals;
  37830. vertexData.uvs = uvs;
  37831. return vertexData;
  37832. };
  37833. /**
  37834. * Creates the VertexData for a Plane
  37835. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37836. * * size sets the width and height of the plane to the value of size, optional default 1
  37837. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37838. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37839. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37840. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37841. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37842. * @returns the VertexData of the box
  37843. */
  37844. VertexData.CreatePlane = function (options) {
  37845. var indices = [];
  37846. var positions = [];
  37847. var normals = [];
  37848. var uvs = [];
  37849. var width = options.width || options.size || 1;
  37850. var height = options.height || options.size || 1;
  37851. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37852. // Vertices
  37853. var halfWidth = width / 2.0;
  37854. var halfHeight = height / 2.0;
  37855. positions.push(-halfWidth, -halfHeight, 0);
  37856. normals.push(0, 0, -1.0);
  37857. uvs.push(0.0, 0.0);
  37858. positions.push(halfWidth, -halfHeight, 0);
  37859. normals.push(0, 0, -1.0);
  37860. uvs.push(1.0, 0.0);
  37861. positions.push(halfWidth, halfHeight, 0);
  37862. normals.push(0, 0, -1.0);
  37863. uvs.push(1.0, 1.0);
  37864. positions.push(-halfWidth, halfHeight, 0);
  37865. normals.push(0, 0, -1.0);
  37866. uvs.push(0.0, 1.0);
  37867. // Indices
  37868. indices.push(0);
  37869. indices.push(1);
  37870. indices.push(2);
  37871. indices.push(0);
  37872. indices.push(2);
  37873. indices.push(3);
  37874. // Sides
  37875. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37876. // Result
  37877. var vertexData = new VertexData();
  37878. vertexData.indices = indices;
  37879. vertexData.positions = positions;
  37880. vertexData.normals = normals;
  37881. vertexData.uvs = uvs;
  37882. return vertexData;
  37883. };
  37884. /**
  37885. * Creates the VertexData of the Disc or regular Polygon
  37886. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37887. * * radius the radius of the disc, optional default 0.5
  37888. * * tessellation the number of polygon sides, optional, default 64
  37889. * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1
  37890. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37891. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37892. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37893. * @returns the VertexData of the box
  37894. */
  37895. VertexData.CreateDisc = function (options) {
  37896. var positions = new Array();
  37897. var indices = new Array();
  37898. var normals = new Array();
  37899. var uvs = new Array();
  37900. var radius = options.radius || 0.5;
  37901. var tessellation = options.tessellation || 64;
  37902. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37903. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37904. // positions and uvs
  37905. positions.push(0, 0, 0); // disc center first
  37906. uvs.push(0.5, 0.5);
  37907. var theta = Math.PI * 2 * arc;
  37908. var step = theta / tessellation;
  37909. for (var a = 0; a < theta; a += step) {
  37910. var x = Math.cos(a);
  37911. var y = Math.sin(a);
  37912. var u = (x + 1) / 2;
  37913. var v = (1 - y) / 2;
  37914. positions.push(radius * x, radius * y, 0);
  37915. uvs.push(u, v);
  37916. }
  37917. if (arc === 1) {
  37918. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37919. uvs.push(uvs[2], uvs[3]);
  37920. }
  37921. //indices
  37922. var vertexNb = positions.length / 3;
  37923. for (var i = 1; i < vertexNb - 1; i++) {
  37924. indices.push(i + 1, 0, i);
  37925. }
  37926. // result
  37927. VertexData.ComputeNormals(positions, indices, normals);
  37928. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37929. var vertexData = new VertexData();
  37930. vertexData.indices = indices;
  37931. vertexData.positions = positions;
  37932. vertexData.normals = normals;
  37933. vertexData.uvs = uvs;
  37934. return vertexData;
  37935. };
  37936. /**
  37937. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37938. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37939. * @param polygon a mesh built from polygonTriangulation.build()
  37940. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37941. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37942. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37943. * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37944. * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37945. * @returns the VertexData of the Polygon
  37946. */
  37947. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37948. var faceUV = fUV || new Array(3);
  37949. var faceColors = fColors;
  37950. var colors = [];
  37951. // default face colors and UV if undefined
  37952. for (var f = 0; f < 3; f++) {
  37953. if (faceUV[f] === undefined) {
  37954. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37955. }
  37956. if (faceColors && faceColors[f] === undefined) {
  37957. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37958. }
  37959. }
  37960. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37961. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37962. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37963. var indices = polygon.getIndices();
  37964. // set face colours and textures
  37965. var idx = 0;
  37966. var face = 0;
  37967. for (var index = 0; index < normals.length; index += 3) {
  37968. //Edge Face no. 1
  37969. if (Math.abs(normals[index + 1]) < 0.001) {
  37970. face = 1;
  37971. }
  37972. //Top Face no. 0
  37973. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37974. face = 0;
  37975. }
  37976. //Bottom Face no. 2
  37977. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37978. face = 2;
  37979. }
  37980. idx = index / 3;
  37981. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37982. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37983. if (faceColors) {
  37984. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37985. }
  37986. }
  37987. // sides
  37988. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37989. // Result
  37990. var vertexData = new VertexData();
  37991. vertexData.indices = indices;
  37992. vertexData.positions = positions;
  37993. vertexData.normals = normals;
  37994. vertexData.uvs = uvs;
  37995. if (faceColors) {
  37996. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37997. vertexData.colors = totalColors;
  37998. }
  37999. return vertexData;
  38000. };
  38001. /**
  38002. * Creates the VertexData of the IcoSphere
  38003. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38004. * * radius the radius of the IcoSphere, optional default 1
  38005. * * radiusX allows stretching in the x direction, optional, default radius
  38006. * * radiusY allows stretching in the y direction, optional, default radius
  38007. * * radiusZ allows stretching in the z direction, optional, default radius
  38008. * * flat when true creates a flat shaded mesh, optional, default true
  38009. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38010. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38011. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38012. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38013. * @returns the VertexData of the IcoSphere
  38014. */
  38015. VertexData.CreateIcoSphere = function (options) {
  38016. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38017. var radius = options.radius || 1;
  38018. var flat = (options.flat === undefined) ? true : options.flat;
  38019. var subdivisions = options.subdivisions || 4;
  38020. var radiusX = options.radiusX || radius;
  38021. var radiusY = options.radiusY || radius;
  38022. var radiusZ = options.radiusZ || radius;
  38023. var t = (1 + Math.sqrt(5)) / 2;
  38024. // 12 vertex x,y,z
  38025. var ico_vertices = [
  38026. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38027. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38028. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38029. ];
  38030. // index of 3 vertex makes a face of icopshere
  38031. var ico_indices = [
  38032. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38033. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38034. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38035. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38036. ];
  38037. // vertex for uv have aliased position, not for UV
  38038. var vertices_unalias_id = [
  38039. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38040. // vertex alias
  38041. 0,
  38042. 2,
  38043. 3,
  38044. 3,
  38045. 3,
  38046. 4,
  38047. 7,
  38048. 8,
  38049. 9,
  38050. 9,
  38051. 10,
  38052. 11 // 23: B + 12
  38053. ];
  38054. // uv as integer step (not pixels !)
  38055. var ico_vertexuv = [
  38056. 5, 1, 3, 1, 6, 4, 0, 0,
  38057. 5, 3, 4, 2, 2, 2, 4, 0,
  38058. 2, 0, 1, 1, 6, 0, 6, 2,
  38059. // vertex alias (for same vertex on different faces)
  38060. 0, 4,
  38061. 3, 3,
  38062. 4, 4,
  38063. 3, 1,
  38064. 4, 2,
  38065. 4, 4,
  38066. 0, 2,
  38067. 1, 1,
  38068. 2, 2,
  38069. 3, 3,
  38070. 1, 3,
  38071. 2, 4 // 23: B + 12
  38072. ];
  38073. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38074. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38075. // First island of uv mapping
  38076. // v = 4h 3+ 2
  38077. // v = 3h 9+ 4
  38078. // v = 2h 9+ 5 B
  38079. // v = 1h 9 1 0
  38080. // v = 0h 3 8 7 A
  38081. // u = 0 1 2 3 4 5 6 *a
  38082. // Second island of uv mapping
  38083. // v = 4h 0+ B+ 4+
  38084. // v = 3h A+ 2+
  38085. // v = 2h 7+ 6 3+
  38086. // v = 1h 8+ 3+
  38087. // v = 0h
  38088. // u = 0 1 2 3 4 5 6 *a
  38089. // Face layout on texture UV mapping
  38090. // ============
  38091. // \ 4 /\ 16 / ======
  38092. // \ / \ / /\ 11 /
  38093. // \/ 7 \/ / \ /
  38094. // ======= / 10 \/
  38095. // /\ 17 /\ =======
  38096. // / \ / \ \ 15 /\
  38097. // / 8 \/ 12 \ \ / \
  38098. // ============ \/ 6 \
  38099. // \ 18 /\ ============
  38100. // \ / \ \ 5 /\ 0 /
  38101. // \/ 13 \ \ / \ /
  38102. // ======= \/ 1 \/
  38103. // =============
  38104. // /\ 19 /\ 2 /\
  38105. // / \ / \ / \
  38106. // / 14 \/ 9 \/ 3 \
  38107. // ===================
  38108. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38109. var ustep = 138 / 1024;
  38110. var vstep = 239 / 1024;
  38111. var uoffset = 60 / 1024;
  38112. var voffset = 26 / 1024;
  38113. // Second island should have margin, not to touch the first island
  38114. // avoid any borderline artefact in pixel rounding
  38115. var island_u_offset = -40 / 1024;
  38116. var island_v_offset = +20 / 1024;
  38117. // face is either island 0 or 1 :
  38118. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38119. var island = [
  38120. 0, 0, 0, 0, 1,
  38121. 0, 0, 1, 1, 0,
  38122. 0, 0, 1, 1, 0,
  38123. 0, 1, 1, 1, 0 // 15 - 19
  38124. ];
  38125. var indices = new Array();
  38126. var positions = new Array();
  38127. var normals = new Array();
  38128. var uvs = new Array();
  38129. var current_indice = 0;
  38130. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38131. var face_vertex_pos = new Array(3);
  38132. var face_vertex_uv = new Array(3);
  38133. var v012;
  38134. for (v012 = 0; v012 < 3; v012++) {
  38135. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38136. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38137. }
  38138. // create all with normals
  38139. for (var face = 0; face < 20; face++) {
  38140. // 3 vertex per face
  38141. for (v012 = 0; v012 < 3; v012++) {
  38142. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38143. var v_id = ico_indices[3 * face + v012];
  38144. // vertex have 3D position (x,y,z)
  38145. face_vertex_pos[v012].copyFromFloats(ico_vertices[3 * vertices_unalias_id[v_id]], ico_vertices[3 * vertices_unalias_id[v_id] + 1], ico_vertices[3 * vertices_unalias_id[v_id] + 2]);
  38146. // Normalize to get normal, then scale to radius
  38147. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38148. // uv Coordinates from vertex ID
  38149. face_vertex_uv[v012].copyFromFloats(ico_vertexuv[2 * v_id] * ustep + uoffset + island[face] * island_u_offset, ico_vertexuv[2 * v_id + 1] * vstep + voffset + island[face] * island_v_offset);
  38150. }
  38151. // Subdivide the face (interpolate pos, norm, uv)
  38152. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38153. // - norm is linear interpolation of vertex corner normal
  38154. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38155. // - uv is linear interpolation
  38156. //
  38157. // Topology is as below for sub-divide by 2
  38158. // vertex shown as v0,v1,v2
  38159. // interp index is i1 to progress in range [v0,v1[
  38160. // interp index is i2 to progress in range [v0,v2[
  38161. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38162. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38163. //
  38164. //
  38165. // i2 v2
  38166. // ^ ^
  38167. // / / \
  38168. // / / \
  38169. // / / \
  38170. // / / (0,1) \
  38171. // / #---------\
  38172. // / / \ (0,0)'/ \
  38173. // / / \ / \
  38174. // / / \ / \
  38175. // / / (0,0) \ / (1,0) \
  38176. // / #---------#---------\
  38177. // v0 v1
  38178. //
  38179. // --------------------> i1
  38180. //
  38181. // interp of (i1,i2):
  38182. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38183. // along i1 : lerp(x0,x1, i1/(S-i2))
  38184. //
  38185. // centroid of triangle is needed to get help normal computation
  38186. // (c1,c2) are used for centroid location
  38187. var interp_vertex = function (i1, i2, c1, c2) {
  38188. // vertex is interpolated from
  38189. // - face_vertex_pos[0..2]
  38190. // - face_vertex_uv[0..2]
  38191. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38192. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38193. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38194. pos_interp.normalize();
  38195. var vertex_normal;
  38196. if (flat) {
  38197. // in flat mode, recalculate normal as face centroid normal
  38198. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38199. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38200. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38201. }
  38202. else {
  38203. // in smooth mode, recalculate normal from each single vertex position
  38204. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38205. }
  38206. // Vertex normal need correction due to X,Y,Z radius scaling
  38207. vertex_normal.x /= radiusX;
  38208. vertex_normal.y /= radiusY;
  38209. vertex_normal.z /= radiusZ;
  38210. vertex_normal.normalize();
  38211. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38212. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38213. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38214. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38215. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38216. uvs.push(uv_interp.x, uv_interp.y);
  38217. // push each vertex has member of a face
  38218. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38219. indices.push(current_indice);
  38220. current_indice++;
  38221. };
  38222. for (var i2 = 0; i2 < subdivisions; i2++) {
  38223. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38224. // face : (i1,i2) for /\ :
  38225. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38226. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38227. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38228. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38229. if (i1 + i2 + 1 < subdivisions) {
  38230. // face : (i1,i2)' for \/ :
  38231. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38232. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38233. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38234. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38235. }
  38236. }
  38237. }
  38238. }
  38239. // Sides
  38240. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38241. // Result
  38242. var vertexData = new VertexData();
  38243. vertexData.indices = indices;
  38244. vertexData.positions = positions;
  38245. vertexData.normals = normals;
  38246. vertexData.uvs = uvs;
  38247. return vertexData;
  38248. };
  38249. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38250. /**
  38251. * Creates the VertexData for a Polyhedron
  38252. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38253. * * type provided types are:
  38254. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38255. * * 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)
  38256. * * size the size of the IcoSphere, optional default 1
  38257. * * sizeX allows stretching in the x direction, optional, default size
  38258. * * sizeY allows stretching in the y direction, optional, default size
  38259. * * sizeZ allows stretching in the z direction, optional, default size
  38260. * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor
  38261. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38262. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38263. * * flat when true creates a flat shaded mesh, optional, default true
  38264. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38265. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38266. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38267. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38268. * @returns the VertexData of the Polyhedron
  38269. */
  38270. VertexData.CreatePolyhedron = function (options) {
  38271. // provided polyhedron types :
  38272. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38273. // 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)
  38274. var polyhedra = [];
  38275. polyhedra[0] = { vertex: [[0, 0, 1.732051], [1.632993, 0, -0.5773503], [-0.8164966, 1.414214, -0.5773503], [-0.8164966, -1.414214, -0.5773503]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]] };
  38276. polyhedra[1] = { vertex: [[0, 0, 1.414214], [1.414214, 0, 0], [0, 1.414214, 0], [-1.414214, 0, 0], [0, -1.414214, 0], [0, 0, -1.414214]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [1, 4, 5], [1, 5, 2], [2, 5, 3], [3, 5, 4]] };
  38277. polyhedra[2] = {
  38278. vertex: [[0, 0, 1.070466], [0.7136442, 0, 0.7978784], [-0.3568221, 0.618034, 0.7978784], [-0.3568221, -0.618034, 0.7978784], [0.7978784, 0.618034, 0.3568221], [0.7978784, -0.618034, 0.3568221], [-0.9341724, 0.381966, 0.3568221], [0.1362939, 1, 0.3568221], [0.1362939, -1, 0.3568221], [-0.9341724, -0.381966, 0.3568221], [0.9341724, 0.381966, -0.3568221], [0.9341724, -0.381966, -0.3568221], [-0.7978784, 0.618034, -0.3568221], [-0.1362939, 1, -0.3568221], [-0.1362939, -1, -0.3568221], [-0.7978784, -0.618034, -0.3568221], [0.3568221, 0.618034, -0.7978784], [0.3568221, -0.618034, -0.7978784], [-0.7136442, 0, -0.7978784], [0, 0, -1.070466]],
  38279. face: [[0, 1, 4, 7, 2], [0, 2, 6, 9, 3], [0, 3, 8, 5, 1], [1, 5, 11, 10, 4], [2, 7, 13, 12, 6], [3, 9, 15, 14, 8], [4, 10, 16, 13, 7], [5, 8, 14, 17, 11], [6, 12, 18, 15, 9], [10, 11, 17, 19, 16], [12, 13, 16, 19, 18], [14, 15, 18, 19, 17]]
  38280. };
  38281. polyhedra[3] = {
  38282. vertex: [[0, 0, 1.175571], [1.051462, 0, 0.5257311], [0.3249197, 1, 0.5257311], [-0.8506508, 0.618034, 0.5257311], [-0.8506508, -0.618034, 0.5257311], [0.3249197, -1, 0.5257311], [0.8506508, 0.618034, -0.5257311], [0.8506508, -0.618034, -0.5257311], [-0.3249197, 1, -0.5257311], [-1.051462, 0, -0.5257311], [-0.3249197, -1, -0.5257311], [0, 0, -1.175571]],
  38283. face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 5], [0, 5, 1], [1, 5, 7], [1, 7, 6], [1, 6, 2], [2, 6, 8], [2, 8, 3], [3, 8, 9], [3, 9, 4], [4, 9, 10], [4, 10, 5], [5, 10, 7], [6, 7, 11], [6, 11, 8], [7, 10, 11], [8, 11, 9], [9, 11, 10]]
  38284. };
  38285. polyhedra[4] = {
  38286. vertex: [[0, 0, 1.070722], [0.7148135, 0, 0.7971752], [-0.104682, 0.7071068, 0.7971752], [-0.6841528, 0.2071068, 0.7971752], [-0.104682, -0.7071068, 0.7971752], [0.6101315, 0.7071068, 0.5236279], [1.04156, 0.2071068, 0.1367736], [0.6101315, -0.7071068, 0.5236279], [-0.3574067, 1, 0.1367736], [-0.7888348, -0.5, 0.5236279], [-0.9368776, 0.5, 0.1367736], [-0.3574067, -1, 0.1367736], [0.3574067, 1, -0.1367736], [0.9368776, -0.5, -0.1367736], [0.7888348, 0.5, -0.5236279], [0.3574067, -1, -0.1367736], [-0.6101315, 0.7071068, -0.5236279], [-1.04156, -0.2071068, -0.1367736], [-0.6101315, -0.7071068, -0.5236279], [0.104682, 0.7071068, -0.7971752], [0.6841528, -0.2071068, -0.7971752], [0.104682, -0.7071068, -0.7971752], [-0.7148135, 0, -0.7971752], [0, 0, -1.070722]],
  38287. face: [[0, 2, 3], [1, 6, 5], [4, 9, 11], [7, 15, 13], [8, 16, 10], [12, 14, 19], [17, 22, 18], [20, 21, 23], [0, 1, 5, 2], [0, 3, 9, 4], [0, 4, 7, 1], [1, 7, 13, 6], [2, 5, 12, 8], [2, 8, 10, 3], [3, 10, 17, 9], [4, 11, 15, 7], [5, 6, 14, 12], [6, 13, 20, 14], [8, 12, 19, 16], [9, 17, 18, 11], [10, 16, 22, 17], [11, 18, 21, 15], [13, 15, 21, 20], [14, 20, 23, 19], [16, 19, 23, 22], [18, 22, 23, 21]]
  38288. };
  38289. polyhedra[5] = { vertex: [[0, 0, 1.322876], [1.309307, 0, 0.1889822], [-0.9819805, 0.8660254, 0.1889822], [0.1636634, -1.299038, 0.1889822], [0.3273268, 0.8660254, -0.9449112], [-0.8183171, -0.4330127, -0.9449112]], face: [[0, 3, 1], [2, 4, 5], [0, 1, 4, 2], [0, 2, 5, 3], [1, 3, 5, 4]] };
  38290. polyhedra[6] = { vertex: [[0, 0, 1.159953], [1.013464, 0, 0.5642542], [-0.3501431, 0.9510565, 0.5642542], [-0.7715208, -0.6571639, 0.5642542], [0.6633206, 0.9510565, -0.03144481], [0.8682979, -0.6571639, -0.3996071], [-1.121664, 0.2938926, -0.03144481], [-0.2348831, -1.063314, -0.3996071], [0.5181548, 0.2938926, -0.9953061], [-0.5850262, -0.112257, -0.9953061]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 9, 7], [5, 7, 9, 8], [0, 3, 7, 5, 1], [2, 4, 8, 9, 6]] };
  38291. polyhedra[7] = { vertex: [[0, 0, 1.118034], [0.8944272, 0, 0.6708204], [-0.2236068, 0.8660254, 0.6708204], [-0.7826238, -0.4330127, 0.6708204], [0.6708204, 0.8660254, 0.2236068], [1.006231, -0.4330127, -0.2236068], [-1.006231, 0.4330127, 0.2236068], [-0.6708204, -0.8660254, -0.2236068], [0.7826238, 0.4330127, -0.6708204], [0.2236068, -0.8660254, -0.6708204], [-0.8944272, 0, -0.6708204], [0, 0, -1.118034]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 10, 7], [5, 9, 11, 8], [7, 10, 11, 9], [0, 3, 7, 9, 5, 1], [2, 4, 8, 11, 10, 6]] };
  38292. polyhedra[8] = { vertex: [[-0.729665, 0.670121, 0.319155], [-0.655235, -0.29213, -0.754096], [-0.093922, -0.607123, 0.537818], [0.702196, 0.595691, 0.485187], [0.776626, -0.36656, -0.588064]], face: [[1, 4, 2], [0, 1, 2], [3, 0, 2], [4, 3, 2], [4, 1, 0, 3]] };
  38293. polyhedra[9] = { vertex: [[-0.868849, -0.100041, 0.61257], [-0.329458, 0.976099, 0.28078], [-0.26629, -0.013796, -0.477654], [-0.13392, -1.034115, 0.229829], [0.738834, 0.707117, -0.307018], [0.859683, -0.535264, -0.338508]], face: [[3, 0, 2], [5, 3, 2], [4, 5, 2], [1, 4, 2], [0, 1, 2], [0, 3, 5, 4, 1]] };
  38294. polyhedra[10] = { vertex: [[-0.610389, 0.243975, 0.531213], [-0.187812, -0.48795, -0.664016], [-0.187812, 0.9759, -0.664016], [0.187812, -0.9759, 0.664016], [0.798201, 0.243975, 0.132803]], face: [[1, 3, 0], [3, 4, 0], [3, 1, 4], [0, 2, 1], [0, 4, 2], [2, 4, 1]] };
  38295. polyhedra[11] = { vertex: [[-1.028778, 0.392027, -0.048786], [-0.640503, -0.646161, 0.621837], [-0.125162, -0.395663, -0.540059], [0.004683, 0.888447, -0.651988], [0.125161, 0.395663, 0.540059], [0.632925, -0.791376, 0.433102], [1.031672, 0.157063, -0.354165]], face: [[3, 2, 0], [2, 1, 0], [2, 5, 1], [0, 4, 3], [0, 1, 4], [4, 1, 5], [2, 3, 6], [3, 4, 6], [5, 2, 6], [4, 5, 6]] };
  38296. polyhedra[12] = { vertex: [[-0.669867, 0.334933, -0.529576], [-0.669867, 0.334933, 0.529577], [-0.4043, 1.212901, 0], [-0.334933, -0.669867, -0.529576], [-0.334933, -0.669867, 0.529577], [0.334933, 0.669867, -0.529576], [0.334933, 0.669867, 0.529577], [0.4043, -1.212901, 0], [0.669867, -0.334933, -0.529576], [0.669867, -0.334933, 0.529577]], face: [[8, 9, 7], [6, 5, 2], [3, 8, 7], [5, 0, 2], [4, 3, 7], [0, 1, 2], [9, 4, 7], [1, 6, 2], [9, 8, 5, 6], [8, 3, 0, 5], [3, 4, 1, 0], [4, 9, 6, 1]] };
  38297. polyhedra[13] = { vertex: [[-0.931836, 0.219976, -0.264632], [-0.636706, 0.318353, 0.692816], [-0.613483, -0.735083, -0.264632], [-0.326545, 0.979634, 0], [-0.318353, -0.636706, 0.692816], [-0.159176, 0.477529, -0.856368], [0.159176, -0.477529, -0.856368], [0.318353, 0.636706, 0.692816], [0.326545, -0.979634, 0], [0.613482, 0.735082, -0.264632], [0.636706, -0.318353, 0.692816], [0.931835, -0.219977, -0.264632]], face: [[11, 10, 8], [7, 9, 3], [6, 11, 8], [9, 5, 3], [2, 6, 8], [5, 0, 3], [4, 2, 8], [0, 1, 3], [10, 4, 8], [1, 7, 3], [10, 11, 9, 7], [11, 6, 5, 9], [6, 2, 0, 5], [2, 4, 1, 0], [4, 10, 7, 1]] };
  38298. polyhedra[14] = {
  38299. vertex: [[-0.93465, 0.300459, -0.271185], [-0.838689, -0.260219, -0.516017], [-0.711319, 0.717591, 0.128359], [-0.710334, -0.156922, 0.080946], [-0.599799, 0.556003, -0.725148], [-0.503838, -0.004675, -0.969981], [-0.487004, 0.26021, 0.48049], [-0.460089, -0.750282, -0.512622], [-0.376468, 0.973135, -0.325605], [-0.331735, -0.646985, 0.084342], [-0.254001, 0.831847, 0.530001], [-0.125239, -0.494738, -0.966586], [0.029622, 0.027949, 0.730817], [0.056536, -0.982543, -0.262295], [0.08085, 1.087391, 0.076037], [0.125583, -0.532729, 0.485984], [0.262625, 0.599586, 0.780328], [0.391387, -0.726999, -0.716259], [0.513854, -0.868287, 0.139347], [0.597475, 0.85513, 0.326364], [0.641224, 0.109523, 0.783723], [0.737185, -0.451155, 0.538891], [0.848705, -0.612742, -0.314616], [0.976075, 0.365067, 0.32976], [1.072036, -0.19561, 0.084927]],
  38300. face: [[15, 18, 21], [12, 20, 16], [6, 10, 2], [3, 0, 1], [9, 7, 13], [2, 8, 4, 0], [0, 4, 5, 1], [1, 5, 11, 7], [7, 11, 17, 13], [13, 17, 22, 18], [18, 22, 24, 21], [21, 24, 23, 20], [20, 23, 19, 16], [16, 19, 14, 10], [10, 14, 8, 2], [15, 9, 13, 18], [12, 15, 21, 20], [6, 12, 16, 10], [3, 6, 2, 0], [9, 3, 1, 7], [9, 15, 12, 6, 3], [22, 17, 11, 5, 4, 8, 14, 19, 23, 24]]
  38301. };
  38302. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38303. var size = options.size;
  38304. var sizeX = options.sizeX || size || 1;
  38305. var sizeY = options.sizeY || size || 1;
  38306. var sizeZ = options.sizeZ || size || 1;
  38307. var data = options.custom || polyhedra[type];
  38308. var nbfaces = data.face.length;
  38309. var faceUV = options.faceUV || new Array(nbfaces);
  38310. var faceColors = options.faceColors;
  38311. var flat = (options.flat === undefined) ? true : options.flat;
  38312. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38313. var positions = new Array();
  38314. var indices = new Array();
  38315. var normals = new Array();
  38316. var uvs = new Array();
  38317. var colors = new Array();
  38318. var index = 0;
  38319. var faceIdx = 0; // face cursor in the array "indexes"
  38320. var indexes = new Array();
  38321. var i = 0;
  38322. var f = 0;
  38323. var u, v, ang, x, y, tmp;
  38324. // default face colors and UV if undefined
  38325. if (flat) {
  38326. for (f = 0; f < nbfaces; f++) {
  38327. if (faceColors && faceColors[f] === undefined) {
  38328. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38329. }
  38330. if (faceUV && faceUV[f] === undefined) {
  38331. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38332. }
  38333. }
  38334. }
  38335. if (!flat) {
  38336. for (i = 0; i < data.vertex.length; i++) {
  38337. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38338. uvs.push(0, 0);
  38339. }
  38340. for (f = 0; f < nbfaces; f++) {
  38341. for (i = 0; i < data.face[f].length - 2; i++) {
  38342. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38343. }
  38344. }
  38345. }
  38346. else {
  38347. for (f = 0; f < nbfaces; f++) {
  38348. var fl = data.face[f].length; // number of vertices of the current face
  38349. ang = 2 * Math.PI / fl;
  38350. x = 0.5 * Math.tan(ang / 2);
  38351. y = 0.5;
  38352. // positions, uvs, colors
  38353. for (i = 0; i < fl; i++) {
  38354. // positions
  38355. positions.push(data.vertex[data.face[f][i]][0] * sizeX, data.vertex[data.face[f][i]][1] * sizeY, data.vertex[data.face[f][i]][2] * sizeZ);
  38356. indexes.push(index);
  38357. index++;
  38358. // uvs
  38359. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38360. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38361. uvs.push(u, v);
  38362. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38363. y = x * Math.sin(ang) + y * Math.cos(ang);
  38364. x = tmp;
  38365. // colors
  38366. if (faceColors) {
  38367. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38368. }
  38369. }
  38370. // indices from indexes
  38371. for (i = 0; i < fl - 2; i++) {
  38372. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38373. }
  38374. faceIdx += fl;
  38375. }
  38376. }
  38377. VertexData.ComputeNormals(positions, indices, normals);
  38378. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38379. var vertexData = new VertexData();
  38380. vertexData.positions = positions;
  38381. vertexData.indices = indices;
  38382. vertexData.normals = normals;
  38383. vertexData.uvs = uvs;
  38384. if (faceColors && flat) {
  38385. vertexData.colors = colors;
  38386. }
  38387. return vertexData;
  38388. };
  38389. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38390. /**
  38391. * Creates the VertexData for a TorusKnot
  38392. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38393. * * radius the radius of the torus knot, optional, default 2
  38394. * * tube the thickness of the tube, optional, default 0.5
  38395. * * radialSegments the number of sides on each tube segments, optional, default 32
  38396. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38397. * * p the number of windings around the z axis, optional, default 2
  38398. * * q the number of windings around the x axis, optional, default 3
  38399. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38400. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38401. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38402. * @returns the VertexData of the Torus Knot
  38403. */
  38404. VertexData.CreateTorusKnot = function (options) {
  38405. var indices = new Array();
  38406. var positions = new Array();
  38407. var normals = new Array();
  38408. var uvs = new Array();
  38409. var radius = options.radius || 2;
  38410. var tube = options.tube || 0.5;
  38411. var radialSegments = options.radialSegments || 32;
  38412. var tubularSegments = options.tubularSegments || 32;
  38413. var p = options.p || 2;
  38414. var q = options.q || 3;
  38415. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38416. // Helper
  38417. var getPos = function (angle) {
  38418. var cu = Math.cos(angle);
  38419. var su = Math.sin(angle);
  38420. var quOverP = q / p * angle;
  38421. var cs = Math.cos(quOverP);
  38422. var tx = radius * (2 + cs) * 0.5 * cu;
  38423. var ty = radius * (2 + cs) * su * 0.5;
  38424. var tz = radius * Math.sin(quOverP) * 0.5;
  38425. return new BABYLON.Vector3(tx, ty, tz);
  38426. };
  38427. // Vertices
  38428. var i;
  38429. var j;
  38430. for (i = 0; i <= radialSegments; i++) {
  38431. var modI = i % radialSegments;
  38432. var u = modI / radialSegments * 2 * p * Math.PI;
  38433. var p1 = getPos(u);
  38434. var p2 = getPos(u + 0.01);
  38435. var tang = p2.subtract(p1);
  38436. var n = p2.add(p1);
  38437. var bitan = BABYLON.Vector3.Cross(tang, n);
  38438. n = BABYLON.Vector3.Cross(bitan, tang);
  38439. bitan.normalize();
  38440. n.normalize();
  38441. for (j = 0; j < tubularSegments; j++) {
  38442. var modJ = j % tubularSegments;
  38443. var v = modJ / tubularSegments * 2 * Math.PI;
  38444. var cx = -tube * Math.cos(v);
  38445. var cy = tube * Math.sin(v);
  38446. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38447. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38448. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38449. uvs.push(i / radialSegments);
  38450. uvs.push(j / tubularSegments);
  38451. }
  38452. }
  38453. for (i = 0; i < radialSegments; i++) {
  38454. for (j = 0; j < tubularSegments; j++) {
  38455. var jNext = (j + 1) % tubularSegments;
  38456. var a = i * tubularSegments + j;
  38457. var b = (i + 1) * tubularSegments + j;
  38458. var c = (i + 1) * tubularSegments + jNext;
  38459. var d = i * tubularSegments + jNext;
  38460. indices.push(d);
  38461. indices.push(b);
  38462. indices.push(a);
  38463. indices.push(d);
  38464. indices.push(c);
  38465. indices.push(b);
  38466. }
  38467. }
  38468. // Normals
  38469. VertexData.ComputeNormals(positions, indices, normals);
  38470. // Sides
  38471. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38472. // Result
  38473. var vertexData = new VertexData();
  38474. vertexData.indices = indices;
  38475. vertexData.positions = positions;
  38476. vertexData.normals = normals;
  38477. vertexData.uvs = uvs;
  38478. return vertexData;
  38479. };
  38480. // Tools
  38481. /**
  38482. * Compute normals for given positions and indices
  38483. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38484. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38485. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38486. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38487. * * facetNormals : optional array of facet normals (vector3)
  38488. * * facetPositions : optional array of facet positions (vector3)
  38489. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38490. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38491. * * bInfo : optional bounding info, required for facetPartitioning computation
  38492. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38493. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38494. * * useRightHandedSystem: optional boolean to for right handed system computation
  38495. * * depthSort : optional boolean to enable the facet depth sort computation
  38496. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38497. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38498. */
  38499. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38500. // temporary scalar variables
  38501. var index = 0; // facet index
  38502. var p1p2x = 0.0; // p1p2 vector x coordinate
  38503. var p1p2y = 0.0; // p1p2 vector y coordinate
  38504. var p1p2z = 0.0; // p1p2 vector z coordinate
  38505. var p3p2x = 0.0; // p3p2 vector x coordinate
  38506. var p3p2y = 0.0; // p3p2 vector y coordinate
  38507. var p3p2z = 0.0; // p3p2 vector z coordinate
  38508. var faceNormalx = 0.0; // facet normal x coordinate
  38509. var faceNormaly = 0.0; // facet normal y coordinate
  38510. var faceNormalz = 0.0; // facet normal z coordinate
  38511. var length = 0.0; // facet normal length before normalization
  38512. var v1x = 0; // vector1 x index in the positions array
  38513. var v1y = 0; // vector1 y index in the positions array
  38514. var v1z = 0; // vector1 z index in the positions array
  38515. var v2x = 0; // vector2 x index in the positions array
  38516. var v2y = 0; // vector2 y index in the positions array
  38517. var v2z = 0; // vector2 z index in the positions array
  38518. var v3x = 0; // vector3 x index in the positions array
  38519. var v3y = 0; // vector3 y index in the positions array
  38520. var v3z = 0; // vector3 z index in the positions array
  38521. var computeFacetNormals = false;
  38522. var computeFacetPositions = false;
  38523. var computeFacetPartitioning = false;
  38524. var computeDepthSort = false;
  38525. var faceNormalSign = 1;
  38526. var ratio = 0;
  38527. var distanceTo = null;
  38528. if (options) {
  38529. computeFacetNormals = (options.facetNormals) ? true : false;
  38530. computeFacetPositions = (options.facetPositions) ? true : false;
  38531. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38532. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38533. ratio = options.ratio || 0;
  38534. computeDepthSort = (options.depthSort) ? true : false;
  38535. distanceTo = (options.distanceTo);
  38536. if (computeDepthSort) {
  38537. if (distanceTo === undefined) {
  38538. distanceTo = BABYLON.Vector3.Zero();
  38539. }
  38540. var depthSortedFacets = options.depthSortedFacets;
  38541. }
  38542. }
  38543. // facetPartitioning reinit if needed
  38544. var xSubRatio = 0;
  38545. var ySubRatio = 0;
  38546. var zSubRatio = 0;
  38547. var subSq = 0;
  38548. if (computeFacetPartitioning && options && options.bbSize) {
  38549. var ox = 0; // X partitioning index for facet position
  38550. var oy = 0; // Y partinioning index for facet position
  38551. var oz = 0; // Z partinioning index for facet position
  38552. var b1x = 0; // X partitioning index for facet v1 vertex
  38553. var b1y = 0; // Y partitioning index for facet v1 vertex
  38554. var b1z = 0; // z partitioning index for facet v1 vertex
  38555. var b2x = 0; // X partitioning index for facet v2 vertex
  38556. var b2y = 0; // Y partitioning index for facet v2 vertex
  38557. var b2z = 0; // Z partitioning index for facet v2 vertex
  38558. var b3x = 0; // X partitioning index for facet v3 vertex
  38559. var b3y = 0; // Y partitioning index for facet v3 vertex
  38560. var b3z = 0; // Z partitioning index for facet v3 vertex
  38561. var block_idx_o = 0; // facet barycenter block index
  38562. var block_idx_v1 = 0; // v1 vertex block index
  38563. var block_idx_v2 = 0; // v2 vertex block index
  38564. var block_idx_v3 = 0; // v3 vertex block index
  38565. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38566. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38567. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38568. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38569. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38570. subSq = options.subDiv.max * options.subDiv.max;
  38571. options.facetPartitioning.length = 0;
  38572. }
  38573. // reset the normals
  38574. for (index = 0; index < positions.length; index++) {
  38575. normals[index] = 0.0;
  38576. }
  38577. // Loop : 1 indice triplet = 1 facet
  38578. var nbFaces = (indices.length / 3) | 0;
  38579. for (index = 0; index < nbFaces; index++) {
  38580. // get the indexes of the coordinates of each vertex of the facet
  38581. v1x = indices[index * 3] * 3;
  38582. v1y = v1x + 1;
  38583. v1z = v1x + 2;
  38584. v2x = indices[index * 3 + 1] * 3;
  38585. v2y = v2x + 1;
  38586. v2z = v2x + 2;
  38587. v3x = indices[index * 3 + 2] * 3;
  38588. v3y = v3x + 1;
  38589. v3z = v3x + 2;
  38590. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38591. p1p2y = positions[v1y] - positions[v2y];
  38592. p1p2z = positions[v1z] - positions[v2z];
  38593. p3p2x = positions[v3x] - positions[v2x];
  38594. p3p2y = positions[v3y] - positions[v2y];
  38595. p3p2z = positions[v3z] - positions[v2z];
  38596. // compute the face normal with the cross product
  38597. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38598. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38599. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38600. // normalize this normal and store it in the array facetData
  38601. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38602. length = (length === 0) ? 1.0 : length;
  38603. faceNormalx /= length;
  38604. faceNormaly /= length;
  38605. faceNormalz /= length;
  38606. if (computeFacetNormals && options) {
  38607. options.facetNormals[index].x = faceNormalx;
  38608. options.facetNormals[index].y = faceNormaly;
  38609. options.facetNormals[index].z = faceNormalz;
  38610. }
  38611. if (computeFacetPositions && options) {
  38612. // compute and the facet barycenter coordinates in the array facetPositions
  38613. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38614. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38615. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38616. }
  38617. if (computeFacetPartitioning && options) {
  38618. // store the facet indexes in arrays in the main facetPartitioning array :
  38619. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38620. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38621. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38622. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38623. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38624. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38625. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38626. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38627. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38628. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38629. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38630. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38631. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38632. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38633. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38634. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38635. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38636. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38637. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38638. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38639. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38640. // push each facet index in each block containing the vertex
  38641. options.facetPartitioning[block_idx_v1].push(index);
  38642. if (block_idx_v2 != block_idx_v1) {
  38643. options.facetPartitioning[block_idx_v2].push(index);
  38644. }
  38645. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38646. options.facetPartitioning[block_idx_v3].push(index);
  38647. }
  38648. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38649. options.facetPartitioning[block_idx_o].push(index);
  38650. }
  38651. }
  38652. if (computeDepthSort && options && options.facetPositions) {
  38653. var dsf = depthSortedFacets[index];
  38654. dsf.ind = index * 3;
  38655. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38656. }
  38657. // compute the normals anyway
  38658. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38659. normals[v1y] += faceNormaly;
  38660. normals[v1z] += faceNormalz;
  38661. normals[v2x] += faceNormalx;
  38662. normals[v2y] += faceNormaly;
  38663. normals[v2z] += faceNormalz;
  38664. normals[v3x] += faceNormalx;
  38665. normals[v3y] += faceNormaly;
  38666. normals[v3z] += faceNormalz;
  38667. }
  38668. // last normalization of each normal
  38669. for (index = 0; index < normals.length / 3; index++) {
  38670. faceNormalx = normals[index * 3];
  38671. faceNormaly = normals[index * 3 + 1];
  38672. faceNormalz = normals[index * 3 + 2];
  38673. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38674. length = (length === 0) ? 1.0 : length;
  38675. faceNormalx /= length;
  38676. faceNormaly /= length;
  38677. faceNormalz /= length;
  38678. normals[index * 3] = faceNormalx;
  38679. normals[index * 3 + 1] = faceNormaly;
  38680. normals[index * 3 + 2] = faceNormalz;
  38681. }
  38682. };
  38683. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38684. var li = indices.length;
  38685. var ln = normals.length;
  38686. var i;
  38687. var n;
  38688. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38689. switch (sideOrientation) {
  38690. case BABYLON.Mesh.FRONTSIDE:
  38691. // nothing changed
  38692. break;
  38693. case BABYLON.Mesh.BACKSIDE:
  38694. var tmp;
  38695. // indices
  38696. for (i = 0; i < li; i += 3) {
  38697. tmp = indices[i];
  38698. indices[i] = indices[i + 2];
  38699. indices[i + 2] = tmp;
  38700. }
  38701. // normals
  38702. for (n = 0; n < ln; n++) {
  38703. normals[n] = -normals[n];
  38704. }
  38705. break;
  38706. case BABYLON.Mesh.DOUBLESIDE:
  38707. // positions
  38708. var lp = positions.length;
  38709. var l = lp / 3;
  38710. for (var p = 0; p < lp; p++) {
  38711. positions[lp + p] = positions[p];
  38712. }
  38713. // indices
  38714. for (i = 0; i < li; i += 3) {
  38715. indices[i + li] = indices[i + 2] + l;
  38716. indices[i + 1 + li] = indices[i + 1] + l;
  38717. indices[i + 2 + li] = indices[i] + l;
  38718. }
  38719. // normals
  38720. for (n = 0; n < ln; n++) {
  38721. normals[ln + n] = -normals[n];
  38722. }
  38723. // uvs
  38724. var lu = uvs.length;
  38725. var u = 0;
  38726. for (u = 0; u < lu; u++) {
  38727. uvs[u + lu] = uvs[u];
  38728. }
  38729. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38730. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38731. u = 0;
  38732. for (i = 0; i < lu / 2; i++) {
  38733. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38734. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38735. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38736. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38737. u += 2;
  38738. }
  38739. break;
  38740. }
  38741. };
  38742. /**
  38743. * Applies VertexData created from the imported parameters to the geometry
  38744. * @param parsedVertexData the parsed data from an imported file
  38745. * @param geometry the geometry to apply the VertexData to
  38746. */
  38747. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38748. var vertexData = new VertexData();
  38749. // positions
  38750. var positions = parsedVertexData.positions;
  38751. if (positions) {
  38752. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38753. }
  38754. // normals
  38755. var normals = parsedVertexData.normals;
  38756. if (normals) {
  38757. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38758. }
  38759. // tangents
  38760. var tangents = parsedVertexData.tangents;
  38761. if (tangents) {
  38762. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38763. }
  38764. // uvs
  38765. var uvs = parsedVertexData.uvs;
  38766. if (uvs) {
  38767. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38768. }
  38769. // uv2s
  38770. var uv2s = parsedVertexData.uv2s;
  38771. if (uv2s) {
  38772. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38773. }
  38774. // uv3s
  38775. var uv3s = parsedVertexData.uv3s;
  38776. if (uv3s) {
  38777. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38778. }
  38779. // uv4s
  38780. var uv4s = parsedVertexData.uv4s;
  38781. if (uv4s) {
  38782. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38783. }
  38784. // uv5s
  38785. var uv5s = parsedVertexData.uv5s;
  38786. if (uv5s) {
  38787. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38788. }
  38789. // uv6s
  38790. var uv6s = parsedVertexData.uv6s;
  38791. if (uv6s) {
  38792. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38793. }
  38794. // colors
  38795. var colors = parsedVertexData.colors;
  38796. if (colors) {
  38797. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38798. }
  38799. // matricesIndices
  38800. var matricesIndices = parsedVertexData.matricesIndices;
  38801. if (matricesIndices) {
  38802. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38803. }
  38804. // matricesWeights
  38805. var matricesWeights = parsedVertexData.matricesWeights;
  38806. if (matricesWeights) {
  38807. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38808. }
  38809. // indices
  38810. var indices = parsedVertexData.indices;
  38811. if (indices) {
  38812. vertexData.indices = indices;
  38813. }
  38814. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38815. };
  38816. return VertexData;
  38817. }());
  38818. BABYLON.VertexData = VertexData;
  38819. })(BABYLON || (BABYLON = {}));
  38820. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38821. var BABYLON;
  38822. (function (BABYLON) {
  38823. /**
  38824. * Class used to store geometry data (vertex buffers + index buffer)
  38825. */
  38826. var Geometry = /** @class */ (function () {
  38827. /**
  38828. * Creates a new geometry
  38829. * @param id defines the unique ID
  38830. * @param scene defines the hosting scene
  38831. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38832. * @param updatable defines if geometry must be updatable (false by default)
  38833. * @param mesh defines the mesh that will be associated with the geometry
  38834. */
  38835. function Geometry(id, scene, vertexData, updatable, mesh) {
  38836. if (updatable === void 0) { updatable = false; }
  38837. if (mesh === void 0) { mesh = null; }
  38838. /**
  38839. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38840. */
  38841. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38842. this._totalVertices = 0;
  38843. this._isDisposed = false;
  38844. this._indexBufferIsUpdatable = false;
  38845. this.id = id;
  38846. this._engine = scene.getEngine();
  38847. this._meshes = [];
  38848. this._scene = scene;
  38849. //Init vertex buffer cache
  38850. this._vertexBuffers = {};
  38851. this._indices = [];
  38852. this._updatable = updatable;
  38853. // vertexData
  38854. if (vertexData) {
  38855. this.setAllVerticesData(vertexData, updatable);
  38856. }
  38857. else {
  38858. this._totalVertices = 0;
  38859. this._indices = [];
  38860. }
  38861. if (this._engine.getCaps().vertexArrayObject) {
  38862. this._vertexArrayObjects = {};
  38863. }
  38864. // applyToMesh
  38865. if (mesh) {
  38866. if (mesh.getClassName() === "LinesMesh") {
  38867. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38868. this._updateExtend();
  38869. }
  38870. this.applyToMesh(mesh);
  38871. mesh.computeWorldMatrix(true);
  38872. }
  38873. }
  38874. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38875. /**
  38876. * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  38877. */
  38878. get: function () {
  38879. return this._boundingBias;
  38880. },
  38881. /**
  38882. * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  38883. */
  38884. set: function (value) {
  38885. if (this._boundingBias && this._boundingBias.equals(value)) {
  38886. return;
  38887. }
  38888. this._boundingBias = value.clone();
  38889. this._updateBoundingInfo(true, null);
  38890. },
  38891. enumerable: true,
  38892. configurable: true
  38893. });
  38894. /**
  38895. * Static function used to attach a new empty geometry to a mesh
  38896. * @param mesh defines the mesh to attach the geometry to
  38897. * @returns the new {BABYLON.Geometry}
  38898. */
  38899. Geometry.CreateGeometryForMesh = function (mesh) {
  38900. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38901. geometry.applyToMesh(mesh);
  38902. return geometry;
  38903. };
  38904. Object.defineProperty(Geometry.prototype, "extend", {
  38905. /**
  38906. * Gets the current extend of the geometry
  38907. */
  38908. get: function () {
  38909. return this._extend;
  38910. },
  38911. enumerable: true,
  38912. configurable: true
  38913. });
  38914. /**
  38915. * Gets the hosting scene
  38916. * @returns the hosting {BABYLON.Scene}
  38917. */
  38918. Geometry.prototype.getScene = function () {
  38919. return this._scene;
  38920. };
  38921. /**
  38922. * Gets the hosting engine
  38923. * @returns the hosting {BABYLON.Engine}
  38924. */
  38925. Geometry.prototype.getEngine = function () {
  38926. return this._engine;
  38927. };
  38928. /**
  38929. * Defines if the geometry is ready to use
  38930. * @returns true if the geometry is ready to be used
  38931. */
  38932. Geometry.prototype.isReady = function () {
  38933. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38934. };
  38935. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38936. /**
  38937. * Gets a value indicating that the geometry should not be serialized
  38938. */
  38939. get: function () {
  38940. for (var index = 0; index < this._meshes.length; index++) {
  38941. if (!this._meshes[index].doNotSerialize) {
  38942. return false;
  38943. }
  38944. }
  38945. return true;
  38946. },
  38947. enumerable: true,
  38948. configurable: true
  38949. });
  38950. /** @hidden */
  38951. Geometry.prototype._rebuild = function () {
  38952. if (this._vertexArrayObjects) {
  38953. this._vertexArrayObjects = {};
  38954. }
  38955. // Index buffer
  38956. if (this._meshes.length !== 0 && this._indices) {
  38957. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38958. }
  38959. // Vertex buffers
  38960. for (var key in this._vertexBuffers) {
  38961. var vertexBuffer = this._vertexBuffers[key];
  38962. vertexBuffer._rebuild();
  38963. }
  38964. };
  38965. /**
  38966. * Affects all gemetry data in one call
  38967. * @param vertexData defines the geometry data
  38968. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38969. */
  38970. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38971. vertexData.applyToGeometry(this, updatable);
  38972. this.notifyUpdate();
  38973. };
  38974. /**
  38975. * Set specific vertex data
  38976. * @param kind defines the data kind (Position, normal, etc...)
  38977. * @param data defines the vertex data to use
  38978. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38979. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38980. */
  38981. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38982. if (updatable === void 0) { updatable = false; }
  38983. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38984. this.setVerticesBuffer(buffer);
  38985. };
  38986. /**
  38987. * Removes a specific vertex data
  38988. * @param kind defines the data kind (Position, normal, etc...)
  38989. */
  38990. Geometry.prototype.removeVerticesData = function (kind) {
  38991. if (this._vertexBuffers[kind]) {
  38992. this._vertexBuffers[kind].dispose();
  38993. delete this._vertexBuffers[kind];
  38994. }
  38995. };
  38996. /**
  38997. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38998. * @param buffer defines the vertex buffer to use
  38999. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39000. */
  39001. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39002. if (totalVertices === void 0) { totalVertices = null; }
  39003. var kind = buffer.getKind();
  39004. if (this._vertexBuffers[kind]) {
  39005. this._vertexBuffers[kind].dispose();
  39006. }
  39007. this._vertexBuffers[kind] = buffer;
  39008. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39009. var data = buffer.getData();
  39010. if (totalVertices != null) {
  39011. this._totalVertices = totalVertices;
  39012. }
  39013. else {
  39014. if (data != null) {
  39015. this._totalVertices = data.length / (buffer.byteStride / 4);
  39016. }
  39017. }
  39018. this._updateExtend(data);
  39019. this._resetPointsArrayCache();
  39020. var meshes = this._meshes;
  39021. var numOfMeshes = meshes.length;
  39022. for (var index = 0; index < numOfMeshes; index++) {
  39023. var mesh = meshes[index];
  39024. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39025. mesh._createGlobalSubMesh(false);
  39026. mesh.computeWorldMatrix(true);
  39027. }
  39028. }
  39029. this.notifyUpdate(kind);
  39030. if (this._vertexArrayObjects) {
  39031. this._disposeVertexArrayObjects();
  39032. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39033. }
  39034. };
  39035. /**
  39036. * Update a specific vertex buffer
  39037. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39038. * It will do nothing if the buffer is not updatable
  39039. * @param kind defines the data kind (Position, normal, etc...)
  39040. * @param data defines the data to use
  39041. * @param offset defines the offset in the target buffer where to store the data
  39042. * @param useBytes set to true if the offset is in bytes
  39043. */
  39044. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39045. if (useBytes === void 0) { useBytes = false; }
  39046. var vertexBuffer = this.getVertexBuffer(kind);
  39047. if (!vertexBuffer) {
  39048. return;
  39049. }
  39050. vertexBuffer.updateDirectly(data, offset, useBytes);
  39051. this.notifyUpdate(kind);
  39052. };
  39053. /**
  39054. * Update a specific vertex buffer
  39055. * This function will create a new buffer if the current one is not updatable
  39056. * @param kind defines the data kind (Position, normal, etc...)
  39057. * @param data defines the data to use
  39058. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39059. */
  39060. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39061. if (updateExtends === void 0) { updateExtends = false; }
  39062. var vertexBuffer = this.getVertexBuffer(kind);
  39063. if (!vertexBuffer) {
  39064. return;
  39065. }
  39066. vertexBuffer.update(data);
  39067. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39068. this._updateBoundingInfo(updateExtends, data);
  39069. }
  39070. this.notifyUpdate(kind);
  39071. };
  39072. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39073. if (updateExtends) {
  39074. this._updateExtend(data);
  39075. }
  39076. var meshes = this._meshes;
  39077. var numOfMeshes = meshes.length;
  39078. this._resetPointsArrayCache();
  39079. for (var index = 0; index < numOfMeshes; index++) {
  39080. var mesh = meshes[index];
  39081. if (updateExtends) {
  39082. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39083. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39084. var subMesh = mesh.subMeshes[subIndex];
  39085. subMesh.refreshBoundingInfo();
  39086. }
  39087. }
  39088. }
  39089. };
  39090. /** @hidden */
  39091. Geometry.prototype._bind = function (effect, indexToBind) {
  39092. if (!effect) {
  39093. return;
  39094. }
  39095. if (indexToBind === undefined) {
  39096. indexToBind = this._indexBuffer;
  39097. }
  39098. var vbs = this.getVertexBuffers();
  39099. if (!vbs) {
  39100. return;
  39101. }
  39102. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39103. this._engine.bindBuffers(vbs, indexToBind, effect);
  39104. return;
  39105. }
  39106. // Using VAO
  39107. if (!this._vertexArrayObjects[effect.key]) {
  39108. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39109. }
  39110. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39111. };
  39112. /**
  39113. * Gets total number of vertices
  39114. * @returns the total number of vertices
  39115. */
  39116. Geometry.prototype.getTotalVertices = function () {
  39117. if (!this.isReady()) {
  39118. return 0;
  39119. }
  39120. return this._totalVertices;
  39121. };
  39122. /**
  39123. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39124. * @param kind defines the data kind (Position, normal, etc...)
  39125. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39126. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39127. * @returns a float array containing vertex data
  39128. */
  39129. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39130. var vertexBuffer = this.getVertexBuffer(kind);
  39131. if (!vertexBuffer) {
  39132. return null;
  39133. }
  39134. var data = vertexBuffer.getData();
  39135. if (!data) {
  39136. return null;
  39137. }
  39138. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39139. var count = this._totalVertices * vertexBuffer.getSize();
  39140. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39141. var copy_1 = new Array(count);
  39142. vertexBuffer.forEach(count, function (value, index) {
  39143. copy_1[index] = value;
  39144. });
  39145. return copy_1;
  39146. }
  39147. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39148. if (data instanceof Array) {
  39149. var offset = vertexBuffer.byteOffset / 4;
  39150. return BABYLON.Tools.Slice(data, offset, offset + count);
  39151. }
  39152. else if (data instanceof ArrayBuffer) {
  39153. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39154. }
  39155. else {
  39156. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39157. }
  39158. }
  39159. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39160. return BABYLON.Tools.Slice(data);
  39161. }
  39162. return data;
  39163. };
  39164. /**
  39165. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39166. * @param kind defines the data kind (Position, normal, etc...)
  39167. * @returns true if the vertex buffer with the specified kind is updatable
  39168. */
  39169. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39170. var vb = this._vertexBuffers[kind];
  39171. if (!vb) {
  39172. return false;
  39173. }
  39174. return vb.isUpdatable();
  39175. };
  39176. /**
  39177. * Gets a specific vertex buffer
  39178. * @param kind defines the data kind (Position, normal, etc...)
  39179. * @returns a {BABYLON.VertexBuffer}
  39180. */
  39181. Geometry.prototype.getVertexBuffer = function (kind) {
  39182. if (!this.isReady()) {
  39183. return null;
  39184. }
  39185. return this._vertexBuffers[kind];
  39186. };
  39187. /**
  39188. * Returns all vertex buffers
  39189. * @return an object holding all vertex buffers indexed by kind
  39190. */
  39191. Geometry.prototype.getVertexBuffers = function () {
  39192. if (!this.isReady()) {
  39193. return null;
  39194. }
  39195. return this._vertexBuffers;
  39196. };
  39197. /**
  39198. * Gets a boolean indicating if specific vertex buffer is present
  39199. * @param kind defines the data kind (Position, normal, etc...)
  39200. * @returns true if data is present
  39201. */
  39202. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39203. if (!this._vertexBuffers) {
  39204. if (this._delayInfo) {
  39205. return this._delayInfo.indexOf(kind) !== -1;
  39206. }
  39207. return false;
  39208. }
  39209. return this._vertexBuffers[kind] !== undefined;
  39210. };
  39211. /**
  39212. * Gets a list of all attached data kinds (Position, normal, etc...)
  39213. * @returns a list of string containing all kinds
  39214. */
  39215. Geometry.prototype.getVerticesDataKinds = function () {
  39216. var result = [];
  39217. var kind;
  39218. if (!this._vertexBuffers && this._delayInfo) {
  39219. for (kind in this._delayInfo) {
  39220. result.push(kind);
  39221. }
  39222. }
  39223. else {
  39224. for (kind in this._vertexBuffers) {
  39225. result.push(kind);
  39226. }
  39227. }
  39228. return result;
  39229. };
  39230. /**
  39231. * Update index buffer
  39232. * @param indices defines the indices to store in the index buffer
  39233. * @param offset defines the offset in the target buffer where to store the data
  39234. */
  39235. Geometry.prototype.updateIndices = function (indices, offset) {
  39236. if (!this._indexBuffer) {
  39237. return;
  39238. }
  39239. if (!this._indexBufferIsUpdatable) {
  39240. this.setIndices(indices, null, true);
  39241. }
  39242. else {
  39243. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39244. }
  39245. };
  39246. /**
  39247. * Creates a new index buffer
  39248. * @param indices defines the indices to store in the index buffer
  39249. * @param totalVertices defines the total number of vertices (could be null)
  39250. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39251. */
  39252. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39253. if (totalVertices === void 0) { totalVertices = null; }
  39254. if (updatable === void 0) { updatable = false; }
  39255. if (this._indexBuffer) {
  39256. this._engine._releaseBuffer(this._indexBuffer);
  39257. }
  39258. this._disposeVertexArrayObjects();
  39259. this._indices = indices;
  39260. this._indexBufferIsUpdatable = updatable;
  39261. if (this._meshes.length !== 0 && this._indices) {
  39262. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39263. }
  39264. if (totalVertices != undefined) { // including null and undefined
  39265. this._totalVertices = totalVertices;
  39266. }
  39267. var meshes = this._meshes;
  39268. var numOfMeshes = meshes.length;
  39269. for (var index = 0; index < numOfMeshes; index++) {
  39270. meshes[index]._createGlobalSubMesh(true);
  39271. }
  39272. this.notifyUpdate();
  39273. };
  39274. /**
  39275. * Return the total number of indices
  39276. * @returns the total number of indices
  39277. */
  39278. Geometry.prototype.getTotalIndices = function () {
  39279. if (!this.isReady()) {
  39280. return 0;
  39281. }
  39282. return this._indices.length;
  39283. };
  39284. /**
  39285. * Gets the index buffer array
  39286. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39287. * @returns the index buffer array
  39288. */
  39289. Geometry.prototype.getIndices = function (copyWhenShared) {
  39290. if (!this.isReady()) {
  39291. return null;
  39292. }
  39293. var orig = this._indices;
  39294. if (!copyWhenShared || this._meshes.length === 1) {
  39295. return orig;
  39296. }
  39297. else {
  39298. var len = orig.length;
  39299. var copy = [];
  39300. for (var i = 0; i < len; i++) {
  39301. copy.push(orig[i]);
  39302. }
  39303. return copy;
  39304. }
  39305. };
  39306. /**
  39307. * Gets the index buffer
  39308. * @return the index buffer
  39309. */
  39310. Geometry.prototype.getIndexBuffer = function () {
  39311. if (!this.isReady()) {
  39312. return null;
  39313. }
  39314. return this._indexBuffer;
  39315. };
  39316. /** @hidden */
  39317. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39318. if (effect === void 0) { effect = null; }
  39319. if (!effect || !this._vertexArrayObjects) {
  39320. return;
  39321. }
  39322. if (this._vertexArrayObjects[effect.key]) {
  39323. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39324. delete this._vertexArrayObjects[effect.key];
  39325. }
  39326. };
  39327. /**
  39328. * Release the associated resources for a specific mesh
  39329. * @param mesh defines the source mesh
  39330. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39331. */
  39332. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39333. var meshes = this._meshes;
  39334. var index = meshes.indexOf(mesh);
  39335. if (index === -1) {
  39336. return;
  39337. }
  39338. meshes.splice(index, 1);
  39339. mesh._geometry = null;
  39340. if (meshes.length === 0 && shouldDispose) {
  39341. this.dispose();
  39342. }
  39343. };
  39344. /**
  39345. * Apply current geometry to a given mesh
  39346. * @param mesh defines the mesh to apply geometry to
  39347. */
  39348. Geometry.prototype.applyToMesh = function (mesh) {
  39349. if (mesh._geometry === this) {
  39350. return;
  39351. }
  39352. var previousGeometry = mesh._geometry;
  39353. if (previousGeometry) {
  39354. previousGeometry.releaseForMesh(mesh);
  39355. }
  39356. var meshes = this._meshes;
  39357. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39358. mesh._geometry = this;
  39359. this._scene.pushGeometry(this);
  39360. meshes.push(mesh);
  39361. if (this.isReady()) {
  39362. this._applyToMesh(mesh);
  39363. }
  39364. else {
  39365. mesh._boundingInfo = this._boundingInfo;
  39366. }
  39367. };
  39368. Geometry.prototype._updateExtend = function (data) {
  39369. if (data === void 0) { data = null; }
  39370. if (!data) {
  39371. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39372. }
  39373. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39374. };
  39375. Geometry.prototype._applyToMesh = function (mesh) {
  39376. var numOfMeshes = this._meshes.length;
  39377. // vertexBuffers
  39378. for (var kind in this._vertexBuffers) {
  39379. if (numOfMeshes === 1) {
  39380. this._vertexBuffers[kind].create();
  39381. }
  39382. var buffer = this._vertexBuffers[kind].getBuffer();
  39383. if (buffer)
  39384. buffer.references = numOfMeshes;
  39385. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39386. if (!this._extend) {
  39387. this._updateExtend();
  39388. }
  39389. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39390. mesh._createGlobalSubMesh(false);
  39391. //bounding info was just created again, world matrix should be applied again.
  39392. mesh._updateBoundingInfo();
  39393. }
  39394. }
  39395. // indexBuffer
  39396. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39397. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39398. }
  39399. if (this._indexBuffer) {
  39400. this._indexBuffer.references = numOfMeshes;
  39401. }
  39402. };
  39403. Geometry.prototype.notifyUpdate = function (kind) {
  39404. if (this.onGeometryUpdated) {
  39405. this.onGeometryUpdated(this, kind);
  39406. }
  39407. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39408. var mesh = _a[_i];
  39409. mesh._markSubMeshesAsAttributesDirty();
  39410. }
  39411. };
  39412. /**
  39413. * Load the geometry if it was flagged as delay loaded
  39414. * @param scene defines the hosting scene
  39415. * @param onLoaded defines a callback called when the geometry is loaded
  39416. */
  39417. Geometry.prototype.load = function (scene, onLoaded) {
  39418. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39419. return;
  39420. }
  39421. if (this.isReady()) {
  39422. if (onLoaded) {
  39423. onLoaded();
  39424. }
  39425. return;
  39426. }
  39427. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39428. this._queueLoad(scene, onLoaded);
  39429. };
  39430. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39431. var _this = this;
  39432. if (!this.delayLoadingFile) {
  39433. return;
  39434. }
  39435. scene._addPendingData(this);
  39436. scene._loadFile(this.delayLoadingFile, function (data) {
  39437. if (!_this._delayLoadingFunction) {
  39438. return;
  39439. }
  39440. _this._delayLoadingFunction(JSON.parse(data), _this);
  39441. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39442. _this._delayInfo = [];
  39443. scene._removePendingData(_this);
  39444. var meshes = _this._meshes;
  39445. var numOfMeshes = meshes.length;
  39446. for (var index = 0; index < numOfMeshes; index++) {
  39447. _this._applyToMesh(meshes[index]);
  39448. }
  39449. if (onLoaded) {
  39450. onLoaded();
  39451. }
  39452. }, undefined, true);
  39453. };
  39454. /**
  39455. * Invert the geometry to move from a right handed system to a left handed one.
  39456. */
  39457. Geometry.prototype.toLeftHanded = function () {
  39458. // Flip faces
  39459. var tIndices = this.getIndices(false);
  39460. if (tIndices != null && tIndices.length > 0) {
  39461. for (var i = 0; i < tIndices.length; i += 3) {
  39462. var tTemp = tIndices[i + 0];
  39463. tIndices[i + 0] = tIndices[i + 2];
  39464. tIndices[i + 2] = tTemp;
  39465. }
  39466. this.setIndices(tIndices);
  39467. }
  39468. // Negate position.z
  39469. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39470. if (tPositions != null && tPositions.length > 0) {
  39471. for (var i = 0; i < tPositions.length; i += 3) {
  39472. tPositions[i + 2] = -tPositions[i + 2];
  39473. }
  39474. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39475. }
  39476. // Negate normal.z
  39477. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39478. if (tNormals != null && tNormals.length > 0) {
  39479. for (var i = 0; i < tNormals.length; i += 3) {
  39480. tNormals[i + 2] = -tNormals[i + 2];
  39481. }
  39482. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39483. }
  39484. };
  39485. // Cache
  39486. /** @hidden */
  39487. Geometry.prototype._resetPointsArrayCache = function () {
  39488. this._positions = null;
  39489. };
  39490. /** @hidden */
  39491. Geometry.prototype._generatePointsArray = function () {
  39492. if (this._positions)
  39493. return true;
  39494. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39495. if (!data || data.length === 0) {
  39496. return false;
  39497. }
  39498. this._positions = [];
  39499. for (var index = 0; index < data.length; index += 3) {
  39500. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39501. }
  39502. return true;
  39503. };
  39504. /**
  39505. * Gets a value indicating if the geometry is disposed
  39506. * @returns true if the geometry was disposed
  39507. */
  39508. Geometry.prototype.isDisposed = function () {
  39509. return this._isDisposed;
  39510. };
  39511. Geometry.prototype._disposeVertexArrayObjects = function () {
  39512. if (this._vertexArrayObjects) {
  39513. for (var kind in this._vertexArrayObjects) {
  39514. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39515. }
  39516. this._vertexArrayObjects = {};
  39517. }
  39518. };
  39519. /**
  39520. * Free all associated resources
  39521. */
  39522. Geometry.prototype.dispose = function () {
  39523. var meshes = this._meshes;
  39524. var numOfMeshes = meshes.length;
  39525. var index;
  39526. for (index = 0; index < numOfMeshes; index++) {
  39527. this.releaseForMesh(meshes[index]);
  39528. }
  39529. this._meshes = [];
  39530. this._disposeVertexArrayObjects();
  39531. for (var kind in this._vertexBuffers) {
  39532. this._vertexBuffers[kind].dispose();
  39533. }
  39534. this._vertexBuffers = {};
  39535. this._totalVertices = 0;
  39536. if (this._indexBuffer) {
  39537. this._engine._releaseBuffer(this._indexBuffer);
  39538. }
  39539. this._indexBuffer = null;
  39540. this._indices = [];
  39541. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39542. this.delayLoadingFile = null;
  39543. this._delayLoadingFunction = null;
  39544. this._delayInfo = [];
  39545. this._boundingInfo = null;
  39546. this._scene.removeGeometry(this);
  39547. this._isDisposed = true;
  39548. };
  39549. /**
  39550. * Clone the current geometry into a new geometry
  39551. * @param id defines the unique ID of the new geometry
  39552. * @returns a new geometry object
  39553. */
  39554. Geometry.prototype.copy = function (id) {
  39555. var vertexData = new BABYLON.VertexData();
  39556. vertexData.indices = [];
  39557. var indices = this.getIndices();
  39558. if (indices) {
  39559. for (var index = 0; index < indices.length; index++) {
  39560. vertexData.indices.push(indices[index]);
  39561. }
  39562. }
  39563. var updatable = false;
  39564. var stopChecking = false;
  39565. var kind;
  39566. for (kind in this._vertexBuffers) {
  39567. // using slice() to make a copy of the array and not just reference it
  39568. var data = this.getVerticesData(kind);
  39569. if (data instanceof Float32Array) {
  39570. vertexData.set(new Float32Array(data), kind);
  39571. }
  39572. else {
  39573. vertexData.set(data.slice(0), kind);
  39574. }
  39575. if (!stopChecking) {
  39576. var vb = this.getVertexBuffer(kind);
  39577. if (vb) {
  39578. updatable = vb.isUpdatable();
  39579. stopChecking = !updatable;
  39580. }
  39581. }
  39582. }
  39583. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39584. geometry.delayLoadState = this.delayLoadState;
  39585. geometry.delayLoadingFile = this.delayLoadingFile;
  39586. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39587. for (kind in this._delayInfo) {
  39588. geometry._delayInfo = geometry._delayInfo || [];
  39589. geometry._delayInfo.push(kind);
  39590. }
  39591. // Bounding info
  39592. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39593. return geometry;
  39594. };
  39595. /**
  39596. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39597. * @return a JSON representation of the current geometry data (without the vertices data)
  39598. */
  39599. Geometry.prototype.serialize = function () {
  39600. var serializationObject = {};
  39601. serializationObject.id = this.id;
  39602. serializationObject.updatable = this._updatable;
  39603. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39604. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39605. }
  39606. return serializationObject;
  39607. };
  39608. Geometry.prototype.toNumberArray = function (origin) {
  39609. if (Array.isArray(origin)) {
  39610. return origin;
  39611. }
  39612. else {
  39613. return Array.prototype.slice.call(origin);
  39614. }
  39615. };
  39616. /**
  39617. * Serialize all vertices data into a JSON oject
  39618. * @returns a JSON representation of the current geometry data
  39619. */
  39620. Geometry.prototype.serializeVerticeData = function () {
  39621. var serializationObject = this.serialize();
  39622. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39623. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39624. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39625. serializationObject.positions._updatable = true;
  39626. }
  39627. }
  39628. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39629. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39630. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39631. serializationObject.normals._updatable = true;
  39632. }
  39633. }
  39634. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39635. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39636. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39637. serializationObject.tangets._updatable = true;
  39638. }
  39639. }
  39640. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39641. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39642. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39643. serializationObject.uvs._updatable = true;
  39644. }
  39645. }
  39646. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39647. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39648. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39649. serializationObject.uv2s._updatable = true;
  39650. }
  39651. }
  39652. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39653. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39654. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39655. serializationObject.uv3s._updatable = true;
  39656. }
  39657. }
  39658. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39659. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39660. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39661. serializationObject.uv4s._updatable = true;
  39662. }
  39663. }
  39664. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39665. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39666. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39667. serializationObject.uv5s._updatable = true;
  39668. }
  39669. }
  39670. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39671. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39672. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39673. serializationObject.uv6s._updatable = true;
  39674. }
  39675. }
  39676. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39677. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39678. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39679. serializationObject.colors._updatable = true;
  39680. }
  39681. }
  39682. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39683. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39684. serializationObject.matricesIndices._isExpanded = true;
  39685. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39686. serializationObject.matricesIndices._updatable = true;
  39687. }
  39688. }
  39689. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39690. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39691. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39692. serializationObject.matricesWeights._updatable = true;
  39693. }
  39694. }
  39695. serializationObject.indices = this.toNumberArray(this.getIndices());
  39696. return serializationObject;
  39697. };
  39698. // Statics
  39699. /**
  39700. * Extracts a clone of a mesh geometry
  39701. * @param mesh defines the source mesh
  39702. * @param id defines the unique ID of the new geometry object
  39703. * @returns the new geometry object
  39704. */
  39705. Geometry.ExtractFromMesh = function (mesh, id) {
  39706. var geometry = mesh._geometry;
  39707. if (!geometry) {
  39708. return null;
  39709. }
  39710. return geometry.copy(id);
  39711. };
  39712. /**
  39713. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39714. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39715. * Be aware Math.random() could cause collisions, but:
  39716. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  39717. * @returns a string containing a new GUID
  39718. */
  39719. Geometry.RandomId = function () {
  39720. return BABYLON.Tools.RandomId();
  39721. };
  39722. /** @hidden */
  39723. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39724. var scene = mesh.getScene();
  39725. // Geometry
  39726. var geometryId = parsedGeometry.geometryId;
  39727. if (geometryId) {
  39728. var geometry = scene.getGeometryByID(geometryId);
  39729. if (geometry) {
  39730. geometry.applyToMesh(mesh);
  39731. }
  39732. }
  39733. else if (parsedGeometry instanceof ArrayBuffer) {
  39734. var binaryInfo = mesh._binaryInfo;
  39735. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39736. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39737. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39738. }
  39739. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39740. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39741. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39742. }
  39743. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39744. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39745. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39746. }
  39747. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39748. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39749. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39750. }
  39751. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39752. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39753. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39754. }
  39755. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39756. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39757. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39758. }
  39759. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39760. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39761. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39762. }
  39763. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39764. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39765. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39766. }
  39767. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39768. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39769. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39770. }
  39771. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39772. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39773. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39774. }
  39775. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39776. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39777. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39778. }
  39779. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39780. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39781. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39782. }
  39783. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39784. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39785. mesh.setIndices(indicesData, null);
  39786. }
  39787. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39788. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39789. mesh.subMeshes = [];
  39790. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39791. var materialIndex = subMeshesData[(i * 5) + 0];
  39792. var verticesStart = subMeshesData[(i * 5) + 1];
  39793. var verticesCount = subMeshesData[(i * 5) + 2];
  39794. var indexStart = subMeshesData[(i * 5) + 3];
  39795. var indexCount = subMeshesData[(i * 5) + 4];
  39796. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39797. }
  39798. }
  39799. }
  39800. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39801. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39802. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39803. if (parsedGeometry.tangents) {
  39804. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39805. }
  39806. if (parsedGeometry.uvs) {
  39807. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39808. }
  39809. if (parsedGeometry.uvs2) {
  39810. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39811. }
  39812. if (parsedGeometry.uvs3) {
  39813. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39814. }
  39815. if (parsedGeometry.uvs4) {
  39816. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39817. }
  39818. if (parsedGeometry.uvs5) {
  39819. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39820. }
  39821. if (parsedGeometry.uvs6) {
  39822. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39823. }
  39824. if (parsedGeometry.colors) {
  39825. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39826. }
  39827. if (parsedGeometry.matricesIndices) {
  39828. if (!parsedGeometry.matricesIndices._isExpanded) {
  39829. var floatIndices = [];
  39830. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39831. var matricesIndex = parsedGeometry.matricesIndices[i];
  39832. floatIndices.push(matricesIndex & 0x000000FF);
  39833. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39834. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39835. floatIndices.push(matricesIndex >> 24);
  39836. }
  39837. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39838. }
  39839. else {
  39840. delete parsedGeometry.matricesIndices._isExpanded;
  39841. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39842. }
  39843. }
  39844. if (parsedGeometry.matricesIndicesExtra) {
  39845. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39846. var floatIndices = [];
  39847. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39848. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39849. floatIndices.push(matricesIndex & 0x000000FF);
  39850. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39851. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39852. floatIndices.push(matricesIndex >> 24);
  39853. }
  39854. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39855. }
  39856. else {
  39857. delete parsedGeometry.matricesIndices._isExpanded;
  39858. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39859. }
  39860. }
  39861. if (parsedGeometry.matricesWeights) {
  39862. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39863. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39864. }
  39865. if (parsedGeometry.matricesWeightsExtra) {
  39866. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39867. }
  39868. mesh.setIndices(parsedGeometry.indices, null);
  39869. }
  39870. // SubMeshes
  39871. if (parsedGeometry.subMeshes) {
  39872. mesh.subMeshes = [];
  39873. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39874. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39875. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39876. }
  39877. }
  39878. // Flat shading
  39879. if (mesh._shouldGenerateFlatShading) {
  39880. mesh.convertToFlatShadedMesh();
  39881. delete mesh._shouldGenerateFlatShading;
  39882. }
  39883. // Update
  39884. mesh.computeWorldMatrix(true);
  39885. // Octree
  39886. var sceneOctree = scene.selectionOctree;
  39887. if (sceneOctree !== undefined && sceneOctree !== null) {
  39888. sceneOctree.addMesh(mesh);
  39889. }
  39890. };
  39891. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39892. var epsilon = 1e-3;
  39893. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39894. return;
  39895. }
  39896. var noInfluenceBoneIndex = 0.0;
  39897. if (parsedGeometry.skeletonId > -1) {
  39898. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39899. if (!skeleton) {
  39900. return;
  39901. }
  39902. noInfluenceBoneIndex = skeleton.bones.length;
  39903. }
  39904. else {
  39905. return;
  39906. }
  39907. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39908. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39909. var matricesWeights = parsedGeometry.matricesWeights;
  39910. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39911. var influencers = parsedGeometry.numBoneInfluencer;
  39912. var size = matricesWeights.length;
  39913. for (var i = 0; i < size; i += 4) {
  39914. var weight = 0.0;
  39915. var firstZeroWeight = -1;
  39916. for (var j = 0; j < 4; j++) {
  39917. var w = matricesWeights[i + j];
  39918. weight += w;
  39919. if (w < epsilon && firstZeroWeight < 0) {
  39920. firstZeroWeight = j;
  39921. }
  39922. }
  39923. if (matricesWeightsExtra) {
  39924. for (var j = 0; j < 4; j++) {
  39925. var w = matricesWeightsExtra[i + j];
  39926. weight += w;
  39927. if (w < epsilon && firstZeroWeight < 0) {
  39928. firstZeroWeight = j + 4;
  39929. }
  39930. }
  39931. }
  39932. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39933. firstZeroWeight = influencers - 1;
  39934. }
  39935. if (weight > epsilon) {
  39936. var mweight = 1.0 / weight;
  39937. for (var j = 0; j < 4; j++) {
  39938. matricesWeights[i + j] *= mweight;
  39939. }
  39940. if (matricesWeightsExtra) {
  39941. for (var j = 0; j < 4; j++) {
  39942. matricesWeightsExtra[i + j] *= mweight;
  39943. }
  39944. }
  39945. }
  39946. else {
  39947. if (firstZeroWeight >= 4) {
  39948. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39949. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39950. }
  39951. else {
  39952. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39953. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39954. }
  39955. }
  39956. }
  39957. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39958. if (parsedGeometry.matricesWeightsExtra) {
  39959. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39960. }
  39961. };
  39962. /**
  39963. * Create a new geometry from persisted data (Using .babylon file format)
  39964. * @param parsedVertexData defines the persisted data
  39965. * @param scene defines the hosting scene
  39966. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39967. * @returns the new geometry object
  39968. */
  39969. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39970. if (scene.getGeometryByID(parsedVertexData.id)) {
  39971. return null; // null since geometry could be something else than a box...
  39972. }
  39973. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39974. if (BABYLON.Tags) {
  39975. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39976. }
  39977. if (parsedVertexData.delayLoadingFile) {
  39978. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39979. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39980. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39981. geometry._delayInfo = [];
  39982. if (parsedVertexData.hasUVs) {
  39983. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39984. }
  39985. if (parsedVertexData.hasUVs2) {
  39986. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39987. }
  39988. if (parsedVertexData.hasUVs3) {
  39989. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39990. }
  39991. if (parsedVertexData.hasUVs4) {
  39992. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39993. }
  39994. if (parsedVertexData.hasUVs5) {
  39995. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39996. }
  39997. if (parsedVertexData.hasUVs6) {
  39998. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39999. }
  40000. if (parsedVertexData.hasColors) {
  40001. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40002. }
  40003. if (parsedVertexData.hasMatricesIndices) {
  40004. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40005. }
  40006. if (parsedVertexData.hasMatricesWeights) {
  40007. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40008. }
  40009. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40010. }
  40011. else {
  40012. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40013. }
  40014. scene.pushGeometry(geometry, true);
  40015. return geometry;
  40016. };
  40017. return Geometry;
  40018. }());
  40019. BABYLON.Geometry = Geometry;
  40020. // Primitives
  40021. /// Abstract class
  40022. /**
  40023. * Abstract class used to provide common services for all typed geometries
  40024. * @hidden
  40025. */
  40026. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40027. __extends(_PrimitiveGeometry, _super);
  40028. /**
  40029. * Creates a new typed geometry
  40030. * @param id defines the unique ID of the geometry
  40031. * @param scene defines the hosting scene
  40032. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40033. * @param mesh defines the hosting mesh (can be null)
  40034. */
  40035. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40036. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40037. if (mesh === void 0) { mesh = null; }
  40038. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40039. _this._canBeRegenerated = _canBeRegenerated;
  40040. _this._beingRegenerated = true;
  40041. _this.regenerate();
  40042. _this._beingRegenerated = false;
  40043. return _this;
  40044. }
  40045. /**
  40046. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40047. * @returns true if the geometry can be regenerated
  40048. */
  40049. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40050. return this._canBeRegenerated;
  40051. };
  40052. /**
  40053. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40054. */
  40055. _PrimitiveGeometry.prototype.regenerate = function () {
  40056. if (!this._canBeRegenerated) {
  40057. return;
  40058. }
  40059. this._beingRegenerated = true;
  40060. this.setAllVerticesData(this._regenerateVertexData(), false);
  40061. this._beingRegenerated = false;
  40062. };
  40063. /**
  40064. * Clone the geometry
  40065. * @param id defines the unique ID of the new geometry
  40066. * @returns the new geometry
  40067. */
  40068. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40069. return _super.prototype.copy.call(this, id);
  40070. };
  40071. // overrides
  40072. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40073. if (!this._beingRegenerated) {
  40074. return;
  40075. }
  40076. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40077. };
  40078. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40079. if (!this._beingRegenerated) {
  40080. return;
  40081. }
  40082. _super.prototype.setVerticesData.call(this, kind, data, false);
  40083. };
  40084. // to override
  40085. /** @hidden */
  40086. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40087. throw new Error("Abstract method");
  40088. };
  40089. _PrimitiveGeometry.prototype.copy = function (id) {
  40090. throw new Error("Must be overriden in sub-classes.");
  40091. };
  40092. _PrimitiveGeometry.prototype.serialize = function () {
  40093. var serializationObject = _super.prototype.serialize.call(this);
  40094. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40095. return serializationObject;
  40096. };
  40097. return _PrimitiveGeometry;
  40098. }(Geometry));
  40099. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40100. /**
  40101. * Creates a ribbon geometry
  40102. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40103. */
  40104. var RibbonGeometry = /** @class */ (function (_super) {
  40105. __extends(RibbonGeometry, _super);
  40106. /**
  40107. * Creates a ribbon geometry
  40108. * @param id defines the unique ID of the geometry
  40109. * @param scene defines the hosting scene
  40110. * @param pathArray defines the array of paths to use
  40111. * @param closeArray defines if the last path and the first path must be joined
  40112. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40113. * @param offset defines the offset between points
  40114. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40115. * @param mesh defines the hosting mesh (can be null)
  40116. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40117. */
  40118. function RibbonGeometry(id, scene,
  40119. /**
  40120. * Defines the array of paths to use
  40121. */
  40122. pathArray,
  40123. /**
  40124. * Defines if the last and first points of each path in your pathArray must be joined
  40125. */
  40126. closeArray,
  40127. /**
  40128. * Defines if the last and first points of each path in your pathArray must be joined
  40129. */
  40130. closePath,
  40131. /**
  40132. * Defines the offset between points
  40133. */
  40134. offset, canBeRegenerated, mesh,
  40135. /**
  40136. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40137. */
  40138. side) {
  40139. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40140. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40141. _this.pathArray = pathArray;
  40142. _this.closeArray = closeArray;
  40143. _this.closePath = closePath;
  40144. _this.offset = offset;
  40145. _this.side = side;
  40146. return _this;
  40147. }
  40148. /** @hidden */
  40149. RibbonGeometry.prototype._regenerateVertexData = function () {
  40150. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40151. };
  40152. RibbonGeometry.prototype.copy = function (id) {
  40153. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40154. };
  40155. return RibbonGeometry;
  40156. }(_PrimitiveGeometry));
  40157. BABYLON.RibbonGeometry = RibbonGeometry;
  40158. /**
  40159. * Creates a box geometry
  40160. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40161. */
  40162. var BoxGeometry = /** @class */ (function (_super) {
  40163. __extends(BoxGeometry, _super);
  40164. /**
  40165. * Creates a box geometry
  40166. * @param id defines the unique ID of the geometry
  40167. * @param scene defines the hosting scene
  40168. * @param size defines the zise of the box (width, height and depth are the same)
  40169. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40170. * @param mesh defines the hosting mesh (can be null)
  40171. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40172. */
  40173. function BoxGeometry(id, scene,
  40174. /**
  40175. * Defines the zise of the box (width, height and depth are the same)
  40176. */
  40177. size, canBeRegenerated, mesh,
  40178. /**
  40179. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40180. */
  40181. side) {
  40182. if (mesh === void 0) { mesh = null; }
  40183. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40184. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40185. _this.size = size;
  40186. _this.side = side;
  40187. return _this;
  40188. }
  40189. BoxGeometry.prototype._regenerateVertexData = function () {
  40190. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40191. };
  40192. BoxGeometry.prototype.copy = function (id) {
  40193. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40194. };
  40195. BoxGeometry.prototype.serialize = function () {
  40196. var serializationObject = _super.prototype.serialize.call(this);
  40197. serializationObject.size = this.size;
  40198. return serializationObject;
  40199. };
  40200. BoxGeometry.Parse = function (parsedBox, scene) {
  40201. if (scene.getGeometryByID(parsedBox.id)) {
  40202. return null; // null since geometry could be something else than a box...
  40203. }
  40204. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40205. if (BABYLON.Tags) {
  40206. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40207. }
  40208. scene.pushGeometry(box, true);
  40209. return box;
  40210. };
  40211. return BoxGeometry;
  40212. }(_PrimitiveGeometry));
  40213. BABYLON.BoxGeometry = BoxGeometry;
  40214. /**
  40215. * Creates a sphere geometry
  40216. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40217. */
  40218. var SphereGeometry = /** @class */ (function (_super) {
  40219. __extends(SphereGeometry, _super);
  40220. /**
  40221. * Create a new sphere geometry
  40222. * @param id defines the unique ID of the geometry
  40223. * @param scene defines the hosting scene
  40224. * @param segments defines the number of segments to use to create the sphere
  40225. * @param diameter defines the diameter of the sphere
  40226. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40227. * @param mesh defines the hosting mesh (can be null)
  40228. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40229. */
  40230. function SphereGeometry(id, scene,
  40231. /**
  40232. * Defines the number of segments to use to create the sphere
  40233. */
  40234. segments,
  40235. /**
  40236. * Defines the diameter of the sphere
  40237. */
  40238. diameter, canBeRegenerated, mesh,
  40239. /**
  40240. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40241. */
  40242. side) {
  40243. if (mesh === void 0) { mesh = null; }
  40244. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40245. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40246. _this.segments = segments;
  40247. _this.diameter = diameter;
  40248. _this.side = side;
  40249. return _this;
  40250. }
  40251. SphereGeometry.prototype._regenerateVertexData = function () {
  40252. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40253. };
  40254. SphereGeometry.prototype.copy = function (id) {
  40255. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40256. };
  40257. SphereGeometry.prototype.serialize = function () {
  40258. var serializationObject = _super.prototype.serialize.call(this);
  40259. serializationObject.segments = this.segments;
  40260. serializationObject.diameter = this.diameter;
  40261. return serializationObject;
  40262. };
  40263. SphereGeometry.Parse = function (parsedSphere, scene) {
  40264. if (scene.getGeometryByID(parsedSphere.id)) {
  40265. return null; // null since geometry could be something else than a sphere...
  40266. }
  40267. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40268. if (BABYLON.Tags) {
  40269. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40270. }
  40271. scene.pushGeometry(sphere, true);
  40272. return sphere;
  40273. };
  40274. return SphereGeometry;
  40275. }(_PrimitiveGeometry));
  40276. BABYLON.SphereGeometry = SphereGeometry;
  40277. /**
  40278. * Creates a disc geometry
  40279. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40280. */
  40281. var DiscGeometry = /** @class */ (function (_super) {
  40282. __extends(DiscGeometry, _super);
  40283. /**
  40284. * Creates a new disc geometry
  40285. * @param id defines the unique ID of the geometry
  40286. * @param scene defines the hosting scene
  40287. * @param radius defines the radius of the disc
  40288. * @param tessellation defines the tesselation factor to apply to the disc
  40289. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40290. * @param mesh defines the hosting mesh (can be null)
  40291. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40292. */
  40293. function DiscGeometry(id, scene,
  40294. /**
  40295. * Defines the radius of the disc
  40296. */
  40297. radius,
  40298. /**
  40299. * Defines the tesselation factor to apply to the disc
  40300. */
  40301. tessellation, canBeRegenerated, mesh,
  40302. /**
  40303. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40304. */
  40305. side) {
  40306. if (mesh === void 0) { mesh = null; }
  40307. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40308. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40309. _this.radius = radius;
  40310. _this.tessellation = tessellation;
  40311. _this.side = side;
  40312. return _this;
  40313. }
  40314. DiscGeometry.prototype._regenerateVertexData = function () {
  40315. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40316. };
  40317. DiscGeometry.prototype.copy = function (id) {
  40318. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40319. };
  40320. return DiscGeometry;
  40321. }(_PrimitiveGeometry));
  40322. BABYLON.DiscGeometry = DiscGeometry;
  40323. /**
  40324. * Creates a new cylinder geometry
  40325. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40326. */
  40327. var CylinderGeometry = /** @class */ (function (_super) {
  40328. __extends(CylinderGeometry, _super);
  40329. /**
  40330. * Creates a new cylinder geometry
  40331. * @param id defines the unique ID of the geometry
  40332. * @param scene defines the hosting scene
  40333. * @param height defines the height of the cylinder
  40334. * @param diameterTop defines the diameter of the cylinder's top cap
  40335. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40336. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40337. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40338. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40339. * @param mesh defines the hosting mesh (can be null)
  40340. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40341. */
  40342. function CylinderGeometry(id, scene,
  40343. /**
  40344. * Defines the height of the cylinder
  40345. */
  40346. height,
  40347. /**
  40348. * Defines the diameter of the cylinder's top cap
  40349. */
  40350. diameterTop,
  40351. /**
  40352. * Defines the diameter of the cylinder's bottom cap
  40353. */
  40354. diameterBottom,
  40355. /**
  40356. * Defines the tessellation factor to apply to the cylinder
  40357. */
  40358. tessellation,
  40359. /**
  40360. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40361. */
  40362. subdivisions, canBeRegenerated, mesh,
  40363. /**
  40364. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40365. */
  40366. side) {
  40367. if (subdivisions === void 0) { subdivisions = 1; }
  40368. if (mesh === void 0) { mesh = null; }
  40369. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40370. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40371. _this.height = height;
  40372. _this.diameterTop = diameterTop;
  40373. _this.diameterBottom = diameterBottom;
  40374. _this.tessellation = tessellation;
  40375. _this.subdivisions = subdivisions;
  40376. _this.side = side;
  40377. return _this;
  40378. }
  40379. CylinderGeometry.prototype._regenerateVertexData = function () {
  40380. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40381. };
  40382. CylinderGeometry.prototype.copy = function (id) {
  40383. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40384. };
  40385. CylinderGeometry.prototype.serialize = function () {
  40386. var serializationObject = _super.prototype.serialize.call(this);
  40387. serializationObject.height = this.height;
  40388. serializationObject.diameterTop = this.diameterTop;
  40389. serializationObject.diameterBottom = this.diameterBottom;
  40390. serializationObject.tessellation = this.tessellation;
  40391. return serializationObject;
  40392. };
  40393. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40394. if (scene.getGeometryByID(parsedCylinder.id)) {
  40395. return null; // null since geometry could be something else than a cylinder...
  40396. }
  40397. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40398. if (BABYLON.Tags) {
  40399. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40400. }
  40401. scene.pushGeometry(cylinder, true);
  40402. return cylinder;
  40403. };
  40404. return CylinderGeometry;
  40405. }(_PrimitiveGeometry));
  40406. BABYLON.CylinderGeometry = CylinderGeometry;
  40407. /**
  40408. * Creates a new torus geometry
  40409. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40410. */
  40411. var TorusGeometry = /** @class */ (function (_super) {
  40412. __extends(TorusGeometry, _super);
  40413. /**
  40414. * Creates a new torus geometry
  40415. * @param id defines the unique ID of the geometry
  40416. * @param scene defines the hosting scene
  40417. * @param diameter defines the diameter of the torus
  40418. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40419. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40420. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40421. * @param mesh defines the hosting mesh (can be null)
  40422. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40423. */
  40424. function TorusGeometry(id, scene,
  40425. /**
  40426. * Defines the diameter of the torus
  40427. */
  40428. diameter,
  40429. /**
  40430. * Defines the thickness of the torus (ie. internal diameter)
  40431. */
  40432. thickness,
  40433. /**
  40434. * Defines the tesselation factor to apply to the torus
  40435. */
  40436. tessellation, canBeRegenerated, mesh,
  40437. /**
  40438. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40439. */
  40440. side) {
  40441. if (mesh === void 0) { mesh = null; }
  40442. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40443. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40444. _this.diameter = diameter;
  40445. _this.thickness = thickness;
  40446. _this.tessellation = tessellation;
  40447. _this.side = side;
  40448. return _this;
  40449. }
  40450. TorusGeometry.prototype._regenerateVertexData = function () {
  40451. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40452. };
  40453. TorusGeometry.prototype.copy = function (id) {
  40454. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40455. };
  40456. TorusGeometry.prototype.serialize = function () {
  40457. var serializationObject = _super.prototype.serialize.call(this);
  40458. serializationObject.diameter = this.diameter;
  40459. serializationObject.thickness = this.thickness;
  40460. serializationObject.tessellation = this.tessellation;
  40461. return serializationObject;
  40462. };
  40463. TorusGeometry.Parse = function (parsedTorus, scene) {
  40464. if (scene.getGeometryByID(parsedTorus.id)) {
  40465. return null; // null since geometry could be something else than a torus...
  40466. }
  40467. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40468. if (BABYLON.Tags) {
  40469. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40470. }
  40471. scene.pushGeometry(torus, true);
  40472. return torus;
  40473. };
  40474. return TorusGeometry;
  40475. }(_PrimitiveGeometry));
  40476. BABYLON.TorusGeometry = TorusGeometry;
  40477. /**
  40478. * Creates a new ground geometry
  40479. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40480. */
  40481. var GroundGeometry = /** @class */ (function (_super) {
  40482. __extends(GroundGeometry, _super);
  40483. /**
  40484. * Creates a new ground geometry
  40485. * @param id defines the unique ID of the geometry
  40486. * @param scene defines the hosting scene
  40487. * @param width defines the width of the ground
  40488. * @param height defines the height of the ground
  40489. * @param subdivisions defines the subdivisions to apply to the ground
  40490. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40491. * @param mesh defines the hosting mesh (can be null)
  40492. */
  40493. function GroundGeometry(id, scene,
  40494. /**
  40495. * Defines the width of the ground
  40496. */
  40497. width,
  40498. /**
  40499. * Defines the height of the ground
  40500. */
  40501. height,
  40502. /**
  40503. * Defines the subdivisions to apply to the ground
  40504. */
  40505. subdivisions, canBeRegenerated, mesh) {
  40506. if (mesh === void 0) { mesh = null; }
  40507. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40508. _this.width = width;
  40509. _this.height = height;
  40510. _this.subdivisions = subdivisions;
  40511. return _this;
  40512. }
  40513. GroundGeometry.prototype._regenerateVertexData = function () {
  40514. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40515. };
  40516. GroundGeometry.prototype.copy = function (id) {
  40517. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40518. };
  40519. GroundGeometry.prototype.serialize = function () {
  40520. var serializationObject = _super.prototype.serialize.call(this);
  40521. serializationObject.width = this.width;
  40522. serializationObject.height = this.height;
  40523. serializationObject.subdivisions = this.subdivisions;
  40524. return serializationObject;
  40525. };
  40526. GroundGeometry.Parse = function (parsedGround, scene) {
  40527. if (scene.getGeometryByID(parsedGround.id)) {
  40528. return null; // null since geometry could be something else than a ground...
  40529. }
  40530. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40531. if (BABYLON.Tags) {
  40532. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40533. }
  40534. scene.pushGeometry(ground, true);
  40535. return ground;
  40536. };
  40537. return GroundGeometry;
  40538. }(_PrimitiveGeometry));
  40539. BABYLON.GroundGeometry = GroundGeometry;
  40540. /**
  40541. * Creates a tiled ground geometry
  40542. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40543. */
  40544. var TiledGroundGeometry = /** @class */ (function (_super) {
  40545. __extends(TiledGroundGeometry, _super);
  40546. /**
  40547. * Creates a tiled ground geometry
  40548. * @param id defines the unique ID of the geometry
  40549. * @param scene defines the hosting scene
  40550. * @param xmin defines the minimum value on X axis
  40551. * @param zmin defines the minimum value on Z axis
  40552. * @param xmax defines the maximum value on X axis
  40553. * @param zmax defines the maximum value on Z axis
  40554. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40555. * @param precision defines the precision to use when computing the tiles
  40556. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40557. * @param mesh defines the hosting mesh (can be null)
  40558. */
  40559. function TiledGroundGeometry(id, scene,
  40560. /**
  40561. * Defines the minimum value on X axis
  40562. */
  40563. xmin,
  40564. /**
  40565. * Defines the minimum value on Z axis
  40566. */
  40567. zmin,
  40568. /**
  40569. * Defines the maximum value on X axis
  40570. */
  40571. xmax,
  40572. /**
  40573. * Defines the maximum value on Z axis
  40574. */
  40575. zmax,
  40576. /**
  40577. * Defines the subdivisions to apply to the ground
  40578. */
  40579. subdivisions,
  40580. /**
  40581. * Defines the precision to use when computing the tiles
  40582. */
  40583. precision, canBeRegenerated, mesh) {
  40584. if (mesh === void 0) { mesh = null; }
  40585. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40586. _this.xmin = xmin;
  40587. _this.zmin = zmin;
  40588. _this.xmax = xmax;
  40589. _this.zmax = zmax;
  40590. _this.subdivisions = subdivisions;
  40591. _this.precision = precision;
  40592. return _this;
  40593. }
  40594. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40595. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40596. };
  40597. TiledGroundGeometry.prototype.copy = function (id) {
  40598. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40599. };
  40600. return TiledGroundGeometry;
  40601. }(_PrimitiveGeometry));
  40602. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40603. /**
  40604. * Creates a plane geometry
  40605. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40606. */
  40607. var PlaneGeometry = /** @class */ (function (_super) {
  40608. __extends(PlaneGeometry, _super);
  40609. /**
  40610. * Creates a plane geometry
  40611. * @param id defines the unique ID of the geometry
  40612. * @param scene defines the hosting scene
  40613. * @param size defines the size of the plane (width === height)
  40614. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40615. * @param mesh defines the hosting mesh (can be null)
  40616. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40617. */
  40618. function PlaneGeometry(id, scene,
  40619. /**
  40620. * Defines the size of the plane (width === height)
  40621. */
  40622. size, canBeRegenerated, mesh,
  40623. /**
  40624. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40625. */
  40626. side) {
  40627. if (mesh === void 0) { mesh = null; }
  40628. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40629. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40630. _this.size = size;
  40631. _this.side = side;
  40632. return _this;
  40633. }
  40634. PlaneGeometry.prototype._regenerateVertexData = function () {
  40635. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40636. };
  40637. PlaneGeometry.prototype.copy = function (id) {
  40638. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40639. };
  40640. PlaneGeometry.prototype.serialize = function () {
  40641. var serializationObject = _super.prototype.serialize.call(this);
  40642. serializationObject.size = this.size;
  40643. return serializationObject;
  40644. };
  40645. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40646. if (scene.getGeometryByID(parsedPlane.id)) {
  40647. return null; // null since geometry could be something else than a ground...
  40648. }
  40649. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40650. if (BABYLON.Tags) {
  40651. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40652. }
  40653. scene.pushGeometry(plane, true);
  40654. return plane;
  40655. };
  40656. return PlaneGeometry;
  40657. }(_PrimitiveGeometry));
  40658. BABYLON.PlaneGeometry = PlaneGeometry;
  40659. /**
  40660. * Creates a torus knot geometry
  40661. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40662. */
  40663. var TorusKnotGeometry = /** @class */ (function (_super) {
  40664. __extends(TorusKnotGeometry, _super);
  40665. /**
  40666. * Creates a torus knot geometry
  40667. * @param id defines the unique ID of the geometry
  40668. * @param scene defines the hosting scene
  40669. * @param radius defines the radius of the torus knot
  40670. * @param tube defines the thickness of the torus knot tube
  40671. * @param radialSegments defines the number of radial segments
  40672. * @param tubularSegments defines the number of tubular segments
  40673. * @param p defines the first number of windings
  40674. * @param q defines the second number of windings
  40675. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40676. * @param mesh defines the hosting mesh (can be null)
  40677. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40678. */
  40679. function TorusKnotGeometry(id, scene,
  40680. /**
  40681. * Defines the radius of the torus knot
  40682. */
  40683. radius,
  40684. /**
  40685. * Defines the thickness of the torus knot tube
  40686. */
  40687. tube,
  40688. /**
  40689. * Defines the number of radial segments
  40690. */
  40691. radialSegments,
  40692. /**
  40693. * Defines the number of tubular segments
  40694. */
  40695. tubularSegments,
  40696. /**
  40697. * Defines the first number of windings
  40698. */
  40699. p,
  40700. /**
  40701. * Defines the second number of windings
  40702. */
  40703. q, canBeRegenerated, mesh,
  40704. /**
  40705. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40706. */
  40707. side) {
  40708. if (mesh === void 0) { mesh = null; }
  40709. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40710. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40711. _this.radius = radius;
  40712. _this.tube = tube;
  40713. _this.radialSegments = radialSegments;
  40714. _this.tubularSegments = tubularSegments;
  40715. _this.p = p;
  40716. _this.q = q;
  40717. _this.side = side;
  40718. return _this;
  40719. }
  40720. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40721. return BABYLON.VertexData.CreateTorusKnot({ radius: this.radius, tube: this.tube, radialSegments: this.radialSegments, tubularSegments: this.tubularSegments, p: this.p, q: this.q, sideOrientation: this.side });
  40722. };
  40723. TorusKnotGeometry.prototype.copy = function (id) {
  40724. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40725. };
  40726. TorusKnotGeometry.prototype.serialize = function () {
  40727. var serializationObject = _super.prototype.serialize.call(this);
  40728. serializationObject.radius = this.radius;
  40729. serializationObject.tube = this.tube;
  40730. serializationObject.radialSegments = this.radialSegments;
  40731. serializationObject.tubularSegments = this.tubularSegments;
  40732. serializationObject.p = this.p;
  40733. serializationObject.q = this.q;
  40734. return serializationObject;
  40735. };
  40736. ;
  40737. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40738. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40739. return null; // null since geometry could be something else than a ground...
  40740. }
  40741. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40742. if (BABYLON.Tags) {
  40743. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40744. }
  40745. scene.pushGeometry(torusKnot, true);
  40746. return torusKnot;
  40747. };
  40748. return TorusKnotGeometry;
  40749. }(_PrimitiveGeometry));
  40750. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40751. //}
  40752. })(BABYLON || (BABYLON = {}));
  40753. //# sourceMappingURL=babylon.geometry.js.map
  40754. var BABYLON;
  40755. (function (BABYLON) {
  40756. /**
  40757. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40758. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40759. */
  40760. var PostProcessManager = /** @class */ (function () {
  40761. /**
  40762. * Creates a new instance PostProcess
  40763. * @param scene The scene that the post process is associated with.
  40764. */
  40765. function PostProcessManager(scene) {
  40766. this._vertexBuffers = {};
  40767. this._scene = scene;
  40768. }
  40769. PostProcessManager.prototype._prepareBuffers = function () {
  40770. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40771. return;
  40772. }
  40773. // VBO
  40774. var vertices = [];
  40775. vertices.push(1, 1);
  40776. vertices.push(-1, 1);
  40777. vertices.push(-1, -1);
  40778. vertices.push(1, -1);
  40779. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40780. this._buildIndexBuffer();
  40781. };
  40782. PostProcessManager.prototype._buildIndexBuffer = function () {
  40783. // Indices
  40784. var indices = [];
  40785. indices.push(0);
  40786. indices.push(1);
  40787. indices.push(2);
  40788. indices.push(0);
  40789. indices.push(2);
  40790. indices.push(3);
  40791. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40792. };
  40793. /**
  40794. * Rebuilds the vertex buffers of the manager.
  40795. */
  40796. PostProcessManager.prototype._rebuild = function () {
  40797. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40798. if (!vb) {
  40799. return;
  40800. }
  40801. vb._rebuild();
  40802. this._buildIndexBuffer();
  40803. };
  40804. // Methods
  40805. /**
  40806. * Prepares a frame to be run through a post process.
  40807. * @param sourceTexture The input texture to the post procesess. (default: null)
  40808. * @param postProcesses An array of post processes to be run. (default: null)
  40809. * @returns True if the post processes were able to be run.
  40810. */
  40811. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40812. if (sourceTexture === void 0) { sourceTexture = null; }
  40813. if (postProcesses === void 0) { postProcesses = null; }
  40814. var camera = this._scene.activeCamera;
  40815. if (!camera) {
  40816. return false;
  40817. }
  40818. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40819. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40820. return false;
  40821. }
  40822. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40823. return true;
  40824. };
  40825. /**
  40826. * Manually render a set of post processes to a texture.
  40827. * @param postProcesses An array of post processes to be run.
  40828. * @param targetTexture The target texture to render to.
  40829. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40830. */
  40831. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40832. if (targetTexture === void 0) { targetTexture = null; }
  40833. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40834. var engine = this._scene.getEngine();
  40835. for (var index = 0; index < postProcesses.length; index++) {
  40836. if (index < postProcesses.length - 1) {
  40837. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40838. }
  40839. else {
  40840. if (targetTexture) {
  40841. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40842. }
  40843. else {
  40844. engine.restoreDefaultFramebuffer();
  40845. }
  40846. }
  40847. var pp = postProcesses[index];
  40848. var effect = pp.apply();
  40849. if (effect) {
  40850. pp.onBeforeRenderObservable.notifyObservers(effect);
  40851. // VBOs
  40852. this._prepareBuffers();
  40853. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40854. // Draw order
  40855. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40856. pp.onAfterRenderObservable.notifyObservers(effect);
  40857. }
  40858. }
  40859. // Restore depth buffer
  40860. engine.setDepthBuffer(true);
  40861. engine.setDepthWrite(true);
  40862. };
  40863. /**
  40864. * Finalize the result of the output of the postprocesses.
  40865. * @param doNotPresent If true the result will not be displayed to the screen.
  40866. * @param targetTexture The target texture to render to.
  40867. * @param faceIndex The index of the face to bind the target texture to.
  40868. * @param postProcesses The array of post processes to render.
  40869. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40870. */
  40871. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40872. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40873. var camera = this._scene.activeCamera;
  40874. if (!camera) {
  40875. return;
  40876. }
  40877. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40878. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40879. return;
  40880. }
  40881. var engine = this._scene.getEngine();
  40882. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40883. var pp = postProcesses[index];
  40884. if (index < len - 1) {
  40885. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40886. }
  40887. else {
  40888. if (targetTexture) {
  40889. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40890. pp._outputTexture = targetTexture;
  40891. }
  40892. else {
  40893. engine.restoreDefaultFramebuffer();
  40894. pp._outputTexture = null;
  40895. }
  40896. }
  40897. if (doNotPresent) {
  40898. break;
  40899. }
  40900. var effect = pp.apply();
  40901. if (effect) {
  40902. pp.onBeforeRenderObservable.notifyObservers(effect);
  40903. // VBOs
  40904. this._prepareBuffers();
  40905. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40906. // Draw order
  40907. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40908. pp.onAfterRenderObservable.notifyObservers(effect);
  40909. }
  40910. }
  40911. // Restore states
  40912. engine.setDepthBuffer(true);
  40913. engine.setDepthWrite(true);
  40914. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40915. };
  40916. /**
  40917. * Disposes of the post process manager.
  40918. */
  40919. PostProcessManager.prototype.dispose = function () {
  40920. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40921. if (buffer) {
  40922. buffer.dispose();
  40923. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40924. }
  40925. if (this._indexBuffer) {
  40926. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40927. this._indexBuffer = null;
  40928. }
  40929. };
  40930. return PostProcessManager;
  40931. }());
  40932. BABYLON.PostProcessManager = PostProcessManager;
  40933. })(BABYLON || (BABYLON = {}));
  40934. //# sourceMappingURL=babylon.postProcessManager.js.map
  40935. var BABYLON;
  40936. (function (BABYLON) {
  40937. /**
  40938. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40939. */
  40940. var PerformanceMonitor = /** @class */ (function () {
  40941. /**
  40942. * constructor
  40943. * @param frameSampleSize The number of samples required to saturate the sliding window
  40944. */
  40945. function PerformanceMonitor(frameSampleSize) {
  40946. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40947. this._enabled = true;
  40948. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40949. }
  40950. /**
  40951. * Samples current frame
  40952. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40953. */
  40954. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40955. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40956. if (!this._enabled)
  40957. return;
  40958. if (this._lastFrameTimeMs != null) {
  40959. var dt = timeMs - this._lastFrameTimeMs;
  40960. this._rollingFrameTime.add(dt);
  40961. }
  40962. this._lastFrameTimeMs = timeMs;
  40963. };
  40964. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40965. /**
  40966. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40967. * @return Average frame time in milliseconds
  40968. */
  40969. get: function () {
  40970. return this._rollingFrameTime.average;
  40971. },
  40972. enumerable: true,
  40973. configurable: true
  40974. });
  40975. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40976. /**
  40977. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40978. * @return Frame time variance in milliseconds squared
  40979. */
  40980. get: function () {
  40981. return this._rollingFrameTime.variance;
  40982. },
  40983. enumerable: true,
  40984. configurable: true
  40985. });
  40986. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40987. /**
  40988. * Returns the frame time of the most recent frame
  40989. * @return Frame time in milliseconds
  40990. */
  40991. get: function () {
  40992. return this._rollingFrameTime.history(0);
  40993. },
  40994. enumerable: true,
  40995. configurable: true
  40996. });
  40997. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40998. /**
  40999. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41000. * @return Framerate in frames per second
  41001. */
  41002. get: function () {
  41003. return 1000.0 / this._rollingFrameTime.average;
  41004. },
  41005. enumerable: true,
  41006. configurable: true
  41007. });
  41008. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41009. /**
  41010. * Returns the average framerate in frames per second using the most recent frame time
  41011. * @return Framerate in frames per second
  41012. */
  41013. get: function () {
  41014. var history = this._rollingFrameTime.history(0);
  41015. if (history === 0) {
  41016. return 0;
  41017. }
  41018. return 1000.0 / history;
  41019. },
  41020. enumerable: true,
  41021. configurable: true
  41022. });
  41023. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41024. /**
  41025. * Returns true if enough samples have been taken to completely fill the sliding window
  41026. * @return true if saturated
  41027. */
  41028. get: function () {
  41029. return this._rollingFrameTime.isSaturated();
  41030. },
  41031. enumerable: true,
  41032. configurable: true
  41033. });
  41034. /**
  41035. * Enables contributions to the sliding window sample set
  41036. */
  41037. PerformanceMonitor.prototype.enable = function () {
  41038. this._enabled = true;
  41039. };
  41040. /**
  41041. * Disables contributions to the sliding window sample set
  41042. * Samples will not be interpolated over the disabled period
  41043. */
  41044. PerformanceMonitor.prototype.disable = function () {
  41045. this._enabled = false;
  41046. //clear last sample to avoid interpolating over the disabled period when next enabled
  41047. this._lastFrameTimeMs = null;
  41048. };
  41049. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41050. /**
  41051. * Returns true if sampling is enabled
  41052. * @return true if enabled
  41053. */
  41054. get: function () {
  41055. return this._enabled;
  41056. },
  41057. enumerable: true,
  41058. configurable: true
  41059. });
  41060. /**
  41061. * Resets performance monitor
  41062. */
  41063. PerformanceMonitor.prototype.reset = function () {
  41064. //clear last sample to avoid interpolating over the disabled period when next enabled
  41065. this._lastFrameTimeMs = null;
  41066. //wipe record
  41067. this._rollingFrameTime.reset();
  41068. };
  41069. return PerformanceMonitor;
  41070. }());
  41071. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41072. /**
  41073. * RollingAverage
  41074. *
  41075. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41076. */
  41077. var RollingAverage = /** @class */ (function () {
  41078. /**
  41079. * constructor
  41080. * @param length The number of samples required to saturate the sliding window
  41081. */
  41082. function RollingAverage(length) {
  41083. this._samples = new Array(length);
  41084. this.reset();
  41085. }
  41086. /**
  41087. * Adds a sample to the sample set
  41088. * @param v The sample value
  41089. */
  41090. RollingAverage.prototype.add = function (v) {
  41091. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41092. var delta;
  41093. //we need to check if we've already wrapped round
  41094. if (this.isSaturated()) {
  41095. //remove bottom of stack from mean
  41096. var bottomValue = this._samples[this._pos];
  41097. delta = bottomValue - this.average;
  41098. this.average -= delta / (this._sampleCount - 1);
  41099. this._m2 -= delta * (bottomValue - this.average);
  41100. }
  41101. else {
  41102. this._sampleCount++;
  41103. }
  41104. //add new value to mean
  41105. delta = v - this.average;
  41106. this.average += delta / (this._sampleCount);
  41107. this._m2 += delta * (v - this.average);
  41108. //set the new variance
  41109. this.variance = this._m2 / (this._sampleCount - 1);
  41110. this._samples[this._pos] = v;
  41111. this._pos++;
  41112. this._pos %= this._samples.length; //positive wrap around
  41113. };
  41114. /**
  41115. * Returns previously added values or null if outside of history or outside the sliding window domain
  41116. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41117. * @return Value previously recorded with add() or null if outside of range
  41118. */
  41119. RollingAverage.prototype.history = function (i) {
  41120. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41121. return 0;
  41122. }
  41123. var i0 = this._wrapPosition(this._pos - 1.0);
  41124. return this._samples[this._wrapPosition(i0 - i)];
  41125. };
  41126. /**
  41127. * Returns true if enough samples have been taken to completely fill the sliding window
  41128. * @return true if sample-set saturated
  41129. */
  41130. RollingAverage.prototype.isSaturated = function () {
  41131. return this._sampleCount >= this._samples.length;
  41132. };
  41133. /**
  41134. * Resets the rolling average (equivalent to 0 samples taken so far)
  41135. */
  41136. RollingAverage.prototype.reset = function () {
  41137. this.average = 0;
  41138. this.variance = 0;
  41139. this._sampleCount = 0;
  41140. this._pos = 0;
  41141. this._m2 = 0;
  41142. };
  41143. /**
  41144. * Wraps a value around the sample range boundaries
  41145. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41146. * @return Wrapped position in sample range
  41147. */
  41148. RollingAverage.prototype._wrapPosition = function (i) {
  41149. var max = this._samples.length;
  41150. return ((i % max) + max) % max;
  41151. };
  41152. return RollingAverage;
  41153. }());
  41154. BABYLON.RollingAverage = RollingAverage;
  41155. })(BABYLON || (BABYLON = {}));
  41156. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41157. var BABYLON;
  41158. (function (BABYLON) {
  41159. /**
  41160. * This groups together the common properties used for image processing either in direct forward pass
  41161. * or through post processing effect depending on the use of the image processing pipeline in your scene
  41162. * or not.
  41163. */
  41164. var ImageProcessingConfiguration = /** @class */ (function () {
  41165. function ImageProcessingConfiguration() {
  41166. /**
  41167. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  41168. */
  41169. this.colorCurves = new BABYLON.ColorCurves();
  41170. this._colorCurvesEnabled = false;
  41171. this._colorGradingEnabled = false;
  41172. this._colorGradingWithGreenDepth = true;
  41173. this._colorGradingBGR = true;
  41174. this._exposure = 1.0;
  41175. this._toneMappingEnabled = false;
  41176. this._contrast = 1.0;
  41177. /**
  41178. * Vignette stretch size.
  41179. */
  41180. this.vignetteStretch = 0;
  41181. /**
  41182. * Vignette centre X Offset.
  41183. */
  41184. this.vignetteCentreX = 0;
  41185. /**
  41186. * Vignette centre Y Offset.
  41187. */
  41188. this.vignetteCentreY = 0;
  41189. /**
  41190. * Vignette weight or intensity of the vignette effect.
  41191. */
  41192. this.vignetteWeight = 1.5;
  41193. /**
  41194. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41195. * if vignetteEnabled is set to true.
  41196. */
  41197. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  41198. /**
  41199. * Camera field of view used by the Vignette effect.
  41200. */
  41201. this.vignetteCameraFov = 0.5;
  41202. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  41203. this._vignetteEnabled = false;
  41204. this._applyByPostProcess = false;
  41205. this._isEnabled = true;
  41206. /**
  41207. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  41208. */
  41209. this.onUpdateParameters = new BABYLON.Observable();
  41210. }
  41211. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  41212. /**
  41213. * Gets wether the color curves effect is enabled.
  41214. */
  41215. get: function () {
  41216. return this._colorCurvesEnabled;
  41217. },
  41218. /**
  41219. * Sets wether the color curves effect is enabled.
  41220. */
  41221. set: function (value) {
  41222. if (this._colorCurvesEnabled === value) {
  41223. return;
  41224. }
  41225. this._colorCurvesEnabled = value;
  41226. this._updateParameters();
  41227. },
  41228. enumerable: true,
  41229. configurable: true
  41230. });
  41231. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  41232. /**
  41233. * Gets wether the color grading effect is enabled.
  41234. */
  41235. get: function () {
  41236. return this._colorGradingEnabled;
  41237. },
  41238. /**
  41239. * Sets wether the color grading effect is enabled.
  41240. */
  41241. set: function (value) {
  41242. if (this._colorGradingEnabled === value) {
  41243. return;
  41244. }
  41245. this._colorGradingEnabled = value;
  41246. this._updateParameters();
  41247. },
  41248. enumerable: true,
  41249. configurable: true
  41250. });
  41251. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  41252. /**
  41253. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  41254. */
  41255. get: function () {
  41256. return this._colorGradingWithGreenDepth;
  41257. },
  41258. /**
  41259. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  41260. */
  41261. set: function (value) {
  41262. if (this._colorGradingWithGreenDepth === value) {
  41263. return;
  41264. }
  41265. this._colorGradingWithGreenDepth = value;
  41266. this._updateParameters();
  41267. },
  41268. enumerable: true,
  41269. configurable: true
  41270. });
  41271. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  41272. /**
  41273. * Gets wether the color grading texture contains BGR values.
  41274. */
  41275. get: function () {
  41276. return this._colorGradingBGR;
  41277. },
  41278. /**
  41279. * Sets wether the color grading texture contains BGR values.
  41280. */
  41281. set: function (value) {
  41282. if (this._colorGradingBGR === value) {
  41283. return;
  41284. }
  41285. this._colorGradingBGR = value;
  41286. this._updateParameters();
  41287. },
  41288. enumerable: true,
  41289. configurable: true
  41290. });
  41291. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  41292. /**
  41293. * Gets the Exposure used in the effect.
  41294. */
  41295. get: function () {
  41296. return this._exposure;
  41297. },
  41298. /**
  41299. * Sets the Exposure used in the effect.
  41300. */
  41301. set: function (value) {
  41302. if (this._exposure === value) {
  41303. return;
  41304. }
  41305. this._exposure = value;
  41306. this._updateParameters();
  41307. },
  41308. enumerable: true,
  41309. configurable: true
  41310. });
  41311. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  41312. /**
  41313. * Gets wether the tone mapping effect is enabled.
  41314. */
  41315. get: function () {
  41316. return this._toneMappingEnabled;
  41317. },
  41318. /**
  41319. * Sets wether the tone mapping effect is enabled.
  41320. */
  41321. set: function (value) {
  41322. if (this._toneMappingEnabled === value) {
  41323. return;
  41324. }
  41325. this._toneMappingEnabled = value;
  41326. this._updateParameters();
  41327. },
  41328. enumerable: true,
  41329. configurable: true
  41330. });
  41331. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  41332. /**
  41333. * Gets the contrast used in the effect.
  41334. */
  41335. get: function () {
  41336. return this._contrast;
  41337. },
  41338. /**
  41339. * Sets the contrast used in the effect.
  41340. */
  41341. set: function (value) {
  41342. if (this._contrast === value) {
  41343. return;
  41344. }
  41345. this._contrast = value;
  41346. this._updateParameters();
  41347. },
  41348. enumerable: true,
  41349. configurable: true
  41350. });
  41351. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  41352. /**
  41353. * Gets the vignette blend mode allowing different kind of effect.
  41354. */
  41355. get: function () {
  41356. return this._vignetteBlendMode;
  41357. },
  41358. /**
  41359. * Sets the vignette blend mode allowing different kind of effect.
  41360. */
  41361. set: function (value) {
  41362. if (this._vignetteBlendMode === value) {
  41363. return;
  41364. }
  41365. this._vignetteBlendMode = value;
  41366. this._updateParameters();
  41367. },
  41368. enumerable: true,
  41369. configurable: true
  41370. });
  41371. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  41372. /**
  41373. * Gets wether the vignette effect is enabled.
  41374. */
  41375. get: function () {
  41376. return this._vignetteEnabled;
  41377. },
  41378. /**
  41379. * Sets wether the vignette effect is enabled.
  41380. */
  41381. set: function (value) {
  41382. if (this._vignetteEnabled === value) {
  41383. return;
  41384. }
  41385. this._vignetteEnabled = value;
  41386. this._updateParameters();
  41387. },
  41388. enumerable: true,
  41389. configurable: true
  41390. });
  41391. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  41392. /**
  41393. * Gets wether the image processing is applied through a post process or not.
  41394. */
  41395. get: function () {
  41396. return this._applyByPostProcess;
  41397. },
  41398. /**
  41399. * Sets wether the image processing is applied through a post process or not.
  41400. */
  41401. set: function (value) {
  41402. if (this._applyByPostProcess === value) {
  41403. return;
  41404. }
  41405. this._applyByPostProcess = value;
  41406. this._updateParameters();
  41407. },
  41408. enumerable: true,
  41409. configurable: true
  41410. });
  41411. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  41412. /**
  41413. * Gets wether the image processing is enabled or not.
  41414. */
  41415. get: function () {
  41416. return this._isEnabled;
  41417. },
  41418. /**
  41419. * Sets wether the image processing is enabled or not.
  41420. */
  41421. set: function (value) {
  41422. if (this._isEnabled === value) {
  41423. return;
  41424. }
  41425. this._isEnabled = value;
  41426. this._updateParameters();
  41427. },
  41428. enumerable: true,
  41429. configurable: true
  41430. });
  41431. /**
  41432. * Method called each time the image processing information changes requires to recompile the effect.
  41433. */
  41434. ImageProcessingConfiguration.prototype._updateParameters = function () {
  41435. this.onUpdateParameters.notifyObservers(this);
  41436. };
  41437. ImageProcessingConfiguration.prototype.getClassName = function () {
  41438. return "ImageProcessingConfiguration";
  41439. };
  41440. /**
  41441. * Prepare the list of uniforms associated with the Image Processing effects.
  41442. * @param uniformsList The list of uniforms used in the effect
  41443. * @param defines the list of defines currently in use
  41444. */
  41445. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41446. if (defines.EXPOSURE) {
  41447. uniforms.push("exposureLinear");
  41448. }
  41449. if (defines.CONTRAST) {
  41450. uniforms.push("contrast");
  41451. }
  41452. if (defines.COLORGRADING) {
  41453. uniforms.push("colorTransformSettings");
  41454. }
  41455. if (defines.VIGNETTE) {
  41456. uniforms.push("vInverseScreenSize");
  41457. uniforms.push("vignetteSettings1");
  41458. uniforms.push("vignetteSettings2");
  41459. }
  41460. if (defines.COLORCURVES) {
  41461. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41462. }
  41463. };
  41464. /**
  41465. * Prepare the list of samplers associated with the Image Processing effects.
  41466. * @param uniformsList The list of uniforms used in the effect
  41467. * @param defines the list of defines currently in use
  41468. */
  41469. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41470. if (defines.COLORGRADING) {
  41471. samplersList.push("txColorTransform");
  41472. }
  41473. };
  41474. /**
  41475. * Prepare the list of defines associated to the shader.
  41476. * @param defines the list of defines to complete
  41477. */
  41478. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41479. if (forPostProcess === void 0) { forPostProcess = false; }
  41480. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41481. defines.VIGNETTE = false;
  41482. defines.TONEMAPPING = false;
  41483. defines.CONTRAST = false;
  41484. defines.EXPOSURE = false;
  41485. defines.COLORCURVES = false;
  41486. defines.COLORGRADING = false;
  41487. defines.COLORGRADING3D = false;
  41488. defines.IMAGEPROCESSING = false;
  41489. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41490. return;
  41491. }
  41492. defines.VIGNETTE = this.vignetteEnabled;
  41493. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41494. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41495. defines.TONEMAPPING = this.toneMappingEnabled;
  41496. defines.CONTRAST = (this.contrast !== 1.0);
  41497. defines.EXPOSURE = (this.exposure !== 1.0);
  41498. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41499. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41500. if (defines.COLORGRADING) {
  41501. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41502. }
  41503. else {
  41504. defines.COLORGRADING3D = false;
  41505. }
  41506. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41507. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41508. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41509. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41510. };
  41511. /**
  41512. * Returns true if all the image processing information are ready.
  41513. */
  41514. ImageProcessingConfiguration.prototype.isReady = function () {
  41515. // Color Grading texure can not be none blocking.
  41516. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41517. };
  41518. /**
  41519. * Binds the image processing to the shader.
  41520. * @param effect The effect to bind to
  41521. */
  41522. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41523. if (aspectRatio === void 0) { aspectRatio = 1; }
  41524. // Color Curves
  41525. if (this._colorCurvesEnabled && this.colorCurves) {
  41526. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41527. }
  41528. // Vignette
  41529. if (this._vignetteEnabled) {
  41530. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41531. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41532. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41533. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41534. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41535. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41536. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41537. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41538. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41539. var vignettePower = -2.0 * this.vignetteWeight;
  41540. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41541. }
  41542. // Exposure
  41543. effect.setFloat("exposureLinear", this.exposure);
  41544. // Contrast
  41545. effect.setFloat("contrast", this.contrast);
  41546. // Color transform settings
  41547. if (this.colorGradingTexture) {
  41548. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41549. var textureSize = this.colorGradingTexture.getSize().height;
  41550. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41551. 0.5 / textureSize, // textureOffset
  41552. textureSize, // textureSize
  41553. this.colorGradingTexture.level // weight
  41554. );
  41555. }
  41556. };
  41557. /**
  41558. * Clones the current image processing instance.
  41559. * @return The cloned image processing
  41560. */
  41561. ImageProcessingConfiguration.prototype.clone = function () {
  41562. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41563. };
  41564. /**
  41565. * Serializes the current image processing instance to a json representation.
  41566. * @return a JSON representation
  41567. */
  41568. ImageProcessingConfiguration.prototype.serialize = function () {
  41569. return BABYLON.SerializationHelper.Serialize(this);
  41570. };
  41571. /**
  41572. * Parses the image processing from a json representation.
  41573. * @param source the JSON source to parse
  41574. * @return The parsed image processing
  41575. */
  41576. ImageProcessingConfiguration.Parse = function (source) {
  41577. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41578. };
  41579. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41580. /**
  41581. * Used to apply the vignette as a mix with the pixel color.
  41582. */
  41583. get: function () {
  41584. return this._VIGNETTEMODE_MULTIPLY;
  41585. },
  41586. enumerable: true,
  41587. configurable: true
  41588. });
  41589. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41590. /**
  41591. * Used to apply the vignette as a replacement of the pixel color.
  41592. */
  41593. get: function () {
  41594. return this._VIGNETTEMODE_OPAQUE;
  41595. },
  41596. enumerable: true,
  41597. configurable: true
  41598. });
  41599. // Static constants associated to the image processing.
  41600. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41601. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41602. __decorate([
  41603. BABYLON.serializeAsColorCurves()
  41604. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41605. __decorate([
  41606. BABYLON.serialize()
  41607. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41608. __decorate([
  41609. BABYLON.serializeAsTexture()
  41610. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41611. __decorate([
  41612. BABYLON.serialize()
  41613. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41614. __decorate([
  41615. BABYLON.serialize()
  41616. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41617. __decorate([
  41618. BABYLON.serialize()
  41619. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41620. __decorate([
  41621. BABYLON.serialize()
  41622. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41623. __decorate([
  41624. BABYLON.serialize()
  41625. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41626. __decorate([
  41627. BABYLON.serialize()
  41628. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41629. __decorate([
  41630. BABYLON.serialize()
  41631. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41632. __decorate([
  41633. BABYLON.serialize()
  41634. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41635. __decorate([
  41636. BABYLON.serialize()
  41637. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41638. __decorate([
  41639. BABYLON.serialize()
  41640. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41641. __decorate([
  41642. BABYLON.serializeAsColor4()
  41643. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41644. __decorate([
  41645. BABYLON.serialize()
  41646. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41647. __decorate([
  41648. BABYLON.serialize()
  41649. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41650. __decorate([
  41651. BABYLON.serialize()
  41652. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41653. __decorate([
  41654. BABYLON.serialize()
  41655. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41656. __decorate([
  41657. BABYLON.serialize()
  41658. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41659. return ImageProcessingConfiguration;
  41660. }());
  41661. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41662. })(BABYLON || (BABYLON = {}));
  41663. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41664. var BABYLON;
  41665. (function (BABYLON) {
  41666. /**
  41667. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41668. * It can help converting any input color in a desired output one. This can then be used to create effects
  41669. * from sepia, black and white to sixties or futuristic rendering...
  41670. *
  41671. * The only supported format is currently 3dl.
  41672. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41673. */
  41674. var ColorGradingTexture = /** @class */ (function (_super) {
  41675. __extends(ColorGradingTexture, _super);
  41676. /**
  41677. * Instantiates a ColorGradingTexture from the following parameters.
  41678. *
  41679. * @param url The location of the color gradind data (currently only supporting 3dl)
  41680. * @param scene The scene the texture will be used in
  41681. */
  41682. function ColorGradingTexture(url, scene) {
  41683. var _this = _super.call(this, scene) || this;
  41684. if (!url) {
  41685. return _this;
  41686. }
  41687. _this._engine = scene.getEngine();
  41688. _this._textureMatrix = BABYLON.Matrix.Identity();
  41689. _this.name = url;
  41690. _this.url = url;
  41691. _this.hasAlpha = false;
  41692. _this.isCube = false;
  41693. _this.is3D = _this._engine.webGLVersion > 1;
  41694. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41695. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41696. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41697. _this.anisotropicFilteringLevel = 1;
  41698. _this._texture = _this._getFromCache(url, true);
  41699. if (!_this._texture) {
  41700. if (!scene.useDelayedTextureLoading) {
  41701. _this.loadTexture();
  41702. }
  41703. else {
  41704. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41705. }
  41706. }
  41707. return _this;
  41708. }
  41709. /**
  41710. * Returns the texture matrix used in most of the material.
  41711. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41712. */
  41713. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41714. return this._textureMatrix;
  41715. };
  41716. /**
  41717. * Occurs when the file being loaded is a .3dl LUT file.
  41718. */
  41719. ColorGradingTexture.prototype.load3dlTexture = function () {
  41720. var engine = this._engine;
  41721. var texture;
  41722. if (engine.webGLVersion === 1) {
  41723. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41724. }
  41725. else {
  41726. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41727. }
  41728. this._texture = texture;
  41729. var callback = function (text) {
  41730. if (typeof text !== "string") {
  41731. return;
  41732. }
  41733. var data = null;
  41734. var tempData = null;
  41735. var line;
  41736. var lines = text.split('\n');
  41737. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41738. var maxColor = 0;
  41739. for (var i = 0; i < lines.length; i++) {
  41740. line = lines[i];
  41741. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41742. continue;
  41743. if (line.indexOf('#') === 0)
  41744. continue;
  41745. var words = line.split(" ");
  41746. if (size === 0) {
  41747. // Number of space + one
  41748. size = words.length;
  41749. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41750. tempData = new Float32Array(size * size * size * 4);
  41751. continue;
  41752. }
  41753. if (size != 0) {
  41754. var r = Math.max(parseInt(words[0]), 0);
  41755. var g = Math.max(parseInt(words[1]), 0);
  41756. var b = Math.max(parseInt(words[2]), 0);
  41757. maxColor = Math.max(r, maxColor);
  41758. maxColor = Math.max(g, maxColor);
  41759. maxColor = Math.max(b, maxColor);
  41760. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41761. if (tempData) {
  41762. tempData[pixelStorageIndex + 0] = r;
  41763. tempData[pixelStorageIndex + 1] = g;
  41764. tempData[pixelStorageIndex + 2] = b;
  41765. }
  41766. pixelIndexSlice++;
  41767. if (pixelIndexSlice % size == 0) {
  41768. pixelIndexH++;
  41769. pixelIndexSlice = 0;
  41770. if (pixelIndexH % size == 0) {
  41771. pixelIndexW++;
  41772. pixelIndexH = 0;
  41773. }
  41774. }
  41775. }
  41776. }
  41777. if (tempData && data) {
  41778. for (var i = 0; i < tempData.length; i++) {
  41779. if (i > 0 && (i + 1) % 4 === 0) {
  41780. data[i] = 255;
  41781. }
  41782. else {
  41783. var value = tempData[i];
  41784. data[i] = (value / maxColor * 255);
  41785. }
  41786. }
  41787. }
  41788. if (texture.is3D) {
  41789. texture.updateSize(size, size, size);
  41790. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41791. }
  41792. else {
  41793. texture.updateSize(size * size, size);
  41794. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41795. }
  41796. };
  41797. var scene = this.getScene();
  41798. if (scene) {
  41799. scene._loadFile(this.url, callback);
  41800. }
  41801. else {
  41802. this._engine._loadFile(this.url, callback);
  41803. }
  41804. return this._texture;
  41805. };
  41806. /**
  41807. * Starts the loading process of the texture.
  41808. */
  41809. ColorGradingTexture.prototype.loadTexture = function () {
  41810. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41811. this.load3dlTexture();
  41812. }
  41813. };
  41814. /**
  41815. * Clones the color gradind texture.
  41816. */
  41817. ColorGradingTexture.prototype.clone = function () {
  41818. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41819. // Base texture
  41820. newTexture.level = this.level;
  41821. return newTexture;
  41822. };
  41823. /**
  41824. * Called during delayed load for textures.
  41825. */
  41826. ColorGradingTexture.prototype.delayLoad = function () {
  41827. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41828. return;
  41829. }
  41830. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41831. this._texture = this._getFromCache(this.url, true);
  41832. if (!this._texture) {
  41833. this.loadTexture();
  41834. }
  41835. };
  41836. /**
  41837. * Parses a color grading texture serialized by Babylon.
  41838. * @param parsedTexture The texture information being parsedTexture
  41839. * @param scene The scene to load the texture in
  41840. * @param rootUrl The root url of the data assets to load
  41841. * @return A color gradind texture
  41842. */
  41843. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41844. var texture = null;
  41845. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41846. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41847. texture.name = parsedTexture.name;
  41848. texture.level = parsedTexture.level;
  41849. }
  41850. return texture;
  41851. };
  41852. /**
  41853. * Serializes the LUT texture to json format.
  41854. */
  41855. ColorGradingTexture.prototype.serialize = function () {
  41856. if (!this.name) {
  41857. return null;
  41858. }
  41859. var serializationObject = {};
  41860. serializationObject.name = this.name;
  41861. serializationObject.level = this.level;
  41862. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41863. return serializationObject;
  41864. };
  41865. /**
  41866. * Empty line regex stored for GC.
  41867. */
  41868. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41869. return ColorGradingTexture;
  41870. }(BABYLON.BaseTexture));
  41871. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41872. })(BABYLON || (BABYLON = {}));
  41873. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41874. var BABYLON;
  41875. (function (BABYLON) {
  41876. /**
  41877. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41878. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41879. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  41880. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41881. */
  41882. var ColorCurves = /** @class */ (function () {
  41883. function ColorCurves() {
  41884. this._dirty = true;
  41885. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41886. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41887. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41888. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41889. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41890. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41891. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41892. this._globalHue = 30;
  41893. this._globalDensity = 0;
  41894. this._globalSaturation = 0;
  41895. this._globalExposure = 0;
  41896. this._highlightsHue = 30;
  41897. this._highlightsDensity = 0;
  41898. this._highlightsSaturation = 0;
  41899. this._highlightsExposure = 0;
  41900. this._midtonesHue = 30;
  41901. this._midtonesDensity = 0;
  41902. this._midtonesSaturation = 0;
  41903. this._midtonesExposure = 0;
  41904. this._shadowsHue = 30;
  41905. this._shadowsDensity = 0;
  41906. this._shadowsSaturation = 0;
  41907. this._shadowsExposure = 0;
  41908. }
  41909. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41910. /**
  41911. * Gets the global Hue value.
  41912. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  41913. */
  41914. get: function () {
  41915. return this._globalHue;
  41916. },
  41917. /**
  41918. * Sets the global Hue value.
  41919. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  41920. */
  41921. set: function (value) {
  41922. this._globalHue = value;
  41923. this._dirty = true;
  41924. },
  41925. enumerable: true,
  41926. configurable: true
  41927. });
  41928. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41929. /**
  41930. * Gets the global Density value.
  41931. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  41932. * Values less than zero provide a filter of opposite hue.
  41933. */
  41934. get: function () {
  41935. return this._globalDensity;
  41936. },
  41937. /**
  41938. * Sets the global Density value.
  41939. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  41940. * Values less than zero provide a filter of opposite hue.
  41941. */
  41942. set: function (value) {
  41943. this._globalDensity = value;
  41944. this._dirty = true;
  41945. },
  41946. enumerable: true,
  41947. configurable: true
  41948. });
  41949. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41950. /**
  41951. * Gets the global Saturation value.
  41952. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  41953. */
  41954. get: function () {
  41955. return this._globalSaturation;
  41956. },
  41957. /**
  41958. * Sets the global Saturation value.
  41959. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  41960. */
  41961. set: function (value) {
  41962. this._globalSaturation = value;
  41963. this._dirty = true;
  41964. },
  41965. enumerable: true,
  41966. configurable: true
  41967. });
  41968. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  41969. /**
  41970. * Gets the global Exposure value.
  41971. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  41972. */
  41973. get: function () {
  41974. return this._globalExposure;
  41975. },
  41976. /**
  41977. * Sets the global Exposure value.
  41978. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  41979. */
  41980. set: function (value) {
  41981. this._globalExposure = value;
  41982. this._dirty = true;
  41983. },
  41984. enumerable: true,
  41985. configurable: true
  41986. });
  41987. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41988. /**
  41989. * Gets the highlights Hue value.
  41990. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  41991. */
  41992. get: function () {
  41993. return this._highlightsHue;
  41994. },
  41995. /**
  41996. * Sets the highlights Hue value.
  41997. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  41998. */
  41999. set: function (value) {
  42000. this._highlightsHue = value;
  42001. this._dirty = true;
  42002. },
  42003. enumerable: true,
  42004. configurable: true
  42005. });
  42006. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  42007. /**
  42008. * Gets the highlights Density value.
  42009. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  42010. * Values less than zero provide a filter of opposite hue.
  42011. */
  42012. get: function () {
  42013. return this._highlightsDensity;
  42014. },
  42015. /**
  42016. * Sets the highlights Density value.
  42017. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  42018. * Values less than zero provide a filter of opposite hue.
  42019. */
  42020. set: function (value) {
  42021. this._highlightsDensity = value;
  42022. this._dirty = true;
  42023. },
  42024. enumerable: true,
  42025. configurable: true
  42026. });
  42027. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  42028. /**
  42029. * Gets the highlights Saturation value.
  42030. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  42031. */
  42032. get: function () {
  42033. return this._highlightsSaturation;
  42034. },
  42035. /**
  42036. * Sets the highlights Saturation value.
  42037. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  42038. */
  42039. set: function (value) {
  42040. this._highlightsSaturation = value;
  42041. this._dirty = true;
  42042. },
  42043. enumerable: true,
  42044. configurable: true
  42045. });
  42046. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  42047. /**
  42048. * Gets the highlights Exposure value.
  42049. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  42050. */
  42051. get: function () {
  42052. return this._highlightsExposure;
  42053. },
  42054. /**
  42055. * Sets the highlights Exposure value.
  42056. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  42057. */
  42058. set: function (value) {
  42059. this._highlightsExposure = value;
  42060. this._dirty = true;
  42061. },
  42062. enumerable: true,
  42063. configurable: true
  42064. });
  42065. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  42066. /**
  42067. * Gets the midtones Hue value.
  42068. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  42069. */
  42070. get: function () {
  42071. return this._midtonesHue;
  42072. },
  42073. /**
  42074. * Sets the midtones Hue value.
  42075. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  42076. */
  42077. set: function (value) {
  42078. this._midtonesHue = value;
  42079. this._dirty = true;
  42080. },
  42081. enumerable: true,
  42082. configurable: true
  42083. });
  42084. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  42085. /**
  42086. * Gets the midtones Density value.
  42087. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  42088. * Values less than zero provide a filter of opposite hue.
  42089. */
  42090. get: function () {
  42091. return this._midtonesDensity;
  42092. },
  42093. /**
  42094. * Sets the midtones Density value.
  42095. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  42096. * Values less than zero provide a filter of opposite hue.
  42097. */
  42098. set: function (value) {
  42099. this._midtonesDensity = value;
  42100. this._dirty = true;
  42101. },
  42102. enumerable: true,
  42103. configurable: true
  42104. });
  42105. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  42106. /**
  42107. * Gets the midtones Saturation value.
  42108. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  42109. */
  42110. get: function () {
  42111. return this._midtonesSaturation;
  42112. },
  42113. /**
  42114. * Sets the midtones Saturation value.
  42115. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  42116. */
  42117. set: function (value) {
  42118. this._midtonesSaturation = value;
  42119. this._dirty = true;
  42120. },
  42121. enumerable: true,
  42122. configurable: true
  42123. });
  42124. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  42125. /**
  42126. * Gets the midtones Exposure value.
  42127. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  42128. */
  42129. get: function () {
  42130. return this._midtonesExposure;
  42131. },
  42132. /**
  42133. * Sets the midtones Exposure value.
  42134. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  42135. */
  42136. set: function (value) {
  42137. this._midtonesExposure = value;
  42138. this._dirty = true;
  42139. },
  42140. enumerable: true,
  42141. configurable: true
  42142. });
  42143. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  42144. /**
  42145. * Gets the shadows Hue value.
  42146. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  42147. */
  42148. get: function () {
  42149. return this._shadowsHue;
  42150. },
  42151. /**
  42152. * Sets the shadows Hue value.
  42153. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  42154. */
  42155. set: function (value) {
  42156. this._shadowsHue = value;
  42157. this._dirty = true;
  42158. },
  42159. enumerable: true,
  42160. configurable: true
  42161. });
  42162. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  42163. /**
  42164. * Gets the shadows Density value.
  42165. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  42166. * Values less than zero provide a filter of opposite hue.
  42167. */
  42168. get: function () {
  42169. return this._shadowsDensity;
  42170. },
  42171. /**
  42172. * Sets the shadows Density value.
  42173. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  42174. * Values less than zero provide a filter of opposite hue.
  42175. */
  42176. set: function (value) {
  42177. this._shadowsDensity = value;
  42178. this._dirty = true;
  42179. },
  42180. enumerable: true,
  42181. configurable: true
  42182. });
  42183. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  42184. /**
  42185. * Gets the shadows Saturation value.
  42186. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  42187. */
  42188. get: function () {
  42189. return this._shadowsSaturation;
  42190. },
  42191. /**
  42192. * Sets the shadows Saturation value.
  42193. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  42194. */
  42195. set: function (value) {
  42196. this._shadowsSaturation = value;
  42197. this._dirty = true;
  42198. },
  42199. enumerable: true,
  42200. configurable: true
  42201. });
  42202. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  42203. /**
  42204. * Gets the shadows Exposure value.
  42205. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  42206. */
  42207. get: function () {
  42208. return this._shadowsExposure;
  42209. },
  42210. /**
  42211. * Sets the shadows Exposure value.
  42212. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  42213. */
  42214. set: function (value) {
  42215. this._shadowsExposure = value;
  42216. this._dirty = true;
  42217. },
  42218. enumerable: true,
  42219. configurable: true
  42220. });
  42221. ColorCurves.prototype.getClassName = function () {
  42222. return "ColorCurves";
  42223. };
  42224. /**
  42225. * Binds the color curves to the shader.
  42226. * @param colorCurves The color curve to bind
  42227. * @param effect The effect to bind to
  42228. */
  42229. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  42230. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  42231. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  42232. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  42233. if (colorCurves._dirty) {
  42234. colorCurves._dirty = false;
  42235. // Fill in global info.
  42236. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  42237. // Compute highlights info.
  42238. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  42239. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  42240. // Compute midtones info.
  42241. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  42242. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  42243. // Compute shadows info.
  42244. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  42245. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  42246. // Compute deltas (neutral is midtones).
  42247. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  42248. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  42249. }
  42250. if (effect) {
  42251. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  42252. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  42253. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  42254. }
  42255. };
  42256. /**
  42257. * Prepare the list of uniforms associated with the ColorCurves effects.
  42258. * @param uniformsList The list of uniforms used in the effect
  42259. */
  42260. ColorCurves.PrepareUniforms = function (uniformsList) {
  42261. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  42262. };
  42263. /**
  42264. * Returns color grading data based on a hue, density, saturation and exposure value.
  42265. * @param filterHue The hue of the color filter.
  42266. * @param filterDensity The density of the color filter.
  42267. * @param saturation The saturation.
  42268. * @param exposure The exposure.
  42269. * @param result The result data container.
  42270. */
  42271. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  42272. if (hue == null) {
  42273. return;
  42274. }
  42275. hue = ColorCurves.clamp(hue, 0, 360);
  42276. density = ColorCurves.clamp(density, -100, 100);
  42277. saturation = ColorCurves.clamp(saturation, -100, 100);
  42278. exposure = ColorCurves.clamp(exposure, -100, 100);
  42279. // Remap the slider/config filter density with non-linear mapping and also scale by half
  42280. // so that the maximum filter density is only 50% control. This provides fine control
  42281. // for small values and reasonable range.
  42282. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  42283. density *= 0.5;
  42284. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  42285. if (density < 0) {
  42286. density *= -1;
  42287. hue = (hue + 180) % 360;
  42288. }
  42289. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  42290. result.scaleToRef(2, result);
  42291. result.a = 1 + 0.01 * saturation;
  42292. };
  42293. /**
  42294. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  42295. * @param value The input slider value in range [-100,100].
  42296. * @returns Adjusted value.
  42297. */
  42298. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  42299. value /= 100;
  42300. var x = Math.abs(value);
  42301. x = Math.pow(x, 2);
  42302. if (value < 0) {
  42303. x *= -1;
  42304. }
  42305. x *= 100;
  42306. return x;
  42307. };
  42308. /**
  42309. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  42310. * @param hue The hue (H) input.
  42311. * @param saturation The saturation (S) input.
  42312. * @param brightness The brightness (B) input.
  42313. * @result An RGBA color represented as Vector4.
  42314. */
  42315. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  42316. var h = ColorCurves.clamp(hue, 0, 360);
  42317. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  42318. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  42319. if (s === 0) {
  42320. result.r = v;
  42321. result.g = v;
  42322. result.b = v;
  42323. }
  42324. else {
  42325. // sector 0 to 5
  42326. h /= 60;
  42327. var i = Math.floor(h);
  42328. // fractional part of h
  42329. var f = h - i;
  42330. var p = v * (1 - s);
  42331. var q = v * (1 - s * f);
  42332. var t = v * (1 - s * (1 - f));
  42333. switch (i) {
  42334. case 0:
  42335. result.r = v;
  42336. result.g = t;
  42337. result.b = p;
  42338. break;
  42339. case 1:
  42340. result.r = q;
  42341. result.g = v;
  42342. result.b = p;
  42343. break;
  42344. case 2:
  42345. result.r = p;
  42346. result.g = v;
  42347. result.b = t;
  42348. break;
  42349. case 3:
  42350. result.r = p;
  42351. result.g = q;
  42352. result.b = v;
  42353. break;
  42354. case 4:
  42355. result.r = t;
  42356. result.g = p;
  42357. result.b = v;
  42358. break;
  42359. default: // case 5:
  42360. result.r = v;
  42361. result.g = p;
  42362. result.b = q;
  42363. break;
  42364. }
  42365. }
  42366. result.a = 1;
  42367. };
  42368. /**
  42369. * Returns a value clamped between min and max
  42370. * @param value The value to clamp
  42371. * @param min The minimum of value
  42372. * @param max The maximum of value
  42373. * @returns The clamped value.
  42374. */
  42375. ColorCurves.clamp = function (value, min, max) {
  42376. return Math.min(Math.max(value, min), max);
  42377. };
  42378. /**
  42379. * Clones the current color curve instance.
  42380. * @return The cloned curves
  42381. */
  42382. ColorCurves.prototype.clone = function () {
  42383. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42384. };
  42385. /**
  42386. * Serializes the current color curve instance to a json representation.
  42387. * @return a JSON representation
  42388. */
  42389. ColorCurves.prototype.serialize = function () {
  42390. return BABYLON.SerializationHelper.Serialize(this);
  42391. };
  42392. /**
  42393. * Parses the color curve from a json representation.
  42394. * @param source the JSON source to parse
  42395. * @return The parsed curves
  42396. */
  42397. ColorCurves.Parse = function (source) {
  42398. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42399. };
  42400. __decorate([
  42401. BABYLON.serialize()
  42402. ], ColorCurves.prototype, "_globalHue", void 0);
  42403. __decorate([
  42404. BABYLON.serialize()
  42405. ], ColorCurves.prototype, "_globalDensity", void 0);
  42406. __decorate([
  42407. BABYLON.serialize()
  42408. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42409. __decorate([
  42410. BABYLON.serialize()
  42411. ], ColorCurves.prototype, "_globalExposure", void 0);
  42412. __decorate([
  42413. BABYLON.serialize()
  42414. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42415. __decorate([
  42416. BABYLON.serialize()
  42417. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42418. __decorate([
  42419. BABYLON.serialize()
  42420. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42421. __decorate([
  42422. BABYLON.serialize()
  42423. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42424. __decorate([
  42425. BABYLON.serialize()
  42426. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42427. __decorate([
  42428. BABYLON.serialize()
  42429. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42430. __decorate([
  42431. BABYLON.serialize()
  42432. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42433. __decorate([
  42434. BABYLON.serialize()
  42435. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42436. return ColorCurves;
  42437. }());
  42438. BABYLON.ColorCurves = ColorCurves;
  42439. })(BABYLON || (BABYLON = {}));
  42440. //# sourceMappingURL=babylon.colorCurves.js.map
  42441. //# sourceMappingURL=babylon.behavior.js.map
  42442. var BABYLON;
  42443. (function (BABYLON) {
  42444. /**
  42445. * "Static Class" containing the most commonly used helper while dealing with material for
  42446. * rendering purpose.
  42447. *
  42448. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42449. *
  42450. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42451. */
  42452. var MaterialHelper = /** @class */ (function () {
  42453. function MaterialHelper() {
  42454. }
  42455. /**
  42456. * Bind the current view position to an effect.
  42457. * @param effect The effect to be bound
  42458. * @param scene The scene the eyes position is used from
  42459. */
  42460. MaterialHelper.BindEyePosition = function (effect, scene) {
  42461. if (scene._forcedViewPosition) {
  42462. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42463. return;
  42464. }
  42465. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42466. };
  42467. /**
  42468. * Helps preparing the defines values about the UVs in used in the effect.
  42469. * UVs are shared as much as we can accross chanels in the shaders.
  42470. * @param texture The texture we are preparing the UVs for
  42471. * @param defines The defines to update
  42472. * @param key The chanel key "diffuse", "specular"... used in the shader
  42473. */
  42474. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42475. defines._needUVs = true;
  42476. defines[key] = true;
  42477. if (texture.getTextureMatrix().isIdentity(true)) {
  42478. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42479. if (texture.coordinatesIndex === 0) {
  42480. defines["MAINUV1"] = true;
  42481. }
  42482. else {
  42483. defines["MAINUV2"] = true;
  42484. }
  42485. }
  42486. else {
  42487. defines[key + "DIRECTUV"] = 0;
  42488. }
  42489. };
  42490. /**
  42491. * Binds a texture matrix value to its corrsponding uniform
  42492. * @param texture The texture to bind the matrix for
  42493. * @param uniformBuffer The uniform buffer receivin the data
  42494. * @param key The chanel key "diffuse", "specular"... used in the shader
  42495. */
  42496. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42497. var matrix = texture.getTextureMatrix();
  42498. if (!matrix.isIdentity(true)) {
  42499. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42500. }
  42501. };
  42502. /**
  42503. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42504. * @param mesh defines the current mesh
  42505. * @param scene defines the current scene
  42506. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42507. * @param pointsCloud defines if point cloud rendering has to be turned on
  42508. * @param fogEnabled defines if fog has to be turned on
  42509. * @param alphaTest defines if alpha testing has to be turned on
  42510. * @param defines defines the current list of defines
  42511. */
  42512. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42513. if (defines._areMiscDirty) {
  42514. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42515. defines["POINTSIZE"] = pointsCloud;
  42516. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42517. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42518. defines["ALPHATEST"] = alphaTest;
  42519. }
  42520. };
  42521. /**
  42522. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42523. * @param scene defines the current scene
  42524. * @param engine defines the current engine
  42525. * @param defines specifies the list of active defines
  42526. * @param useInstances defines if instances have to be turned on
  42527. * @param useClipPlane defines if clip plane have to be turned on
  42528. */
  42529. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42530. if (useClipPlane === void 0) { useClipPlane = null; }
  42531. var changed = false;
  42532. if (useClipPlane == null) {
  42533. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42534. }
  42535. if (defines["CLIPPLANE"] !== useClipPlane) {
  42536. defines["CLIPPLANE"] = useClipPlane;
  42537. changed = true;
  42538. }
  42539. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42540. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42541. changed = true;
  42542. }
  42543. if (defines["INSTANCES"] !== useInstances) {
  42544. defines["INSTANCES"] = useInstances;
  42545. changed = true;
  42546. }
  42547. if (changed) {
  42548. defines.markAsUnprocessed();
  42549. }
  42550. };
  42551. /**
  42552. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42553. * @param mesh The mesh containing the geometry data we will draw
  42554. * @param defines The defines to update
  42555. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42556. * @param useBones Precise whether bones should be used or not (override mesh info)
  42557. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42558. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42559. * @returns false if defines are considered not dirty and have not been checked
  42560. */
  42561. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42562. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42563. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42564. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42565. return false;
  42566. }
  42567. defines._normals = defines._needNormals;
  42568. defines._uvs = defines._needUVs;
  42569. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42570. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42571. defines["TANGENT"] = true;
  42572. }
  42573. if (defines._needUVs) {
  42574. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42575. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42576. }
  42577. else {
  42578. defines["UV1"] = false;
  42579. defines["UV2"] = false;
  42580. }
  42581. if (useVertexColor) {
  42582. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42583. defines["VERTEXCOLOR"] = hasVertexColors;
  42584. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42585. }
  42586. if (useBones) {
  42587. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42588. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42589. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42590. }
  42591. else {
  42592. defines["NUM_BONE_INFLUENCERS"] = 0;
  42593. defines["BonesPerMesh"] = 0;
  42594. }
  42595. }
  42596. if (useMorphTargets) {
  42597. var manager = mesh.morphTargetManager;
  42598. if (manager) {
  42599. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42600. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42601. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42602. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42603. }
  42604. else {
  42605. defines["MORPHTARGETS_TANGENT"] = false;
  42606. defines["MORPHTARGETS_NORMAL"] = false;
  42607. defines["MORPHTARGETS"] = false;
  42608. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42609. }
  42610. }
  42611. return true;
  42612. };
  42613. /**
  42614. * Prepares the defines related to the light information passed in parameter
  42615. * @param scene The scene we are intending to draw
  42616. * @param mesh The mesh the effect is compiling for
  42617. * @param defines The defines to update
  42618. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42619. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42620. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42621. * @returns true if normals will be required for the rest of the effect
  42622. */
  42623. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42624. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42625. if (disableLighting === void 0) { disableLighting = false; }
  42626. if (!defines._areLightsDirty) {
  42627. return defines._needNormals;
  42628. }
  42629. var lightIndex = 0;
  42630. var needNormals = false;
  42631. var needRebuild = false;
  42632. var lightmapMode = false;
  42633. var shadowEnabled = false;
  42634. var specularEnabled = false;
  42635. if (scene.lightsEnabled && !disableLighting) {
  42636. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42637. var light = _a[_i];
  42638. needNormals = true;
  42639. if (defines["LIGHT" + lightIndex] === undefined) {
  42640. needRebuild = true;
  42641. }
  42642. defines["LIGHT" + lightIndex] = true;
  42643. defines["SPOTLIGHT" + lightIndex] = false;
  42644. defines["HEMILIGHT" + lightIndex] = false;
  42645. defines["POINTLIGHT" + lightIndex] = false;
  42646. defines["DIRLIGHT" + lightIndex] = false;
  42647. var type;
  42648. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42649. type = "SPOTLIGHT" + lightIndex;
  42650. var spotLight = light;
  42651. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42652. }
  42653. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42654. type = "HEMILIGHT" + lightIndex;
  42655. }
  42656. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42657. type = "POINTLIGHT" + lightIndex;
  42658. }
  42659. else {
  42660. type = "DIRLIGHT" + lightIndex;
  42661. }
  42662. defines[type] = true;
  42663. // Specular
  42664. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42665. specularEnabled = true;
  42666. }
  42667. // Shadows
  42668. defines["SHADOW" + lightIndex] = false;
  42669. defines["SHADOWPCF" + lightIndex] = false;
  42670. defines["SHADOWPCSS" + lightIndex] = false;
  42671. defines["SHADOWPOISSON" + lightIndex] = false;
  42672. defines["SHADOWESM" + lightIndex] = false;
  42673. defines["SHADOWCUBE" + lightIndex] = false;
  42674. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42675. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42676. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42677. var shadowGenerator = light.getShadowGenerator();
  42678. if (shadowGenerator) {
  42679. shadowEnabled = true;
  42680. shadowGenerator.prepareDefines(defines, lightIndex);
  42681. }
  42682. }
  42683. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42684. lightmapMode = true;
  42685. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42686. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42687. }
  42688. else {
  42689. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42690. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42691. }
  42692. lightIndex++;
  42693. if (lightIndex === maxSimultaneousLights)
  42694. break;
  42695. }
  42696. }
  42697. defines["SPECULARTERM"] = specularEnabled;
  42698. defines["SHADOWS"] = shadowEnabled;
  42699. // Resetting all other lights if any
  42700. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42701. if (defines["LIGHT" + index] !== undefined) {
  42702. defines["LIGHT" + index] = false;
  42703. defines["HEMILIGHT" + lightIndex] = false;
  42704. defines["POINTLIGHT" + lightIndex] = false;
  42705. defines["DIRLIGHT" + lightIndex] = false;
  42706. defines["SPOTLIGHT" + lightIndex] = false;
  42707. defines["SHADOW" + lightIndex] = false;
  42708. }
  42709. }
  42710. var caps = scene.getEngine().getCaps();
  42711. if (defines["SHADOWFLOAT"] === undefined) {
  42712. needRebuild = true;
  42713. }
  42714. defines["SHADOWFLOAT"] = shadowEnabled &&
  42715. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42716. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42717. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42718. if (needRebuild) {
  42719. defines.rebuild();
  42720. }
  42721. return needNormals;
  42722. };
  42723. /**
  42724. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42725. * that won t be acctive due to defines being turned off.
  42726. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42727. * @param samplersList The samplers list
  42728. * @param defines The defines helping in the list generation
  42729. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42730. */
  42731. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42732. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42733. var uniformsList;
  42734. var uniformBuffersList = null;
  42735. if (uniformsListOrOptions.uniformsNames) {
  42736. var options = uniformsListOrOptions;
  42737. uniformsList = options.uniformsNames;
  42738. uniformBuffersList = options.uniformBuffersNames;
  42739. samplersList = options.samplers;
  42740. defines = options.defines;
  42741. maxSimultaneousLights = options.maxSimultaneousLights;
  42742. }
  42743. else {
  42744. uniformsList = uniformsListOrOptions;
  42745. if (!samplersList) {
  42746. samplersList = [];
  42747. }
  42748. }
  42749. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42750. if (!defines["LIGHT" + lightIndex]) {
  42751. break;
  42752. }
  42753. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42754. if (uniformBuffersList) {
  42755. uniformBuffersList.push("Light" + lightIndex);
  42756. }
  42757. samplersList.push("shadowSampler" + lightIndex);
  42758. samplersList.push("depthSampler" + lightIndex);
  42759. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42760. samplersList.push("projectionLightSampler" + lightIndex);
  42761. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42762. }
  42763. }
  42764. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42765. uniformsList.push("morphTargetInfluences");
  42766. }
  42767. };
  42768. /**
  42769. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42770. * @param defines The defines to update while falling back
  42771. * @param fallbacks The authorized effect fallbacks
  42772. * @param maxSimultaneousLights The maximum number of lights allowed
  42773. * @param rank the current rank of the Effect
  42774. * @returns The newly affected rank
  42775. */
  42776. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42777. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42778. if (rank === void 0) { rank = 0; }
  42779. var lightFallbackRank = 0;
  42780. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42781. if (!defines["LIGHT" + lightIndex]) {
  42782. break;
  42783. }
  42784. if (lightIndex > 0) {
  42785. lightFallbackRank = rank + lightIndex;
  42786. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42787. }
  42788. if (!defines["SHADOWS"]) {
  42789. if (defines["SHADOW" + lightIndex]) {
  42790. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42791. }
  42792. if (defines["SHADOWPCF" + lightIndex]) {
  42793. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42794. }
  42795. if (defines["SHADOWPCSS" + lightIndex]) {
  42796. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42797. }
  42798. if (defines["SHADOWPOISSON" + lightIndex]) {
  42799. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42800. }
  42801. if (defines["SHADOWESM" + lightIndex]) {
  42802. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42803. }
  42804. }
  42805. }
  42806. return lightFallbackRank++;
  42807. };
  42808. /**
  42809. * Prepares the list of attributes required for morph targets according to the effect defines.
  42810. * @param attribs The current list of supported attribs
  42811. * @param mesh The mesh to prepare the morph targets attributes for
  42812. * @param defines The current Defines of the effect
  42813. */
  42814. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42815. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42816. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42817. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42818. var manager = mesh.morphTargetManager;
  42819. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42820. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42821. for (var index = 0; index < influencers; index++) {
  42822. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42823. if (normal) {
  42824. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42825. }
  42826. if (tangent) {
  42827. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42828. }
  42829. if (attribs.length > maxAttributesCount) {
  42830. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42831. }
  42832. }
  42833. }
  42834. };
  42835. /**
  42836. * Prepares the list of attributes required for bones according to the effect defines.
  42837. * @param attribs The current list of supported attribs
  42838. * @param mesh The mesh to prepare the bones attributes for
  42839. * @param defines The current Defines of the effect
  42840. * @param fallbacks The current efffect fallback strategy
  42841. */
  42842. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42843. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42844. fallbacks.addCPUSkinningFallback(0, mesh);
  42845. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42846. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42847. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42848. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42849. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42850. }
  42851. }
  42852. };
  42853. /**
  42854. * Prepares the list of attributes required for instances according to the effect defines.
  42855. * @param attribs The current list of supported attribs
  42856. * @param defines The current Defines of the effect
  42857. */
  42858. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42859. if (defines["INSTANCES"]) {
  42860. attribs.push("world0");
  42861. attribs.push("world1");
  42862. attribs.push("world2");
  42863. attribs.push("world3");
  42864. }
  42865. };
  42866. /**
  42867. * Binds the light shadow information to the effect for the given mesh.
  42868. * @param light The light containing the generator
  42869. * @param scene The scene the lights belongs to
  42870. * @param mesh The mesh we are binding the information to render
  42871. * @param lightIndex The light index in the effect used to render the mesh
  42872. * @param effect The effect we are binding the data to
  42873. */
  42874. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42875. if (light.shadowEnabled && mesh.receiveShadows) {
  42876. var shadowGenerator = light.getShadowGenerator();
  42877. if (shadowGenerator) {
  42878. shadowGenerator.bindShadowLight(lightIndex, effect);
  42879. }
  42880. }
  42881. };
  42882. /**
  42883. * Binds the light information to the effect.
  42884. * @param light The light containing the generator
  42885. * @param effect The effect we are binding the data to
  42886. * @param lightIndex The light index in the effect used to render
  42887. */
  42888. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42889. light.transferToEffect(effect, lightIndex + "");
  42890. };
  42891. /**
  42892. * Binds the lights information from the scene to the effect for the given mesh.
  42893. * @param scene The scene the lights belongs to
  42894. * @param mesh The mesh we are binding the information to render
  42895. * @param effect The effect we are binding the data to
  42896. * @param defines The generated defines for the effect
  42897. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42898. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42899. */
  42900. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42901. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42902. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42903. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42904. for (var i = 0; i < len; i++) {
  42905. var light = mesh._lightSources[i];
  42906. var iAsString = i.toString();
  42907. var scaledIntensity = light.getScaledIntensity();
  42908. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42909. MaterialHelper.BindLightProperties(light, effect, i);
  42910. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42911. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42912. if (defines["SPECULARTERM"]) {
  42913. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42914. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42915. }
  42916. // Shadows
  42917. if (scene.shadowsEnabled) {
  42918. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42919. }
  42920. light._uniformBuffer.update();
  42921. }
  42922. };
  42923. /**
  42924. * Binds the fog information from the scene to the effect for the given mesh.
  42925. * @param scene The scene the lights belongs to
  42926. * @param mesh The mesh we are binding the information to render
  42927. * @param effect The effect we are binding the data to
  42928. */
  42929. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42930. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42931. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42932. effect.setColor3("vFogColor", scene.fogColor);
  42933. }
  42934. };
  42935. /**
  42936. * Binds the bones information from the mesh to the effect.
  42937. * @param mesh The mesh we are binding the information to render
  42938. * @param effect The effect we are binding the data to
  42939. */
  42940. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42941. if (!effect || !mesh) {
  42942. return;
  42943. }
  42944. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  42945. mesh.computeBonesUsingShaders = false;
  42946. }
  42947. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42948. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42949. if (matrices) {
  42950. effect.setMatrices("mBones", matrices);
  42951. }
  42952. }
  42953. };
  42954. /**
  42955. * Binds the morph targets information from the mesh to the effect.
  42956. * @param abstractMesh The mesh we are binding the information to render
  42957. * @param effect The effect we are binding the data to
  42958. */
  42959. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42960. var manager = abstractMesh.morphTargetManager;
  42961. if (!abstractMesh || !manager) {
  42962. return;
  42963. }
  42964. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42965. };
  42966. /**
  42967. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42968. * @param defines The generated defines used in the effect
  42969. * @param effect The effect we are binding the data to
  42970. * @param scene The scene we are willing to render with logarithmic scale for
  42971. */
  42972. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42973. if (defines["LOGARITHMICDEPTH"]) {
  42974. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42975. }
  42976. };
  42977. /**
  42978. * Binds the clip plane information from the scene to the effect.
  42979. * @param scene The scene the clip plane information are extracted from
  42980. * @param effect The effect we are binding the data to
  42981. */
  42982. MaterialHelper.BindClipPlane = function (effect, scene) {
  42983. if (scene.clipPlane) {
  42984. var clipPlane = scene.clipPlane;
  42985. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42986. }
  42987. };
  42988. return MaterialHelper;
  42989. }());
  42990. BABYLON.MaterialHelper = MaterialHelper;
  42991. })(BABYLON || (BABYLON = {}));
  42992. //# sourceMappingURL=babylon.materialHelper.js.map
  42993. var BABYLON;
  42994. (function (BABYLON) {
  42995. var PushMaterial = /** @class */ (function (_super) {
  42996. __extends(PushMaterial, _super);
  42997. function PushMaterial(name, scene) {
  42998. var _this = _super.call(this, name, scene) || this;
  42999. _this._normalMatrix = new BABYLON.Matrix();
  43000. _this.storeEffectOnSubMeshes = true;
  43001. return _this;
  43002. }
  43003. PushMaterial.prototype.getEffect = function () {
  43004. return this._activeEffect;
  43005. };
  43006. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  43007. if (!mesh) {
  43008. return false;
  43009. }
  43010. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  43011. return true;
  43012. }
  43013. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  43014. };
  43015. /**
  43016. * Binds the given world matrix to the active effect
  43017. *
  43018. * @param world the matrix to bind
  43019. */
  43020. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  43021. this._activeEffect.setMatrix("world", world);
  43022. };
  43023. /**
  43024. * Binds the given normal matrix to the active effect
  43025. *
  43026. * @param normalMatrix the matrix to bind
  43027. */
  43028. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  43029. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  43030. };
  43031. PushMaterial.prototype.bind = function (world, mesh) {
  43032. if (!mesh) {
  43033. return;
  43034. }
  43035. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  43036. };
  43037. PushMaterial.prototype._afterBind = function (mesh, effect) {
  43038. if (effect === void 0) { effect = null; }
  43039. _super.prototype._afterBind.call(this, mesh);
  43040. this.getScene()._cachedEffect = effect;
  43041. };
  43042. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  43043. if (visibility === void 0) { visibility = 1; }
  43044. return scene.isCachedMaterialInvalid(this, effect, visibility);
  43045. };
  43046. return PushMaterial;
  43047. }(BABYLON.Material));
  43048. BABYLON.PushMaterial = PushMaterial;
  43049. })(BABYLON || (BABYLON = {}));
  43050. //# sourceMappingURL=babylon.pushMaterial.js.map
  43051. var BABYLON;
  43052. (function (BABYLON) {
  43053. /** @hidden */
  43054. var StandardMaterialDefines = /** @class */ (function (_super) {
  43055. __extends(StandardMaterialDefines, _super);
  43056. function StandardMaterialDefines() {
  43057. var _this = _super.call(this) || this;
  43058. _this.MAINUV1 = false;
  43059. _this.MAINUV2 = false;
  43060. _this.DIFFUSE = false;
  43061. _this.DIFFUSEDIRECTUV = 0;
  43062. _this.AMBIENT = false;
  43063. _this.AMBIENTDIRECTUV = 0;
  43064. _this.OPACITY = false;
  43065. _this.OPACITYDIRECTUV = 0;
  43066. _this.OPACITYRGB = false;
  43067. _this.REFLECTION = false;
  43068. _this.EMISSIVE = false;
  43069. _this.EMISSIVEDIRECTUV = 0;
  43070. _this.SPECULAR = false;
  43071. _this.SPECULARDIRECTUV = 0;
  43072. _this.BUMP = false;
  43073. _this.BUMPDIRECTUV = 0;
  43074. _this.PARALLAX = false;
  43075. _this.PARALLAXOCCLUSION = false;
  43076. _this.SPECULAROVERALPHA = false;
  43077. _this.CLIPPLANE = false;
  43078. _this.ALPHATEST = false;
  43079. _this.DEPTHPREPASS = false;
  43080. _this.ALPHAFROMDIFFUSE = false;
  43081. _this.POINTSIZE = false;
  43082. _this.FOG = false;
  43083. _this.SPECULARTERM = false;
  43084. _this.DIFFUSEFRESNEL = false;
  43085. _this.OPACITYFRESNEL = false;
  43086. _this.REFLECTIONFRESNEL = false;
  43087. _this.REFRACTIONFRESNEL = false;
  43088. _this.EMISSIVEFRESNEL = false;
  43089. _this.FRESNEL = false;
  43090. _this.NORMAL = false;
  43091. _this.UV1 = false;
  43092. _this.UV2 = false;
  43093. _this.VERTEXCOLOR = false;
  43094. _this.VERTEXALPHA = false;
  43095. _this.NUM_BONE_INFLUENCERS = 0;
  43096. _this.BonesPerMesh = 0;
  43097. _this.INSTANCES = false;
  43098. _this.GLOSSINESS = false;
  43099. _this.ROUGHNESS = false;
  43100. _this.EMISSIVEASILLUMINATION = false;
  43101. _this.LINKEMISSIVEWITHDIFFUSE = false;
  43102. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  43103. _this.LIGHTMAP = false;
  43104. _this.LIGHTMAPDIRECTUV = 0;
  43105. _this.OBJECTSPACE_NORMALMAP = false;
  43106. _this.USELIGHTMAPASSHADOWMAP = false;
  43107. _this.REFLECTIONMAP_3D = false;
  43108. _this.REFLECTIONMAP_SPHERICAL = false;
  43109. _this.REFLECTIONMAP_PLANAR = false;
  43110. _this.REFLECTIONMAP_CUBIC = false;
  43111. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43112. _this.REFLECTIONMAP_PROJECTION = false;
  43113. _this.REFLECTIONMAP_SKYBOX = false;
  43114. _this.REFLECTIONMAP_EXPLICIT = false;
  43115. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43116. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43117. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43118. _this.INVERTCUBICMAP = false;
  43119. _this.LOGARITHMICDEPTH = false;
  43120. _this.REFRACTION = false;
  43121. _this.REFRACTIONMAP_3D = false;
  43122. _this.REFLECTIONOVERALPHA = false;
  43123. _this.TWOSIDEDLIGHTING = false;
  43124. _this.SHADOWFLOAT = false;
  43125. _this.MORPHTARGETS = false;
  43126. _this.MORPHTARGETS_NORMAL = false;
  43127. _this.MORPHTARGETS_TANGENT = false;
  43128. _this.NUM_MORPH_INFLUENCERS = 0;
  43129. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  43130. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  43131. _this.IMAGEPROCESSING = false;
  43132. _this.VIGNETTE = false;
  43133. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43134. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43135. _this.TONEMAPPING = false;
  43136. _this.CONTRAST = false;
  43137. _this.COLORCURVES = false;
  43138. _this.COLORGRADING = false;
  43139. _this.COLORGRADING3D = false;
  43140. _this.SAMPLER3DGREENDEPTH = false;
  43141. _this.SAMPLER3DBGRMAP = false;
  43142. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43143. /**
  43144. * If the reflection texture on this material is in linear color space
  43145. * @hidden
  43146. */
  43147. _this.IS_REFLECTION_LINEAR = false;
  43148. /**
  43149. * If the refraction texture on this material is in linear color space
  43150. * @hidden
  43151. */
  43152. _this.IS_REFRACTION_LINEAR = false;
  43153. _this.EXPOSURE = false;
  43154. _this.rebuild();
  43155. return _this;
  43156. }
  43157. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  43158. var modes = [
  43159. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  43160. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  43161. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  43162. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  43163. ];
  43164. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  43165. var mode = modes_1[_i];
  43166. this[mode] = (mode === modeToEnable);
  43167. }
  43168. };
  43169. return StandardMaterialDefines;
  43170. }(BABYLON.MaterialDefines));
  43171. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  43172. var StandardMaterial = /** @class */ (function (_super) {
  43173. __extends(StandardMaterial, _super);
  43174. function StandardMaterial(name, scene) {
  43175. var _this = _super.call(this, name, scene) || this;
  43176. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43177. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  43178. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43179. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43180. _this.specularPower = 64;
  43181. _this._useAlphaFromDiffuseTexture = false;
  43182. _this._useEmissiveAsIllumination = false;
  43183. _this._linkEmissiveWithDiffuse = false;
  43184. _this._useSpecularOverAlpha = false;
  43185. _this._useReflectionOverAlpha = false;
  43186. _this._disableLighting = false;
  43187. _this._useObjectSpaceNormalMap = false;
  43188. _this._useParallax = false;
  43189. _this._useParallaxOcclusion = false;
  43190. _this.parallaxScaleBias = 0.05;
  43191. _this._roughness = 0;
  43192. _this.indexOfRefraction = 0.98;
  43193. _this.invertRefractionY = true;
  43194. /**
  43195. * Defines the alpha limits in alpha test mode
  43196. */
  43197. _this.alphaCutOff = 0.4;
  43198. _this._useLightmapAsShadowmap = false;
  43199. _this._useReflectionFresnelFromSpecular = false;
  43200. _this._useGlossinessFromSpecularMapAlpha = false;
  43201. _this._maxSimultaneousLights = 4;
  43202. /**
  43203. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  43204. */
  43205. _this._invertNormalMapX = false;
  43206. /**
  43207. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  43208. */
  43209. _this._invertNormalMapY = false;
  43210. /**
  43211. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43212. */
  43213. _this._twoSidedLighting = false;
  43214. _this._renderTargets = new BABYLON.SmartArray(16);
  43215. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43216. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43217. // Setup the default processing configuration to the scene.
  43218. _this._attachImageProcessingConfiguration(null);
  43219. _this.getRenderTargetTextures = function () {
  43220. _this._renderTargets.reset();
  43221. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43222. _this._renderTargets.push(_this._reflectionTexture);
  43223. }
  43224. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43225. _this._renderTargets.push(_this._refractionTexture);
  43226. }
  43227. return _this._renderTargets;
  43228. };
  43229. return _this;
  43230. }
  43231. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43232. /**
  43233. * Gets the image processing configuration used either in this material.
  43234. */
  43235. get: function () {
  43236. return this._imageProcessingConfiguration;
  43237. },
  43238. /**
  43239. * Sets the Default image processing configuration used either in the this material.
  43240. *
  43241. * If sets to null, the scene one is in use.
  43242. */
  43243. set: function (value) {
  43244. this._attachImageProcessingConfiguration(value);
  43245. // Ensure the effect will be rebuilt.
  43246. this._markAllSubMeshesAsTexturesDirty();
  43247. },
  43248. enumerable: true,
  43249. configurable: true
  43250. });
  43251. /**
  43252. * Attaches a new image processing configuration to the Standard Material.
  43253. * @param configuration
  43254. */
  43255. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43256. var _this = this;
  43257. if (configuration === this._imageProcessingConfiguration) {
  43258. return;
  43259. }
  43260. // Detaches observer.
  43261. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43262. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43263. }
  43264. // Pick the scene configuration if needed.
  43265. if (!configuration) {
  43266. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43267. }
  43268. else {
  43269. this._imageProcessingConfiguration = configuration;
  43270. }
  43271. // Attaches observer.
  43272. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43273. _this._markAllSubMeshesAsImageProcessingDirty();
  43274. });
  43275. };
  43276. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43277. /**
  43278. * Gets wether the color curves effect is enabled.
  43279. */
  43280. get: function () {
  43281. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43282. },
  43283. /**
  43284. * Sets wether the color curves effect is enabled.
  43285. */
  43286. set: function (value) {
  43287. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43288. },
  43289. enumerable: true,
  43290. configurable: true
  43291. });
  43292. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43293. /**
  43294. * Gets wether the color grading effect is enabled.
  43295. */
  43296. get: function () {
  43297. return this.imageProcessingConfiguration.colorGradingEnabled;
  43298. },
  43299. /**
  43300. * Gets wether the color grading effect is enabled.
  43301. */
  43302. set: function (value) {
  43303. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43304. },
  43305. enumerable: true,
  43306. configurable: true
  43307. });
  43308. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43309. /**
  43310. * Gets wether tonemapping is enabled or not.
  43311. */
  43312. get: function () {
  43313. return this._imageProcessingConfiguration.toneMappingEnabled;
  43314. },
  43315. /**
  43316. * Sets wether tonemapping is enabled or not
  43317. */
  43318. set: function (value) {
  43319. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43320. },
  43321. enumerable: true,
  43322. configurable: true
  43323. });
  43324. ;
  43325. ;
  43326. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43327. /**
  43328. * The camera exposure used on this material.
  43329. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43330. * This corresponds to a photographic exposure.
  43331. */
  43332. get: function () {
  43333. return this._imageProcessingConfiguration.exposure;
  43334. },
  43335. /**
  43336. * The camera exposure used on this material.
  43337. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43338. * This corresponds to a photographic exposure.
  43339. */
  43340. set: function (value) {
  43341. this._imageProcessingConfiguration.exposure = value;
  43342. },
  43343. enumerable: true,
  43344. configurable: true
  43345. });
  43346. ;
  43347. ;
  43348. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43349. /**
  43350. * Gets The camera contrast used on this material.
  43351. */
  43352. get: function () {
  43353. return this._imageProcessingConfiguration.contrast;
  43354. },
  43355. /**
  43356. * Sets The camera contrast used on this material.
  43357. */
  43358. set: function (value) {
  43359. this._imageProcessingConfiguration.contrast = value;
  43360. },
  43361. enumerable: true,
  43362. configurable: true
  43363. });
  43364. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43365. /**
  43366. * Gets the Color Grading 2D Lookup Texture.
  43367. */
  43368. get: function () {
  43369. return this._imageProcessingConfiguration.colorGradingTexture;
  43370. },
  43371. /**
  43372. * Sets the Color Grading 2D Lookup Texture.
  43373. */
  43374. set: function (value) {
  43375. this._imageProcessingConfiguration.colorGradingTexture = value;
  43376. },
  43377. enumerable: true,
  43378. configurable: true
  43379. });
  43380. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43381. /**
  43382. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43383. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43384. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  43385. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43386. */
  43387. get: function () {
  43388. return this._imageProcessingConfiguration.colorCurves;
  43389. },
  43390. /**
  43391. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43392. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43393. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  43394. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43395. */
  43396. set: function (value) {
  43397. this._imageProcessingConfiguration.colorCurves = value;
  43398. },
  43399. enumerable: true,
  43400. configurable: true
  43401. });
  43402. StandardMaterial.prototype.getClassName = function () {
  43403. return "StandardMaterial";
  43404. };
  43405. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43406. get: function () {
  43407. return this._useLogarithmicDepth;
  43408. },
  43409. set: function (value) {
  43410. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43411. this._markAllSubMeshesAsMiscDirty();
  43412. },
  43413. enumerable: true,
  43414. configurable: true
  43415. });
  43416. StandardMaterial.prototype.needAlphaBlending = function () {
  43417. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43418. };
  43419. StandardMaterial.prototype.needAlphaTesting = function () {
  43420. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43421. };
  43422. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43423. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43424. };
  43425. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43426. return this._diffuseTexture;
  43427. };
  43428. /**
  43429. * Child classes can use it to update shaders
  43430. */
  43431. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43432. if (useInstances === void 0) { useInstances = false; }
  43433. if (subMesh.effect && this.isFrozen) {
  43434. if (this._wasPreviouslyReady && subMesh.effect) {
  43435. return true;
  43436. }
  43437. }
  43438. if (!subMesh._materialDefines) {
  43439. subMesh._materialDefines = new StandardMaterialDefines();
  43440. }
  43441. var scene = this.getScene();
  43442. var defines = subMesh._materialDefines;
  43443. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43444. if (defines._renderId === scene.getRenderId()) {
  43445. return true;
  43446. }
  43447. }
  43448. var engine = scene.getEngine();
  43449. // Lights
  43450. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43451. // Textures
  43452. if (defines._areTexturesDirty) {
  43453. defines._needUVs = false;
  43454. defines.MAINUV1 = false;
  43455. defines.MAINUV2 = false;
  43456. if (scene.texturesEnabled) {
  43457. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43458. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43459. return false;
  43460. }
  43461. else {
  43462. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43463. }
  43464. }
  43465. else {
  43466. defines.DIFFUSE = false;
  43467. }
  43468. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43469. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43470. return false;
  43471. }
  43472. else {
  43473. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43474. }
  43475. }
  43476. else {
  43477. defines.AMBIENT = false;
  43478. }
  43479. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43480. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43481. return false;
  43482. }
  43483. else {
  43484. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43485. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43486. }
  43487. }
  43488. else {
  43489. defines.OPACITY = false;
  43490. }
  43491. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43492. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43493. return false;
  43494. }
  43495. else {
  43496. defines._needNormals = true;
  43497. defines.REFLECTION = true;
  43498. defines.ROUGHNESS = (this._roughness > 0);
  43499. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43500. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43501. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43502. switch (this._reflectionTexture.coordinatesMode) {
  43503. case BABYLON.Texture.EXPLICIT_MODE:
  43504. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43505. break;
  43506. case BABYLON.Texture.PLANAR_MODE:
  43507. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43508. break;
  43509. case BABYLON.Texture.PROJECTION_MODE:
  43510. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43511. break;
  43512. case BABYLON.Texture.SKYBOX_MODE:
  43513. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43514. break;
  43515. case BABYLON.Texture.SPHERICAL_MODE:
  43516. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43517. break;
  43518. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43519. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43520. break;
  43521. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43522. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43523. break;
  43524. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43525. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43526. break;
  43527. case BABYLON.Texture.CUBIC_MODE:
  43528. case BABYLON.Texture.INVCUBIC_MODE:
  43529. default:
  43530. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43531. break;
  43532. }
  43533. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43534. }
  43535. }
  43536. else {
  43537. defines.REFLECTION = false;
  43538. }
  43539. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43540. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43541. return false;
  43542. }
  43543. else {
  43544. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43545. }
  43546. }
  43547. else {
  43548. defines.EMISSIVE = false;
  43549. }
  43550. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43551. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43552. return false;
  43553. }
  43554. else {
  43555. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43556. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43557. }
  43558. }
  43559. else {
  43560. defines.LIGHTMAP = false;
  43561. }
  43562. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43563. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43564. return false;
  43565. }
  43566. else {
  43567. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43568. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43569. }
  43570. }
  43571. else {
  43572. defines.SPECULAR = false;
  43573. }
  43574. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43575. // Bump texure can not be not blocking.
  43576. if (!this._bumpTexture.isReady()) {
  43577. return false;
  43578. }
  43579. else {
  43580. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43581. defines.PARALLAX = this._useParallax;
  43582. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43583. }
  43584. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43585. }
  43586. else {
  43587. defines.BUMP = false;
  43588. }
  43589. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43590. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43591. return false;
  43592. }
  43593. else {
  43594. defines._needUVs = true;
  43595. defines.REFRACTION = true;
  43596. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43597. }
  43598. }
  43599. else {
  43600. defines.REFRACTION = false;
  43601. }
  43602. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43603. }
  43604. else {
  43605. defines.DIFFUSE = false;
  43606. defines.AMBIENT = false;
  43607. defines.OPACITY = false;
  43608. defines.REFLECTION = false;
  43609. defines.EMISSIVE = false;
  43610. defines.LIGHTMAP = false;
  43611. defines.BUMP = false;
  43612. defines.REFRACTION = false;
  43613. }
  43614. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43615. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43616. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43617. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43618. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43619. }
  43620. if (defines._areImageProcessingDirty) {
  43621. if (!this._imageProcessingConfiguration.isReady()) {
  43622. return false;
  43623. }
  43624. this._imageProcessingConfiguration.prepareDefines(defines);
  43625. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43626. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43627. }
  43628. if (defines._areFresnelDirty) {
  43629. if (StandardMaterial.FresnelEnabled) {
  43630. // Fresnel
  43631. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43632. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43633. this._reflectionFresnelParameters) {
  43634. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43635. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43636. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43637. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43638. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43639. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43640. defines._needNormals = true;
  43641. defines.FRESNEL = true;
  43642. }
  43643. }
  43644. else {
  43645. defines.FRESNEL = false;
  43646. }
  43647. }
  43648. // Misc.
  43649. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43650. // Attribs
  43651. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43652. // Values that need to be evaluated on every frame
  43653. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43654. // Get correct effect
  43655. if (defines.isDirty) {
  43656. defines.markAsProcessed();
  43657. scene.resetCachedMaterial();
  43658. // Fallbacks
  43659. var fallbacks = new BABYLON.EffectFallbacks();
  43660. if (defines.REFLECTION) {
  43661. fallbacks.addFallback(0, "REFLECTION");
  43662. }
  43663. if (defines.SPECULAR) {
  43664. fallbacks.addFallback(0, "SPECULAR");
  43665. }
  43666. if (defines.BUMP) {
  43667. fallbacks.addFallback(0, "BUMP");
  43668. }
  43669. if (defines.PARALLAX) {
  43670. fallbacks.addFallback(1, "PARALLAX");
  43671. }
  43672. if (defines.PARALLAXOCCLUSION) {
  43673. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43674. }
  43675. if (defines.SPECULAROVERALPHA) {
  43676. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43677. }
  43678. if (defines.FOG) {
  43679. fallbacks.addFallback(1, "FOG");
  43680. }
  43681. if (defines.POINTSIZE) {
  43682. fallbacks.addFallback(0, "POINTSIZE");
  43683. }
  43684. if (defines.LOGARITHMICDEPTH) {
  43685. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43686. }
  43687. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43688. if (defines.SPECULARTERM) {
  43689. fallbacks.addFallback(0, "SPECULARTERM");
  43690. }
  43691. if (defines.DIFFUSEFRESNEL) {
  43692. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43693. }
  43694. if (defines.OPACITYFRESNEL) {
  43695. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43696. }
  43697. if (defines.REFLECTIONFRESNEL) {
  43698. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43699. }
  43700. if (defines.EMISSIVEFRESNEL) {
  43701. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43702. }
  43703. if (defines.FRESNEL) {
  43704. fallbacks.addFallback(4, "FRESNEL");
  43705. }
  43706. //Attributes
  43707. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43708. if (defines.NORMAL) {
  43709. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43710. }
  43711. if (defines.UV1) {
  43712. attribs.push(BABYLON.VertexBuffer.UVKind);
  43713. }
  43714. if (defines.UV2) {
  43715. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43716. }
  43717. if (defines.VERTEXCOLOR) {
  43718. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43719. }
  43720. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43721. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43722. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43723. var shaderName = "default";
  43724. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43725. "vFogInfos", "vFogColor", "pointSize",
  43726. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43727. "mBones",
  43728. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43729. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43730. "vReflectionPosition", "vReflectionSize",
  43731. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43732. ];
  43733. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43734. var uniformBuffers = ["Material", "Scene"];
  43735. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43736. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43737. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43738. uniformsNames: uniforms,
  43739. uniformBuffersNames: uniformBuffers,
  43740. samplers: samplers,
  43741. defines: defines,
  43742. maxSimultaneousLights: this._maxSimultaneousLights
  43743. });
  43744. if (this.customShaderNameResolve) {
  43745. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43746. }
  43747. var join = defines.toString();
  43748. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43749. attributes: attribs,
  43750. uniformsNames: uniforms,
  43751. uniformBuffersNames: uniformBuffers,
  43752. samplers: samplers,
  43753. defines: join,
  43754. fallbacks: fallbacks,
  43755. onCompiled: this.onCompiled,
  43756. onError: this.onError,
  43757. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43758. }, engine), defines);
  43759. this.buildUniformLayout();
  43760. }
  43761. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43762. return false;
  43763. }
  43764. defines._renderId = scene.getRenderId();
  43765. this._wasPreviouslyReady = true;
  43766. return true;
  43767. };
  43768. StandardMaterial.prototype.buildUniformLayout = function () {
  43769. // Order is important !
  43770. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43771. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43772. this._uniformBuffer.addUniform("opacityParts", 4);
  43773. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43774. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43775. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43776. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43777. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43778. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43779. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43780. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43781. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43782. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43783. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43784. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43785. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43786. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43787. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43788. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43789. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43790. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43791. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43792. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43793. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43794. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43795. this._uniformBuffer.addUniform("specularMatrix", 16);
  43796. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43797. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43798. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43799. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43800. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43801. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43802. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43803. this._uniformBuffer.addUniform("pointSize", 1);
  43804. this._uniformBuffer.create();
  43805. };
  43806. StandardMaterial.prototype.unbind = function () {
  43807. if (this._activeEffect) {
  43808. var needFlag = false;
  43809. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43810. this._activeEffect.setTexture("reflection2DSampler", null);
  43811. needFlag = true;
  43812. }
  43813. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43814. this._activeEffect.setTexture("refraction2DSampler", null);
  43815. needFlag = true;
  43816. }
  43817. if (needFlag) {
  43818. this._markAllSubMeshesAsTexturesDirty();
  43819. }
  43820. }
  43821. _super.prototype.unbind.call(this);
  43822. };
  43823. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43824. var scene = this.getScene();
  43825. var defines = subMesh._materialDefines;
  43826. if (!defines) {
  43827. return;
  43828. }
  43829. var effect = subMesh.effect;
  43830. if (!effect) {
  43831. return;
  43832. }
  43833. this._activeEffect = effect;
  43834. // Matrices
  43835. this.bindOnlyWorldMatrix(world);
  43836. // Normal Matrix
  43837. if (defines.OBJECTSPACE_NORMALMAP) {
  43838. world.toNormalMatrix(this._normalMatrix);
  43839. this.bindOnlyNormalMatrix(this._normalMatrix);
  43840. }
  43841. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43842. // Bones
  43843. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43844. if (mustRebind) {
  43845. this._uniformBuffer.bindToEffect(effect, "Material");
  43846. this.bindViewProjection(effect);
  43847. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43848. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43849. // Fresnel
  43850. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43851. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43852. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43853. }
  43854. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43855. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43856. }
  43857. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43858. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43859. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43860. }
  43861. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43862. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43863. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43864. }
  43865. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43866. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43867. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43868. }
  43869. }
  43870. // Textures
  43871. if (scene.texturesEnabled) {
  43872. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43873. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43874. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43875. if (this._diffuseTexture.hasAlpha) {
  43876. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43877. }
  43878. }
  43879. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43880. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43881. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43882. }
  43883. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43884. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43885. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43886. }
  43887. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43888. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43889. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43890. if (this._reflectionTexture.boundingBoxSize) {
  43891. var cubeTexture = this._reflectionTexture;
  43892. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43893. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43894. }
  43895. }
  43896. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43897. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43898. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43899. }
  43900. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43901. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43902. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43903. }
  43904. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43905. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43906. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43907. }
  43908. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43909. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43910. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43911. if (scene._mirroredCameraPosition) {
  43912. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43913. }
  43914. else {
  43915. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43916. }
  43917. }
  43918. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43919. var depth = 1.0;
  43920. if (!this._refractionTexture.isCube) {
  43921. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43922. if (this._refractionTexture.depth) {
  43923. depth = this._refractionTexture.depth;
  43924. }
  43925. }
  43926. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43927. }
  43928. }
  43929. // Point size
  43930. if (this.pointsCloud) {
  43931. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43932. }
  43933. if (defines.SPECULARTERM) {
  43934. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43935. }
  43936. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43937. // Diffuse
  43938. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43939. }
  43940. // Textures
  43941. if (scene.texturesEnabled) {
  43942. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43943. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43944. }
  43945. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43946. effect.setTexture("ambientSampler", this._ambientTexture);
  43947. }
  43948. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43949. effect.setTexture("opacitySampler", this._opacityTexture);
  43950. }
  43951. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43952. if (this._reflectionTexture.isCube) {
  43953. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43954. }
  43955. else {
  43956. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43957. }
  43958. }
  43959. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43960. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43961. }
  43962. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43963. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43964. }
  43965. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43966. effect.setTexture("specularSampler", this._specularTexture);
  43967. }
  43968. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43969. effect.setTexture("bumpSampler", this._bumpTexture);
  43970. }
  43971. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43972. var depth = 1.0;
  43973. if (this._refractionTexture.isCube) {
  43974. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43975. }
  43976. else {
  43977. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43978. }
  43979. }
  43980. }
  43981. // Clip plane
  43982. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43983. // Colors
  43984. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43985. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43986. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43987. }
  43988. if (mustRebind || !this.isFrozen) {
  43989. // Lights
  43990. if (scene.lightsEnabled && !this._disableLighting) {
  43991. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43992. }
  43993. // View
  43994. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43995. this.bindView(effect);
  43996. }
  43997. // Fog
  43998. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43999. // Morph targets
  44000. if (defines.NUM_MORPH_INFLUENCERS) {
  44001. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  44002. }
  44003. // Log. depth
  44004. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  44005. // image processing
  44006. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  44007. this._imageProcessingConfiguration.bind(this._activeEffect);
  44008. }
  44009. }
  44010. this._uniformBuffer.update();
  44011. this._afterBind(mesh, this._activeEffect);
  44012. };
  44013. StandardMaterial.prototype.getAnimatables = function () {
  44014. var results = [];
  44015. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  44016. results.push(this._diffuseTexture);
  44017. }
  44018. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44019. results.push(this._ambientTexture);
  44020. }
  44021. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44022. results.push(this._opacityTexture);
  44023. }
  44024. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44025. results.push(this._reflectionTexture);
  44026. }
  44027. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44028. results.push(this._emissiveTexture);
  44029. }
  44030. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  44031. results.push(this._specularTexture);
  44032. }
  44033. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44034. results.push(this._bumpTexture);
  44035. }
  44036. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44037. results.push(this._lightmapTexture);
  44038. }
  44039. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44040. results.push(this._refractionTexture);
  44041. }
  44042. return results;
  44043. };
  44044. StandardMaterial.prototype.getActiveTextures = function () {
  44045. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44046. if (this._diffuseTexture) {
  44047. activeTextures.push(this._diffuseTexture);
  44048. }
  44049. if (this._ambientTexture) {
  44050. activeTextures.push(this._ambientTexture);
  44051. }
  44052. if (this._opacityTexture) {
  44053. activeTextures.push(this._opacityTexture);
  44054. }
  44055. if (this._reflectionTexture) {
  44056. activeTextures.push(this._reflectionTexture);
  44057. }
  44058. if (this._emissiveTexture) {
  44059. activeTextures.push(this._emissiveTexture);
  44060. }
  44061. if (this._specularTexture) {
  44062. activeTextures.push(this._specularTexture);
  44063. }
  44064. if (this._bumpTexture) {
  44065. activeTextures.push(this._bumpTexture);
  44066. }
  44067. if (this._lightmapTexture) {
  44068. activeTextures.push(this._lightmapTexture);
  44069. }
  44070. if (this._refractionTexture) {
  44071. activeTextures.push(this._refractionTexture);
  44072. }
  44073. return activeTextures;
  44074. };
  44075. StandardMaterial.prototype.hasTexture = function (texture) {
  44076. if (_super.prototype.hasTexture.call(this, texture)) {
  44077. return true;
  44078. }
  44079. if (this._diffuseTexture === texture) {
  44080. return true;
  44081. }
  44082. if (this._ambientTexture === texture) {
  44083. return true;
  44084. }
  44085. if (this._opacityTexture === texture) {
  44086. return true;
  44087. }
  44088. if (this._reflectionTexture === texture) {
  44089. return true;
  44090. }
  44091. if (this._emissiveTexture === texture) {
  44092. return true;
  44093. }
  44094. if (this._specularTexture === texture) {
  44095. return true;
  44096. }
  44097. if (this._bumpTexture === texture) {
  44098. return true;
  44099. }
  44100. if (this._lightmapTexture === texture) {
  44101. return true;
  44102. }
  44103. if (this._refractionTexture === texture) {
  44104. return true;
  44105. }
  44106. return false;
  44107. };
  44108. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44109. if (forceDisposeTextures) {
  44110. if (this._diffuseTexture) {
  44111. this._diffuseTexture.dispose();
  44112. }
  44113. if (this._ambientTexture) {
  44114. this._ambientTexture.dispose();
  44115. }
  44116. if (this._opacityTexture) {
  44117. this._opacityTexture.dispose();
  44118. }
  44119. if (this._reflectionTexture) {
  44120. this._reflectionTexture.dispose();
  44121. }
  44122. if (this._emissiveTexture) {
  44123. this._emissiveTexture.dispose();
  44124. }
  44125. if (this._specularTexture) {
  44126. this._specularTexture.dispose();
  44127. }
  44128. if (this._bumpTexture) {
  44129. this._bumpTexture.dispose();
  44130. }
  44131. if (this._lightmapTexture) {
  44132. this._lightmapTexture.dispose();
  44133. }
  44134. if (this._refractionTexture) {
  44135. this._refractionTexture.dispose();
  44136. }
  44137. }
  44138. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44139. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44140. }
  44141. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44142. };
  44143. StandardMaterial.prototype.clone = function (name) {
  44144. var _this = this;
  44145. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44146. result.name = name;
  44147. result.id = name;
  44148. return result;
  44149. };
  44150. StandardMaterial.prototype.serialize = function () {
  44151. return BABYLON.SerializationHelper.Serialize(this);
  44152. };
  44153. // Statics
  44154. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44155. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44156. };
  44157. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44158. get: function () {
  44159. return StandardMaterial._DiffuseTextureEnabled;
  44160. },
  44161. set: function (value) {
  44162. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44163. return;
  44164. }
  44165. StandardMaterial._DiffuseTextureEnabled = value;
  44166. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44167. },
  44168. enumerable: true,
  44169. configurable: true
  44170. });
  44171. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44172. get: function () {
  44173. return StandardMaterial._AmbientTextureEnabled;
  44174. },
  44175. set: function (value) {
  44176. if (StandardMaterial._AmbientTextureEnabled === value) {
  44177. return;
  44178. }
  44179. StandardMaterial._AmbientTextureEnabled = value;
  44180. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44181. },
  44182. enumerable: true,
  44183. configurable: true
  44184. });
  44185. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44186. get: function () {
  44187. return StandardMaterial._OpacityTextureEnabled;
  44188. },
  44189. set: function (value) {
  44190. if (StandardMaterial._OpacityTextureEnabled === value) {
  44191. return;
  44192. }
  44193. StandardMaterial._OpacityTextureEnabled = value;
  44194. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44195. },
  44196. enumerable: true,
  44197. configurable: true
  44198. });
  44199. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44200. get: function () {
  44201. return StandardMaterial._ReflectionTextureEnabled;
  44202. },
  44203. set: function (value) {
  44204. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44205. return;
  44206. }
  44207. StandardMaterial._ReflectionTextureEnabled = value;
  44208. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44209. },
  44210. enumerable: true,
  44211. configurable: true
  44212. });
  44213. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44214. get: function () {
  44215. return StandardMaterial._EmissiveTextureEnabled;
  44216. },
  44217. set: function (value) {
  44218. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44219. return;
  44220. }
  44221. StandardMaterial._EmissiveTextureEnabled = value;
  44222. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44223. },
  44224. enumerable: true,
  44225. configurable: true
  44226. });
  44227. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44228. get: function () {
  44229. return StandardMaterial._SpecularTextureEnabled;
  44230. },
  44231. set: function (value) {
  44232. if (StandardMaterial._SpecularTextureEnabled === value) {
  44233. return;
  44234. }
  44235. StandardMaterial._SpecularTextureEnabled = value;
  44236. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44237. },
  44238. enumerable: true,
  44239. configurable: true
  44240. });
  44241. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44242. get: function () {
  44243. return StandardMaterial._BumpTextureEnabled;
  44244. },
  44245. set: function (value) {
  44246. if (StandardMaterial._BumpTextureEnabled === value) {
  44247. return;
  44248. }
  44249. StandardMaterial._BumpTextureEnabled = value;
  44250. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44251. },
  44252. enumerable: true,
  44253. configurable: true
  44254. });
  44255. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44256. get: function () {
  44257. return StandardMaterial._LightmapTextureEnabled;
  44258. },
  44259. set: function (value) {
  44260. if (StandardMaterial._LightmapTextureEnabled === value) {
  44261. return;
  44262. }
  44263. StandardMaterial._LightmapTextureEnabled = value;
  44264. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44265. },
  44266. enumerable: true,
  44267. configurable: true
  44268. });
  44269. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44270. get: function () {
  44271. return StandardMaterial._RefractionTextureEnabled;
  44272. },
  44273. set: function (value) {
  44274. if (StandardMaterial._RefractionTextureEnabled === value) {
  44275. return;
  44276. }
  44277. StandardMaterial._RefractionTextureEnabled = value;
  44278. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44279. },
  44280. enumerable: true,
  44281. configurable: true
  44282. });
  44283. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44284. get: function () {
  44285. return StandardMaterial._ColorGradingTextureEnabled;
  44286. },
  44287. set: function (value) {
  44288. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44289. return;
  44290. }
  44291. StandardMaterial._ColorGradingTextureEnabled = value;
  44292. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44293. },
  44294. enumerable: true,
  44295. configurable: true
  44296. });
  44297. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44298. get: function () {
  44299. return StandardMaterial._FresnelEnabled;
  44300. },
  44301. set: function (value) {
  44302. if (StandardMaterial._FresnelEnabled === value) {
  44303. return;
  44304. }
  44305. StandardMaterial._FresnelEnabled = value;
  44306. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44307. },
  44308. enumerable: true,
  44309. configurable: true
  44310. });
  44311. // Flags used to enable or disable a type of texture for all Standard Materials
  44312. StandardMaterial._DiffuseTextureEnabled = true;
  44313. StandardMaterial._AmbientTextureEnabled = true;
  44314. StandardMaterial._OpacityTextureEnabled = true;
  44315. StandardMaterial._ReflectionTextureEnabled = true;
  44316. StandardMaterial._EmissiveTextureEnabled = true;
  44317. StandardMaterial._SpecularTextureEnabled = true;
  44318. StandardMaterial._BumpTextureEnabled = true;
  44319. StandardMaterial._LightmapTextureEnabled = true;
  44320. StandardMaterial._RefractionTextureEnabled = true;
  44321. StandardMaterial._ColorGradingTextureEnabled = true;
  44322. StandardMaterial._FresnelEnabled = true;
  44323. __decorate([
  44324. BABYLON.serializeAsTexture("diffuseTexture")
  44325. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44326. __decorate([
  44327. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44328. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44329. __decorate([
  44330. BABYLON.serializeAsTexture("ambientTexture")
  44331. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44332. __decorate([
  44333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44334. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44335. __decorate([
  44336. BABYLON.serializeAsTexture("opacityTexture")
  44337. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44338. __decorate([
  44339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44340. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44341. __decorate([
  44342. BABYLON.serializeAsTexture("reflectionTexture")
  44343. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44344. __decorate([
  44345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44346. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44347. __decorate([
  44348. BABYLON.serializeAsTexture("emissiveTexture")
  44349. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44350. __decorate([
  44351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44352. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44353. __decorate([
  44354. BABYLON.serializeAsTexture("specularTexture")
  44355. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44356. __decorate([
  44357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44358. ], StandardMaterial.prototype, "specularTexture", void 0);
  44359. __decorate([
  44360. BABYLON.serializeAsTexture("bumpTexture")
  44361. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44362. __decorate([
  44363. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44364. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44365. __decorate([
  44366. BABYLON.serializeAsTexture("lightmapTexture")
  44367. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44368. __decorate([
  44369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44370. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44371. __decorate([
  44372. BABYLON.serializeAsTexture("refractionTexture")
  44373. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44374. __decorate([
  44375. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44376. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44377. __decorate([
  44378. BABYLON.serializeAsColor3("ambient")
  44379. ], StandardMaterial.prototype, "ambientColor", void 0);
  44380. __decorate([
  44381. BABYLON.serializeAsColor3("diffuse")
  44382. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44383. __decorate([
  44384. BABYLON.serializeAsColor3("specular")
  44385. ], StandardMaterial.prototype, "specularColor", void 0);
  44386. __decorate([
  44387. BABYLON.serializeAsColor3("emissive")
  44388. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44389. __decorate([
  44390. BABYLON.serialize()
  44391. ], StandardMaterial.prototype, "specularPower", void 0);
  44392. __decorate([
  44393. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44394. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44395. __decorate([
  44396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44397. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44398. __decorate([
  44399. BABYLON.serialize("useEmissiveAsIllumination")
  44400. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44401. __decorate([
  44402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44403. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44404. __decorate([
  44405. BABYLON.serialize("linkEmissiveWithDiffuse")
  44406. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44407. __decorate([
  44408. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44409. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44410. __decorate([
  44411. BABYLON.serialize("useSpecularOverAlpha")
  44412. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44413. __decorate([
  44414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44415. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44416. __decorate([
  44417. BABYLON.serialize("useReflectionOverAlpha")
  44418. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44419. __decorate([
  44420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44421. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44422. __decorate([
  44423. BABYLON.serialize("disableLighting")
  44424. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44425. __decorate([
  44426. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44427. ], StandardMaterial.prototype, "disableLighting", void 0);
  44428. __decorate([
  44429. BABYLON.serialize("useObjectSpaceNormalMap")
  44430. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44431. __decorate([
  44432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44433. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44434. __decorate([
  44435. BABYLON.serialize("useParallax")
  44436. ], StandardMaterial.prototype, "_useParallax", void 0);
  44437. __decorate([
  44438. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44439. ], StandardMaterial.prototype, "useParallax", void 0);
  44440. __decorate([
  44441. BABYLON.serialize("useParallaxOcclusion")
  44442. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44443. __decorate([
  44444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44445. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44446. __decorate([
  44447. BABYLON.serialize()
  44448. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44449. __decorate([
  44450. BABYLON.serialize("roughness")
  44451. ], StandardMaterial.prototype, "_roughness", void 0);
  44452. __decorate([
  44453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44454. ], StandardMaterial.prototype, "roughness", void 0);
  44455. __decorate([
  44456. BABYLON.serialize()
  44457. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44458. __decorate([
  44459. BABYLON.serialize()
  44460. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44461. __decorate([
  44462. BABYLON.serialize()
  44463. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44464. __decorate([
  44465. BABYLON.serialize("useLightmapAsShadowmap")
  44466. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44467. __decorate([
  44468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44469. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44470. __decorate([
  44471. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44472. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44473. __decorate([
  44474. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44475. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44476. __decorate([
  44477. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44478. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44479. __decorate([
  44480. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44481. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44482. __decorate([
  44483. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44484. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44485. __decorate([
  44486. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44487. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44488. __decorate([
  44489. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44490. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44491. __decorate([
  44492. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44493. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44494. __decorate([
  44495. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44496. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44497. __decorate([
  44498. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44499. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44500. __decorate([
  44501. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44502. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44503. __decorate([
  44504. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44505. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44506. __decorate([
  44507. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44508. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44509. __decorate([
  44510. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44511. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44512. __decorate([
  44513. BABYLON.serialize("maxSimultaneousLights")
  44514. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44515. __decorate([
  44516. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44517. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44518. __decorate([
  44519. BABYLON.serialize("invertNormalMapX")
  44520. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44521. __decorate([
  44522. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44523. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44524. __decorate([
  44525. BABYLON.serialize("invertNormalMapY")
  44526. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44527. __decorate([
  44528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44529. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44530. __decorate([
  44531. BABYLON.serialize("twoSidedLighting")
  44532. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44533. __decorate([
  44534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44535. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44536. __decorate([
  44537. BABYLON.serialize()
  44538. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44539. return StandardMaterial;
  44540. }(BABYLON.PushMaterial));
  44541. BABYLON.StandardMaterial = StandardMaterial;
  44542. })(BABYLON || (BABYLON = {}));
  44543. //# sourceMappingURL=babylon.standardMaterial.js.map
  44544. var BABYLON;
  44545. (function (BABYLON) {
  44546. /**
  44547. * Manages the defines for the PBR Material.
  44548. * @hiddenChildren
  44549. */
  44550. var PBRMaterialDefines = /** @class */ (function (_super) {
  44551. __extends(PBRMaterialDefines, _super);
  44552. /**
  44553. * Initializes the PBR Material defines.
  44554. */
  44555. function PBRMaterialDefines() {
  44556. var _this = _super.call(this) || this;
  44557. _this.PBR = true;
  44558. _this.MAINUV1 = false;
  44559. _this.MAINUV2 = false;
  44560. _this.UV1 = false;
  44561. _this.UV2 = false;
  44562. _this.ALBEDO = false;
  44563. _this.ALBEDODIRECTUV = 0;
  44564. _this.VERTEXCOLOR = false;
  44565. _this.AMBIENT = false;
  44566. _this.AMBIENTDIRECTUV = 0;
  44567. _this.AMBIENTINGRAYSCALE = false;
  44568. _this.OPACITY = false;
  44569. _this.VERTEXALPHA = false;
  44570. _this.OPACITYDIRECTUV = 0;
  44571. _this.OPACITYRGB = false;
  44572. _this.ALPHATEST = false;
  44573. _this.DEPTHPREPASS = false;
  44574. _this.ALPHABLEND = false;
  44575. _this.ALPHAFROMALBEDO = false;
  44576. _this.ALPHATESTVALUE = "0.5";
  44577. _this.SPECULAROVERALPHA = false;
  44578. _this.RADIANCEOVERALPHA = false;
  44579. _this.ALPHAFRESNEL = false;
  44580. _this.LINEARALPHAFRESNEL = false;
  44581. _this.PREMULTIPLYALPHA = false;
  44582. _this.EMISSIVE = false;
  44583. _this.EMISSIVEDIRECTUV = 0;
  44584. _this.REFLECTIVITY = false;
  44585. _this.REFLECTIVITYDIRECTUV = 0;
  44586. _this.SPECULARTERM = false;
  44587. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44588. _this.MICROSURFACEAUTOMATIC = false;
  44589. _this.LODBASEDMICROSFURACE = false;
  44590. _this.MICROSURFACEMAP = false;
  44591. _this.MICROSURFACEMAPDIRECTUV = 0;
  44592. _this.METALLICWORKFLOW = false;
  44593. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44594. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44595. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44596. _this.AOSTOREINMETALMAPRED = false;
  44597. _this.ENVIRONMENTBRDF = false;
  44598. _this.NORMAL = false;
  44599. _this.TANGENT = false;
  44600. _this.BUMP = false;
  44601. _this.BUMPDIRECTUV = 0;
  44602. _this.OBJECTSPACE_NORMALMAP = false;
  44603. _this.PARALLAX = false;
  44604. _this.PARALLAXOCCLUSION = false;
  44605. _this.NORMALXYSCALE = true;
  44606. _this.LIGHTMAP = false;
  44607. _this.LIGHTMAPDIRECTUV = 0;
  44608. _this.USELIGHTMAPASSHADOWMAP = false;
  44609. _this.GAMMALIGHTMAP = false;
  44610. _this.REFLECTION = false;
  44611. _this.REFLECTIONMAP_3D = false;
  44612. _this.REFLECTIONMAP_SPHERICAL = false;
  44613. _this.REFLECTIONMAP_PLANAR = false;
  44614. _this.REFLECTIONMAP_CUBIC = false;
  44615. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44616. _this.REFLECTIONMAP_PROJECTION = false;
  44617. _this.REFLECTIONMAP_SKYBOX = false;
  44618. _this.REFLECTIONMAP_EXPLICIT = false;
  44619. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44620. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44621. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44622. _this.INVERTCUBICMAP = false;
  44623. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44624. _this.USESPHERICALINVERTEX = false;
  44625. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44626. _this.LODINREFLECTIONALPHA = false;
  44627. _this.GAMMAREFLECTION = false;
  44628. _this.RADIANCEOCCLUSION = false;
  44629. _this.HORIZONOCCLUSION = false;
  44630. _this.REFRACTION = false;
  44631. _this.REFRACTIONMAP_3D = false;
  44632. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44633. _this.LODINREFRACTIONALPHA = false;
  44634. _this.GAMMAREFRACTION = false;
  44635. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44636. _this.INSTANCES = false;
  44637. _this.NUM_BONE_INFLUENCERS = 0;
  44638. _this.BonesPerMesh = 0;
  44639. _this.NONUNIFORMSCALING = false;
  44640. _this.MORPHTARGETS = false;
  44641. _this.MORPHTARGETS_NORMAL = false;
  44642. _this.MORPHTARGETS_TANGENT = false;
  44643. _this.NUM_MORPH_INFLUENCERS = 0;
  44644. _this.IMAGEPROCESSING = false;
  44645. _this.VIGNETTE = false;
  44646. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44647. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44648. _this.TONEMAPPING = false;
  44649. _this.CONTRAST = false;
  44650. _this.COLORCURVES = false;
  44651. _this.COLORGRADING = false;
  44652. _this.COLORGRADING3D = false;
  44653. _this.SAMPLER3DGREENDEPTH = false;
  44654. _this.SAMPLER3DBGRMAP = false;
  44655. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44656. _this.EXPOSURE = false;
  44657. _this.USEPHYSICALLIGHTFALLOFF = false;
  44658. _this.TWOSIDEDLIGHTING = false;
  44659. _this.SHADOWFLOAT = false;
  44660. _this.CLIPPLANE = false;
  44661. _this.POINTSIZE = false;
  44662. _this.FOG = false;
  44663. _this.LOGARITHMICDEPTH = false;
  44664. _this.FORCENORMALFORWARD = false;
  44665. _this.SPECULARAA = false;
  44666. _this.UNLIT = false;
  44667. _this.rebuild();
  44668. return _this;
  44669. }
  44670. /**
  44671. * Resets the PBR Material defines.
  44672. */
  44673. PBRMaterialDefines.prototype.reset = function () {
  44674. _super.prototype.reset.call(this);
  44675. this.ALPHATESTVALUE = "0.5";
  44676. this.PBR = true;
  44677. };
  44678. return PBRMaterialDefines;
  44679. }(BABYLON.MaterialDefines));
  44680. /**
  44681. * The Physically based material base class of BJS.
  44682. *
  44683. * This offers the main features of a standard PBR material.
  44684. * For more information, please refer to the documentation :
  44685. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44686. */
  44687. var PBRBaseMaterial = /** @class */ (function (_super) {
  44688. __extends(PBRBaseMaterial, _super);
  44689. /**
  44690. * Instantiates a new PBRMaterial instance.
  44691. *
  44692. * @param name The material name
  44693. * @param scene The scene the material will be use in.
  44694. */
  44695. function PBRBaseMaterial(name, scene) {
  44696. var _this = _super.call(this, name, scene) || this;
  44697. /**
  44698. * Intensity of the direct lights e.g. the four lights available in your scene.
  44699. * This impacts both the direct diffuse and specular highlights.
  44700. */
  44701. _this._directIntensity = 1.0;
  44702. /**
  44703. * Intensity of the emissive part of the material.
  44704. * This helps controlling the emissive effect without modifying the emissive color.
  44705. */
  44706. _this._emissiveIntensity = 1.0;
  44707. /**
  44708. * Intensity of the environment e.g. how much the environment will light the object
  44709. * either through harmonics for rough material or through the refelction for shiny ones.
  44710. */
  44711. _this._environmentIntensity = 1.0;
  44712. /**
  44713. * This is a special control allowing the reduction of the specular highlights coming from the
  44714. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44715. */
  44716. _this._specularIntensity = 1.0;
  44717. /**
  44718. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44719. */
  44720. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44721. /**
  44722. * Debug Control allowing disabling the bump map on this material.
  44723. */
  44724. _this._disableBumpMap = false;
  44725. /**
  44726. * AKA Occlusion Texture Intensity in other nomenclature.
  44727. */
  44728. _this._ambientTextureStrength = 1.0;
  44729. /**
  44730. * The color of a material in ambient lighting.
  44731. */
  44732. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44733. /**
  44734. * AKA Diffuse Color in other nomenclature.
  44735. */
  44736. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44737. /**
  44738. * AKA Specular Color in other nomenclature.
  44739. */
  44740. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44741. /**
  44742. * The color applied when light is reflected from a material.
  44743. */
  44744. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44745. /**
  44746. * The color applied when light is emitted from a material.
  44747. */
  44748. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44749. /**
  44750. * AKA Glossiness in other nomenclature.
  44751. */
  44752. _this._microSurface = 0.9;
  44753. /**
  44754. * source material index of refraction (IOR)' / 'destination material IOR.
  44755. */
  44756. _this._indexOfRefraction = 0.66;
  44757. /**
  44758. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44759. */
  44760. _this._invertRefractionY = false;
  44761. /**
  44762. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44763. * Materials half opaque for instance using refraction could benefit from this control.
  44764. */
  44765. _this._linkRefractionWithTransparency = false;
  44766. /**
  44767. * Specifies that the material will use the light map as a show map.
  44768. */
  44769. _this._useLightmapAsShadowmap = false;
  44770. /**
  44771. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44772. * makes the reflect vector face the model (under horizon).
  44773. */
  44774. _this._useHorizonOcclusion = true;
  44775. /**
  44776. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44777. * too much the area relying on ambient texture to define their ambient occlusion.
  44778. */
  44779. _this._useRadianceOcclusion = true;
  44780. /**
  44781. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44782. */
  44783. _this._useAlphaFromAlbedoTexture = false;
  44784. /**
  44785. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44786. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44787. */
  44788. _this._useSpecularOverAlpha = true;
  44789. /**
  44790. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44791. */
  44792. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44793. /**
  44794. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44795. */
  44796. _this._useRoughnessFromMetallicTextureAlpha = true;
  44797. /**
  44798. * Specifies if the metallic texture contains the roughness information in its green channel.
  44799. */
  44800. _this._useRoughnessFromMetallicTextureGreen = false;
  44801. /**
  44802. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44803. */
  44804. _this._useMetallnessFromMetallicTextureBlue = false;
  44805. /**
  44806. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44807. */
  44808. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44809. /**
  44810. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44811. */
  44812. _this._useAmbientInGrayScale = false;
  44813. /**
  44814. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44815. * The material will try to infer what glossiness each pixel should be.
  44816. */
  44817. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44818. /**
  44819. * BJS is using an harcoded light falloff based on a manually sets up range.
  44820. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44821. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44822. */
  44823. _this._usePhysicalLightFalloff = true;
  44824. /**
  44825. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44826. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44827. */
  44828. _this._useRadianceOverAlpha = true;
  44829. /**
  44830. * Allows using an object space normal map (instead of tangent space).
  44831. */
  44832. _this._useObjectSpaceNormalMap = false;
  44833. /**
  44834. * Allows using the bump map in parallax mode.
  44835. */
  44836. _this._useParallax = false;
  44837. /**
  44838. * Allows using the bump map in parallax occlusion mode.
  44839. */
  44840. _this._useParallaxOcclusion = false;
  44841. /**
  44842. * Controls the scale bias of the parallax mode.
  44843. */
  44844. _this._parallaxScaleBias = 0.05;
  44845. /**
  44846. * If sets to true, disables all the lights affecting the material.
  44847. */
  44848. _this._disableLighting = false;
  44849. /**
  44850. * Number of Simultaneous lights allowed on the material.
  44851. */
  44852. _this._maxSimultaneousLights = 4;
  44853. /**
  44854. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44855. */
  44856. _this._invertNormalMapX = false;
  44857. /**
  44858. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44859. */
  44860. _this._invertNormalMapY = false;
  44861. /**
  44862. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44863. */
  44864. _this._twoSidedLighting = false;
  44865. /**
  44866. * Defines the alpha limits in alpha test mode.
  44867. */
  44868. _this._alphaCutOff = 0.4;
  44869. /**
  44870. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44871. */
  44872. _this._forceAlphaTest = false;
  44873. /**
  44874. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44875. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44876. */
  44877. _this._useAlphaFresnel = false;
  44878. /**
  44879. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44880. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44881. */
  44882. _this._useLinearAlphaFresnel = false;
  44883. /**
  44884. * The transparency mode of the material.
  44885. */
  44886. _this._transparencyMode = null;
  44887. /**
  44888. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44889. * from cos thetav and roughness:
  44890. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44891. */
  44892. _this._environmentBRDFTexture = null;
  44893. /**
  44894. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44895. */
  44896. _this._forceIrradianceInFragment = false;
  44897. /**
  44898. * Force normal to face away from face.
  44899. */
  44900. _this._forceNormalForward = false;
  44901. /**
  44902. * Enables specular anti aliasing in the PBR shader.
  44903. * It will both interacts on the Geometry for analytical and IBL lighting.
  44904. * It also prefilter the roughness map based on the bump values.
  44905. */
  44906. _this._enableSpecularAntiAliasing = false;
  44907. /**
  44908. * Stores the available render targets.
  44909. */
  44910. _this._renderTargets = new BABYLON.SmartArray(16);
  44911. /**
  44912. * Sets the global ambient color for the material used in lighting calculations.
  44913. */
  44914. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44915. /**
  44916. * If set to true, no lighting calculations will be applied.
  44917. */
  44918. _this._unlit = false;
  44919. // Setup the default processing configuration to the scene.
  44920. _this._attachImageProcessingConfiguration(null);
  44921. _this.getRenderTargetTextures = function () {
  44922. _this._renderTargets.reset();
  44923. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44924. _this._renderTargets.push(_this._reflectionTexture);
  44925. }
  44926. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44927. _this._renderTargets.push(_this._refractionTexture);
  44928. }
  44929. return _this._renderTargets;
  44930. };
  44931. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44932. return _this;
  44933. }
  44934. /**
  44935. * Attaches a new image processing configuration to the PBR Material.
  44936. * @param configuration
  44937. */
  44938. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44939. var _this = this;
  44940. if (configuration === this._imageProcessingConfiguration) {
  44941. return;
  44942. }
  44943. // Detaches observer.
  44944. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44945. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44946. }
  44947. // Pick the scene configuration if needed.
  44948. if (!configuration) {
  44949. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44950. }
  44951. else {
  44952. this._imageProcessingConfiguration = configuration;
  44953. }
  44954. // Attaches observer.
  44955. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44956. _this._markAllSubMeshesAsImageProcessingDirty();
  44957. });
  44958. };
  44959. /**
  44960. * Gets the name of the material class.
  44961. */
  44962. PBRBaseMaterial.prototype.getClassName = function () {
  44963. return "PBRBaseMaterial";
  44964. };
  44965. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44966. /**
  44967. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44968. */
  44969. get: function () {
  44970. return this._useLogarithmicDepth;
  44971. },
  44972. /**
  44973. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44974. */
  44975. set: function (value) {
  44976. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44977. },
  44978. enumerable: true,
  44979. configurable: true
  44980. });
  44981. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44982. /**
  44983. * Gets the current transparency mode.
  44984. */
  44985. get: function () {
  44986. return this._transparencyMode;
  44987. },
  44988. /**
  44989. * Sets the transparency mode of the material.
  44990. */
  44991. set: function (value) {
  44992. if (this._transparencyMode === value) {
  44993. return;
  44994. }
  44995. this._transparencyMode = value;
  44996. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44997. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44998. },
  44999. enumerable: true,
  45000. configurable: true
  45001. });
  45002. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  45003. /**
  45004. * Returns true if alpha blending should be disabled.
  45005. */
  45006. get: function () {
  45007. return (this._linkRefractionWithTransparency ||
  45008. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  45009. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45010. },
  45011. enumerable: true,
  45012. configurable: true
  45013. });
  45014. /**
  45015. * Specifies whether or not this material should be rendered in alpha blend mode.
  45016. */
  45017. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  45018. if (this._disableAlphaBlending) {
  45019. return false;
  45020. }
  45021. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  45022. };
  45023. /**
  45024. * Specifies if the mesh will require alpha blending.
  45025. * @param mesh - BJS mesh.
  45026. */
  45027. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  45028. if (this._disableAlphaBlending) {
  45029. return false;
  45030. }
  45031. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  45032. };
  45033. /**
  45034. * Specifies whether or not this material should be rendered in alpha test mode.
  45035. */
  45036. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  45037. if (this._forceAlphaTest) {
  45038. return true;
  45039. }
  45040. if (this._linkRefractionWithTransparency) {
  45041. return false;
  45042. }
  45043. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45044. };
  45045. /**
  45046. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  45047. */
  45048. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  45049. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  45050. };
  45051. /**
  45052. * Gets the texture used for the alpha test.
  45053. */
  45054. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  45055. return this._albedoTexture;
  45056. };
  45057. /**
  45058. * Specifies that the submesh is ready to be used.
  45059. * @param mesh - BJS mesh.
  45060. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  45061. * @param useInstances - Specifies that instances should be used.
  45062. * @returns - boolean indicating that the submesh is ready or not.
  45063. */
  45064. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  45065. if (subMesh.effect && this.isFrozen) {
  45066. if (this._wasPreviouslyReady) {
  45067. return true;
  45068. }
  45069. }
  45070. if (!subMesh._materialDefines) {
  45071. subMesh._materialDefines = new PBRMaterialDefines();
  45072. }
  45073. var defines = subMesh._materialDefines;
  45074. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  45075. if (defines._renderId === this.getScene().getRenderId()) {
  45076. return true;
  45077. }
  45078. }
  45079. var scene = this.getScene();
  45080. var engine = scene.getEngine();
  45081. if (defines._areTexturesDirty) {
  45082. if (scene.texturesEnabled) {
  45083. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45084. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  45085. return false;
  45086. }
  45087. }
  45088. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45089. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  45090. return false;
  45091. }
  45092. }
  45093. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45094. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  45095. return false;
  45096. }
  45097. }
  45098. var reflectionTexture = this._getReflectionTexture();
  45099. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45100. if (!reflectionTexture.isReadyOrNotBlocking()) {
  45101. return false;
  45102. }
  45103. }
  45104. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45105. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  45106. return false;
  45107. }
  45108. }
  45109. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45110. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  45111. return false;
  45112. }
  45113. }
  45114. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45115. if (this._metallicTexture) {
  45116. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  45117. return false;
  45118. }
  45119. }
  45120. else if (this._reflectivityTexture) {
  45121. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  45122. return false;
  45123. }
  45124. }
  45125. if (this._microSurfaceTexture) {
  45126. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  45127. return false;
  45128. }
  45129. }
  45130. }
  45131. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45132. // Bump texture cannot be not blocking.
  45133. if (!this._bumpTexture.isReady()) {
  45134. return false;
  45135. }
  45136. }
  45137. var refractionTexture = this._getRefractionTexture();
  45138. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45139. if (!refractionTexture.isReadyOrNotBlocking()) {
  45140. return false;
  45141. }
  45142. }
  45143. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45144. // This is blocking.
  45145. if (!this._environmentBRDFTexture.isReady()) {
  45146. return false;
  45147. }
  45148. }
  45149. }
  45150. }
  45151. if (defines._areImageProcessingDirty) {
  45152. if (!this._imageProcessingConfiguration.isReady()) {
  45153. return false;
  45154. }
  45155. }
  45156. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45157. mesh.createNormals(true);
  45158. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  45159. }
  45160. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  45161. if (effect) {
  45162. scene.resetCachedMaterial();
  45163. subMesh.setEffect(effect, defines);
  45164. this.buildUniformLayout();
  45165. }
  45166. if (!subMesh.effect || !subMesh.effect.isReady()) {
  45167. return false;
  45168. }
  45169. defines._renderId = scene.getRenderId();
  45170. this._wasPreviouslyReady = true;
  45171. return true;
  45172. };
  45173. /**
  45174. * Specifies if the material uses metallic roughness workflow.
  45175. * @returns boolean specifiying if the material uses metallic roughness workflow.
  45176. */
  45177. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  45178. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  45179. return true;
  45180. }
  45181. return false;
  45182. };
  45183. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  45184. if (onCompiled === void 0) { onCompiled = null; }
  45185. if (onError === void 0) { onError = null; }
  45186. if (useInstances === void 0) { useInstances = null; }
  45187. if (useClipPlane === void 0) { useClipPlane = null; }
  45188. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  45189. if (!defines.isDirty) {
  45190. return null;
  45191. }
  45192. defines.markAsProcessed();
  45193. var scene = this.getScene();
  45194. var engine = scene.getEngine();
  45195. // Fallbacks
  45196. var fallbacks = new BABYLON.EffectFallbacks();
  45197. var fallbackRank = 0;
  45198. if (defines.USESPHERICALINVERTEX) {
  45199. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  45200. }
  45201. if (defines.FOG) {
  45202. fallbacks.addFallback(fallbackRank, "FOG");
  45203. }
  45204. if (defines.SPECULARAA) {
  45205. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  45206. }
  45207. if (defines.POINTSIZE) {
  45208. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  45209. }
  45210. if (defines.LOGARITHMICDEPTH) {
  45211. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  45212. }
  45213. if (defines.PARALLAX) {
  45214. fallbacks.addFallback(fallbackRank, "PARALLAX");
  45215. }
  45216. if (defines.PARALLAXOCCLUSION) {
  45217. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  45218. }
  45219. if (defines.ENVIRONMENTBRDF) {
  45220. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  45221. }
  45222. if (defines.TANGENT) {
  45223. fallbacks.addFallback(fallbackRank++, "TANGENT");
  45224. }
  45225. if (defines.BUMP) {
  45226. fallbacks.addFallback(fallbackRank++, "BUMP");
  45227. }
  45228. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45229. if (defines.SPECULARTERM) {
  45230. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45231. }
  45232. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45233. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45234. }
  45235. if (defines.LIGHTMAP) {
  45236. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45237. }
  45238. if (defines.NORMAL) {
  45239. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45240. }
  45241. if (defines.AMBIENT) {
  45242. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45243. }
  45244. if (defines.EMISSIVE) {
  45245. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45246. }
  45247. if (defines.VERTEXCOLOR) {
  45248. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45249. }
  45250. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45251. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45252. }
  45253. if (defines.MORPHTARGETS) {
  45254. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45255. }
  45256. //Attributes
  45257. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45258. if (defines.NORMAL) {
  45259. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45260. }
  45261. if (defines.TANGENT) {
  45262. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45263. }
  45264. if (defines.UV1) {
  45265. attribs.push(BABYLON.VertexBuffer.UVKind);
  45266. }
  45267. if (defines.UV2) {
  45268. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45269. }
  45270. if (defines.VERTEXCOLOR) {
  45271. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45272. }
  45273. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45274. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45275. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45276. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45277. "vFogInfos", "vFogColor", "pointSize",
  45278. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45279. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45280. "mBones",
  45281. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45282. "vLightingIntensity",
  45283. "logarithmicDepthConstant",
  45284. "vSphericalX", "vSphericalY", "vSphericalZ",
  45285. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45286. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45287. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45288. "vTangentSpaceParams"
  45289. ];
  45290. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45291. "bumpSampler", "lightmapSampler", "opacitySampler",
  45292. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45293. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45294. "microSurfaceSampler", "environmentBrdfSampler"];
  45295. var uniformBuffers = ["Material", "Scene"];
  45296. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45297. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45298. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45299. uniformsNames: uniforms,
  45300. uniformBuffersNames: uniformBuffers,
  45301. samplers: samplers,
  45302. defines: defines,
  45303. maxSimultaneousLights: this._maxSimultaneousLights
  45304. });
  45305. var join = defines.toString();
  45306. return engine.createEffect("pbr", {
  45307. attributes: attribs,
  45308. uniformsNames: uniforms,
  45309. uniformBuffersNames: uniformBuffers,
  45310. samplers: samplers,
  45311. defines: join,
  45312. fallbacks: fallbacks,
  45313. onCompiled: onCompiled,
  45314. onError: onError,
  45315. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45316. }, engine);
  45317. };
  45318. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45319. if (useInstances === void 0) { useInstances = null; }
  45320. if (useClipPlane === void 0) { useClipPlane = null; }
  45321. var scene = this.getScene();
  45322. var engine = scene.getEngine();
  45323. // Lights
  45324. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45325. defines._needNormals = true;
  45326. // Textures
  45327. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45328. if (defines._areTexturesDirty) {
  45329. defines._needUVs = false;
  45330. if (scene.texturesEnabled) {
  45331. if (scene.getEngine().getCaps().textureLOD) {
  45332. defines.LODBASEDMICROSFURACE = true;
  45333. }
  45334. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45335. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45336. }
  45337. else {
  45338. defines.ALBEDO = false;
  45339. }
  45340. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45341. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45342. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45343. }
  45344. else {
  45345. defines.AMBIENT = false;
  45346. }
  45347. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45348. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45349. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45350. }
  45351. else {
  45352. defines.OPACITY = false;
  45353. }
  45354. var reflectionTexture = this._getReflectionTexture();
  45355. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45356. defines.REFLECTION = true;
  45357. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45358. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45359. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45360. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45361. defines.INVERTCUBICMAP = true;
  45362. }
  45363. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45364. switch (reflectionTexture.coordinatesMode) {
  45365. case BABYLON.Texture.EXPLICIT_MODE:
  45366. defines.REFLECTIONMAP_EXPLICIT = true;
  45367. break;
  45368. case BABYLON.Texture.PLANAR_MODE:
  45369. defines.REFLECTIONMAP_PLANAR = true;
  45370. break;
  45371. case BABYLON.Texture.PROJECTION_MODE:
  45372. defines.REFLECTIONMAP_PROJECTION = true;
  45373. break;
  45374. case BABYLON.Texture.SKYBOX_MODE:
  45375. defines.REFLECTIONMAP_SKYBOX = true;
  45376. break;
  45377. case BABYLON.Texture.SPHERICAL_MODE:
  45378. defines.REFLECTIONMAP_SPHERICAL = true;
  45379. break;
  45380. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45381. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45382. break;
  45383. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45384. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45385. break;
  45386. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45387. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45388. break;
  45389. case BABYLON.Texture.CUBIC_MODE:
  45390. case BABYLON.Texture.INVCUBIC_MODE:
  45391. default:
  45392. defines.REFLECTIONMAP_CUBIC = true;
  45393. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45394. break;
  45395. }
  45396. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45397. if (reflectionTexture.sphericalPolynomial) {
  45398. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45399. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45400. defines.USESPHERICALINVERTEX = false;
  45401. }
  45402. else {
  45403. defines.USESPHERICALINVERTEX = true;
  45404. }
  45405. }
  45406. }
  45407. }
  45408. else {
  45409. defines.REFLECTION = false;
  45410. defines.REFLECTIONMAP_3D = false;
  45411. defines.REFLECTIONMAP_SPHERICAL = false;
  45412. defines.REFLECTIONMAP_PLANAR = false;
  45413. defines.REFLECTIONMAP_CUBIC = false;
  45414. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45415. defines.REFLECTIONMAP_PROJECTION = false;
  45416. defines.REFLECTIONMAP_SKYBOX = false;
  45417. defines.REFLECTIONMAP_EXPLICIT = false;
  45418. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45419. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45420. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45421. defines.INVERTCUBICMAP = false;
  45422. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45423. defines.USESPHERICALINVERTEX = false;
  45424. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45425. defines.LODINREFLECTIONALPHA = false;
  45426. defines.GAMMAREFLECTION = false;
  45427. }
  45428. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45429. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45430. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45431. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45432. }
  45433. else {
  45434. defines.LIGHTMAP = false;
  45435. }
  45436. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45437. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45438. }
  45439. else {
  45440. defines.EMISSIVE = false;
  45441. }
  45442. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45443. if (this._metallicTexture) {
  45444. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45445. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45446. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45447. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45448. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45449. }
  45450. else if (this._reflectivityTexture) {
  45451. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45452. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45453. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45454. }
  45455. else {
  45456. defines.REFLECTIVITY = false;
  45457. }
  45458. if (this._microSurfaceTexture) {
  45459. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45460. }
  45461. else {
  45462. defines.MICROSURFACEMAP = false;
  45463. }
  45464. }
  45465. else {
  45466. defines.REFLECTIVITY = false;
  45467. defines.MICROSURFACEMAP = false;
  45468. }
  45469. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45470. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45471. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45472. defines.PARALLAX = true;
  45473. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45474. }
  45475. else {
  45476. defines.PARALLAX = false;
  45477. }
  45478. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45479. }
  45480. else {
  45481. defines.BUMP = false;
  45482. }
  45483. var refractionTexture = this._getRefractionTexture();
  45484. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45485. defines.REFRACTION = true;
  45486. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45487. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45488. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45489. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45490. if (this._linkRefractionWithTransparency) {
  45491. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45492. }
  45493. }
  45494. else {
  45495. defines.REFRACTION = false;
  45496. }
  45497. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45498. defines.ENVIRONMENTBRDF = true;
  45499. }
  45500. else {
  45501. defines.ENVIRONMENTBRDF = false;
  45502. }
  45503. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45504. defines.ALPHAFROMALBEDO = true;
  45505. }
  45506. else {
  45507. defines.ALPHAFROMALBEDO = false;
  45508. }
  45509. }
  45510. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45511. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45512. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45513. if (!this.backFaceCulling && this._twoSidedLighting) {
  45514. defines.TWOSIDEDLIGHTING = true;
  45515. }
  45516. else {
  45517. defines.TWOSIDEDLIGHTING = false;
  45518. }
  45519. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45520. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45521. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45522. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45523. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45524. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45525. }
  45526. if (defines._areImageProcessingDirty) {
  45527. this._imageProcessingConfiguration.prepareDefines(defines);
  45528. }
  45529. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45530. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45531. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45532. // Misc.
  45533. if (defines._areMiscDirty) {
  45534. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45535. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45536. }
  45537. // Values that need to be evaluated on every frame
  45538. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45539. // Attribs
  45540. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45541. };
  45542. /**
  45543. * Force shader compilation
  45544. */
  45545. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45546. var _this = this;
  45547. var localOptions = __assign({ clipPlane: false }, options);
  45548. var defines = new PBRMaterialDefines();
  45549. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45550. if (effect.isReady()) {
  45551. if (onCompiled) {
  45552. onCompiled(this);
  45553. }
  45554. }
  45555. else {
  45556. effect.onCompileObservable.add(function () {
  45557. if (onCompiled) {
  45558. onCompiled(_this);
  45559. }
  45560. });
  45561. }
  45562. };
  45563. /**
  45564. * Initializes the uniform buffer layout for the shader.
  45565. */
  45566. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45567. // Order is important !
  45568. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45569. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45570. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45571. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45572. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45573. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45574. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45575. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45576. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45577. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45578. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45579. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45580. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45581. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45582. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45583. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45584. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45585. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45586. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45587. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45588. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45589. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45590. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45591. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45592. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45593. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45594. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45595. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45596. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45597. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45598. this._uniformBuffer.addUniform("pointSize", 1);
  45599. this._uniformBuffer.create();
  45600. };
  45601. /**
  45602. * Unbinds the textures.
  45603. */
  45604. PBRBaseMaterial.prototype.unbind = function () {
  45605. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45606. this._uniformBuffer.setTexture("reflectionSampler", null);
  45607. }
  45608. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45609. this._uniformBuffer.setTexture("refractionSampler", null);
  45610. }
  45611. _super.prototype.unbind.call(this);
  45612. };
  45613. /**
  45614. * Binds the submesh data.
  45615. * @param world - The world matrix.
  45616. * @param mesh - The BJS mesh.
  45617. * @param subMesh - A submesh of the BJS mesh.
  45618. */
  45619. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45620. var scene = this.getScene();
  45621. var defines = subMesh._materialDefines;
  45622. if (!defines) {
  45623. return;
  45624. }
  45625. var effect = subMesh.effect;
  45626. if (!effect) {
  45627. return;
  45628. }
  45629. this._activeEffect = effect;
  45630. // Matrices
  45631. this.bindOnlyWorldMatrix(world);
  45632. // Normal Matrix
  45633. if (defines.OBJECTSPACE_NORMALMAP) {
  45634. world.toNormalMatrix(this._normalMatrix);
  45635. this.bindOnlyNormalMatrix(this._normalMatrix);
  45636. }
  45637. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45638. // Bones
  45639. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45640. var reflectionTexture = null;
  45641. if (mustRebind) {
  45642. this._uniformBuffer.bindToEffect(effect, "Material");
  45643. this.bindViewProjection(effect);
  45644. reflectionTexture = this._getReflectionTexture();
  45645. var refractionTexture = this._getRefractionTexture();
  45646. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45647. // Texture uniforms
  45648. if (scene.texturesEnabled) {
  45649. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45650. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45651. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45652. }
  45653. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45654. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45655. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45656. }
  45657. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45658. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45659. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45660. }
  45661. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45662. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45663. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45664. if (reflectionTexture.boundingBoxSize) {
  45665. var cubeTexture = reflectionTexture;
  45666. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45667. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45668. }
  45669. var polynomials = reflectionTexture.sphericalPolynomial;
  45670. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45671. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45672. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45673. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45674. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45675. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45676. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45677. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45678. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45679. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45680. }
  45681. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45682. }
  45683. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45684. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45685. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45686. }
  45687. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45688. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45689. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45690. }
  45691. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45692. if (this._metallicTexture) {
  45693. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45694. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45695. }
  45696. else if (this._reflectivityTexture) {
  45697. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45698. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45699. }
  45700. if (this._microSurfaceTexture) {
  45701. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45702. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45703. }
  45704. }
  45705. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45706. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45707. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45708. if (scene._mirroredCameraPosition) {
  45709. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45710. }
  45711. else {
  45712. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45713. }
  45714. }
  45715. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45716. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45717. var depth = 1.0;
  45718. if (!refractionTexture.isCube) {
  45719. if (refractionTexture.depth) {
  45720. depth = refractionTexture.depth;
  45721. }
  45722. }
  45723. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45724. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45725. }
  45726. }
  45727. // Point size
  45728. if (this.pointsCloud) {
  45729. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45730. }
  45731. // Colors
  45732. if (defines.METALLICWORKFLOW) {
  45733. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45734. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45735. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45736. }
  45737. else {
  45738. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45739. }
  45740. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45741. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45742. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45743. // Misc
  45744. this._lightingInfos.x = this._directIntensity;
  45745. this._lightingInfos.y = this._emissiveIntensity;
  45746. this._lightingInfos.z = this._environmentIntensity;
  45747. this._lightingInfos.w = this._specularIntensity;
  45748. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45749. }
  45750. // Textures
  45751. if (scene.texturesEnabled) {
  45752. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45753. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45754. }
  45755. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45756. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45757. }
  45758. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45759. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45760. }
  45761. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45762. if (defines.LODBASEDMICROSFURACE) {
  45763. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45764. }
  45765. else {
  45766. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45767. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45768. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45769. }
  45770. }
  45771. if (defines.ENVIRONMENTBRDF) {
  45772. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45773. }
  45774. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45775. if (defines.LODBASEDMICROSFURACE) {
  45776. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45777. }
  45778. else {
  45779. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45780. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45781. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45782. }
  45783. }
  45784. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45785. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45786. }
  45787. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45788. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45789. }
  45790. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45791. if (this._metallicTexture) {
  45792. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45793. }
  45794. else if (this._reflectivityTexture) {
  45795. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45796. }
  45797. if (this._microSurfaceTexture) {
  45798. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45799. }
  45800. }
  45801. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45802. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45803. }
  45804. }
  45805. // Clip plane
  45806. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45807. // Colors
  45808. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45809. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45810. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45811. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45812. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45813. }
  45814. if (mustRebind || !this.isFrozen) {
  45815. // Lights
  45816. if (scene.lightsEnabled && !this._disableLighting) {
  45817. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45818. }
  45819. // View
  45820. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45821. this.bindView(effect);
  45822. }
  45823. // Fog
  45824. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45825. // Morph targets
  45826. if (defines.NUM_MORPH_INFLUENCERS) {
  45827. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45828. }
  45829. // image processing
  45830. this._imageProcessingConfiguration.bind(this._activeEffect);
  45831. // Log. depth
  45832. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45833. }
  45834. this._uniformBuffer.update();
  45835. this._afterBind(mesh, this._activeEffect);
  45836. };
  45837. /**
  45838. * Returns the animatable textures.
  45839. * @returns - Array of animatable textures.
  45840. */
  45841. PBRBaseMaterial.prototype.getAnimatables = function () {
  45842. var results = [];
  45843. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45844. results.push(this._albedoTexture);
  45845. }
  45846. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45847. results.push(this._ambientTexture);
  45848. }
  45849. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45850. results.push(this._opacityTexture);
  45851. }
  45852. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45853. results.push(this._reflectionTexture);
  45854. }
  45855. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45856. results.push(this._emissiveTexture);
  45857. }
  45858. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45859. results.push(this._metallicTexture);
  45860. }
  45861. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45862. results.push(this._reflectivityTexture);
  45863. }
  45864. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45865. results.push(this._bumpTexture);
  45866. }
  45867. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45868. results.push(this._lightmapTexture);
  45869. }
  45870. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45871. results.push(this._refractionTexture);
  45872. }
  45873. return results;
  45874. };
  45875. /**
  45876. * Returns the texture used for reflections.
  45877. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45878. */
  45879. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45880. if (this._reflectionTexture) {
  45881. return this._reflectionTexture;
  45882. }
  45883. return this.getScene().environmentTexture;
  45884. };
  45885. /**
  45886. * Returns the texture used for refraction or null if none is used.
  45887. * @returns - Refection texture if present. If no refraction texture and refraction
  45888. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45889. */
  45890. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45891. if (this._refractionTexture) {
  45892. return this._refractionTexture;
  45893. }
  45894. if (this._linkRefractionWithTransparency) {
  45895. return this.getScene().environmentTexture;
  45896. }
  45897. return null;
  45898. };
  45899. /**
  45900. * Disposes the resources of the material.
  45901. * @param forceDisposeEffect - Forces the disposal of effects.
  45902. * @param forceDisposeTextures - Forces the disposal of all textures.
  45903. */
  45904. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45905. if (forceDisposeTextures) {
  45906. if (this._albedoTexture) {
  45907. this._albedoTexture.dispose();
  45908. }
  45909. if (this._ambientTexture) {
  45910. this._ambientTexture.dispose();
  45911. }
  45912. if (this._opacityTexture) {
  45913. this._opacityTexture.dispose();
  45914. }
  45915. if (this._reflectionTexture) {
  45916. this._reflectionTexture.dispose();
  45917. }
  45918. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45919. this._environmentBRDFTexture.dispose();
  45920. }
  45921. if (this._emissiveTexture) {
  45922. this._emissiveTexture.dispose();
  45923. }
  45924. if (this._metallicTexture) {
  45925. this._metallicTexture.dispose();
  45926. }
  45927. if (this._reflectivityTexture) {
  45928. this._reflectivityTexture.dispose();
  45929. }
  45930. if (this._bumpTexture) {
  45931. this._bumpTexture.dispose();
  45932. }
  45933. if (this._lightmapTexture) {
  45934. this._lightmapTexture.dispose();
  45935. }
  45936. if (this._refractionTexture) {
  45937. this._refractionTexture.dispose();
  45938. }
  45939. }
  45940. this._renderTargets.dispose();
  45941. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45942. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45943. }
  45944. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45945. };
  45946. /**
  45947. * Stores the reflectivity values based on metallic roughness workflow.
  45948. */
  45949. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45950. __decorate([
  45951. BABYLON.serializeAsImageProcessingConfiguration()
  45952. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45953. __decorate([
  45954. BABYLON.serialize()
  45955. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45956. __decorate([
  45957. BABYLON.serialize()
  45958. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45959. return PBRBaseMaterial;
  45960. }(BABYLON.PushMaterial));
  45961. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45962. })(BABYLON || (BABYLON = {}));
  45963. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45964. var BABYLON;
  45965. (function (BABYLON) {
  45966. /**
  45967. * The Physically based simple base material of BJS.
  45968. *
  45969. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45970. * It is used as the base class for both the specGloss and metalRough conventions.
  45971. */
  45972. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45973. __extends(PBRBaseSimpleMaterial, _super);
  45974. /**
  45975. * Instantiates a new PBRMaterial instance.
  45976. *
  45977. * @param name The material name
  45978. * @param scene The scene the material will be use in.
  45979. */
  45980. function PBRBaseSimpleMaterial(name, scene) {
  45981. var _this = _super.call(this, name, scene) || this;
  45982. /**
  45983. * Number of Simultaneous lights allowed on the material.
  45984. */
  45985. _this.maxSimultaneousLights = 4;
  45986. /**
  45987. * If sets to true, disables all the lights affecting the material.
  45988. */
  45989. _this.disableLighting = false;
  45990. /**
  45991. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45992. */
  45993. _this.invertNormalMapX = false;
  45994. /**
  45995. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45996. */
  45997. _this.invertNormalMapY = false;
  45998. /**
  45999. * Emissivie color used to self-illuminate the model.
  46000. */
  46001. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46002. /**
  46003. * Occlusion Channel Strenght.
  46004. */
  46005. _this.occlusionStrength = 1.0;
  46006. _this.useLightmapAsShadowmap = false;
  46007. _this._useAlphaFromAlbedoTexture = true;
  46008. _this._useAmbientInGrayScale = true;
  46009. return _this;
  46010. }
  46011. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  46012. /**
  46013. * Gets the current double sided mode.
  46014. */
  46015. get: function () {
  46016. return this._twoSidedLighting;
  46017. },
  46018. /**
  46019. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46020. */
  46021. set: function (value) {
  46022. if (this._twoSidedLighting === value) {
  46023. return;
  46024. }
  46025. this._twoSidedLighting = value;
  46026. this.backFaceCulling = !value;
  46027. this._markAllSubMeshesAsTexturesDirty();
  46028. },
  46029. enumerable: true,
  46030. configurable: true
  46031. });
  46032. /**
  46033. * Return the active textures of the material.
  46034. */
  46035. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  46036. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46037. if (this.environmentTexture) {
  46038. activeTextures.push(this.environmentTexture);
  46039. }
  46040. if (this.normalTexture) {
  46041. activeTextures.push(this.normalTexture);
  46042. }
  46043. if (this.emissiveTexture) {
  46044. activeTextures.push(this.emissiveTexture);
  46045. }
  46046. if (this.occlusionTexture) {
  46047. activeTextures.push(this.occlusionTexture);
  46048. }
  46049. if (this.lightmapTexture) {
  46050. activeTextures.push(this.lightmapTexture);
  46051. }
  46052. return activeTextures;
  46053. };
  46054. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  46055. if (_super.prototype.hasTexture.call(this, texture)) {
  46056. return true;
  46057. }
  46058. if (this.lightmapTexture === texture) {
  46059. return true;
  46060. }
  46061. return false;
  46062. };
  46063. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  46064. return "PBRBaseSimpleMaterial";
  46065. };
  46066. __decorate([
  46067. BABYLON.serialize(),
  46068. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46069. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  46070. __decorate([
  46071. BABYLON.serialize(),
  46072. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46073. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  46074. __decorate([
  46075. BABYLON.serializeAsTexture(),
  46076. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  46077. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  46078. __decorate([
  46079. BABYLON.serialize(),
  46080. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46081. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  46082. __decorate([
  46083. BABYLON.serialize(),
  46084. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46085. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  46086. __decorate([
  46087. BABYLON.serializeAsTexture(),
  46088. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  46089. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  46090. __decorate([
  46091. BABYLON.serializeAsColor3("emissive"),
  46092. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46093. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  46094. __decorate([
  46095. BABYLON.serializeAsTexture(),
  46096. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46097. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  46098. __decorate([
  46099. BABYLON.serialize(),
  46100. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  46101. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  46102. __decorate([
  46103. BABYLON.serializeAsTexture(),
  46104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  46105. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  46106. __decorate([
  46107. BABYLON.serialize(),
  46108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  46109. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  46110. __decorate([
  46111. BABYLON.serialize()
  46112. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  46113. __decorate([
  46114. BABYLON.serializeAsTexture(),
  46115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46116. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  46117. __decorate([
  46118. BABYLON.serialize(),
  46119. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46120. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46121. return PBRBaseSimpleMaterial;
  46122. }(BABYLON.PBRBaseMaterial));
  46123. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  46124. })(BABYLON || (BABYLON = {}));
  46125. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  46126. var BABYLON;
  46127. (function (BABYLON) {
  46128. /**
  46129. * The Physically based material of BJS.
  46130. *
  46131. * This offers the main features of a standard PBR material.
  46132. * For more information, please refer to the documentation :
  46133. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  46134. */
  46135. var PBRMaterial = /** @class */ (function (_super) {
  46136. __extends(PBRMaterial, _super);
  46137. /**
  46138. * Instantiates a new PBRMaterial instance.
  46139. *
  46140. * @param name The material name
  46141. * @param scene The scene the material will be use in.
  46142. */
  46143. function PBRMaterial(name, scene) {
  46144. var _this = _super.call(this, name, scene) || this;
  46145. /**
  46146. * Intensity of the direct lights e.g. the four lights available in your scene.
  46147. * This impacts both the direct diffuse and specular highlights.
  46148. */
  46149. _this.directIntensity = 1.0;
  46150. /**
  46151. * Intensity of the emissive part of the material.
  46152. * This helps controlling the emissive effect without modifying the emissive color.
  46153. */
  46154. _this.emissiveIntensity = 1.0;
  46155. /**
  46156. * Intensity of the environment e.g. how much the environment will light the object
  46157. * either through harmonics for rough material or through the refelction for shiny ones.
  46158. */
  46159. _this.environmentIntensity = 1.0;
  46160. /**
  46161. * This is a special control allowing the reduction of the specular highlights coming from the
  46162. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  46163. */
  46164. _this.specularIntensity = 1.0;
  46165. /**
  46166. * Debug Control allowing disabling the bump map on this material.
  46167. */
  46168. _this.disableBumpMap = false;
  46169. /**
  46170. * AKA Occlusion Texture Intensity in other nomenclature.
  46171. */
  46172. _this.ambientTextureStrength = 1.0;
  46173. /**
  46174. * The color of a material in ambient lighting.
  46175. */
  46176. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  46177. /**
  46178. * AKA Diffuse Color in other nomenclature.
  46179. */
  46180. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  46181. /**
  46182. * AKA Specular Color in other nomenclature.
  46183. */
  46184. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  46185. /**
  46186. * The color reflected from the material.
  46187. */
  46188. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  46189. /**
  46190. * The color emitted from the material.
  46191. */
  46192. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46193. /**
  46194. * AKA Glossiness in other nomenclature.
  46195. */
  46196. _this.microSurface = 1.0;
  46197. /**
  46198. * source material index of refraction (IOR)' / 'destination material IOR.
  46199. */
  46200. _this.indexOfRefraction = 0.66;
  46201. /**
  46202. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46203. */
  46204. _this.invertRefractionY = false;
  46205. /**
  46206. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46207. * Materials half opaque for instance using refraction could benefit from this control.
  46208. */
  46209. _this.linkRefractionWithTransparency = false;
  46210. _this.useLightmapAsShadowmap = false;
  46211. /**
  46212. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46213. */
  46214. _this.useAlphaFromAlbedoTexture = false;
  46215. /**
  46216. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46217. */
  46218. _this.forceAlphaTest = false;
  46219. /**
  46220. * Defines the alpha limits in alpha test mode.
  46221. */
  46222. _this.alphaCutOff = 0.4;
  46223. /**
  46224. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  46225. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46226. */
  46227. _this.useSpecularOverAlpha = true;
  46228. /**
  46229. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46230. */
  46231. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46232. /**
  46233. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46234. */
  46235. _this.useRoughnessFromMetallicTextureAlpha = true;
  46236. /**
  46237. * Specifies if the metallic texture contains the roughness information in its green channel.
  46238. */
  46239. _this.useRoughnessFromMetallicTextureGreen = false;
  46240. /**
  46241. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46242. */
  46243. _this.useMetallnessFromMetallicTextureBlue = false;
  46244. /**
  46245. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46246. */
  46247. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46248. /**
  46249. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46250. */
  46251. _this.useAmbientInGrayScale = false;
  46252. /**
  46253. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46254. * The material will try to infer what glossiness each pixel should be.
  46255. */
  46256. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46257. /**
  46258. * BJS is using an harcoded light falloff based on a manually sets up range.
  46259. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46260. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46261. */
  46262. _this.usePhysicalLightFalloff = true;
  46263. /**
  46264. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46265. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46266. */
  46267. _this.useRadianceOverAlpha = true;
  46268. /**
  46269. * Allows using an object space normal map (instead of tangent space).
  46270. */
  46271. _this.useObjectSpaceNormalMap = false;
  46272. /**
  46273. * Allows using the bump map in parallax mode.
  46274. */
  46275. _this.useParallax = false;
  46276. /**
  46277. * Allows using the bump map in parallax occlusion mode.
  46278. */
  46279. _this.useParallaxOcclusion = false;
  46280. /**
  46281. * Controls the scale bias of the parallax mode.
  46282. */
  46283. _this.parallaxScaleBias = 0.05;
  46284. /**
  46285. * If sets to true, disables all the lights affecting the material.
  46286. */
  46287. _this.disableLighting = false;
  46288. /**
  46289. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46290. */
  46291. _this.forceIrradianceInFragment = false;
  46292. /**
  46293. * Number of Simultaneous lights allowed on the material.
  46294. */
  46295. _this.maxSimultaneousLights = 4;
  46296. /**
  46297. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46298. */
  46299. _this.invertNormalMapX = false;
  46300. /**
  46301. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46302. */
  46303. _this.invertNormalMapY = false;
  46304. /**
  46305. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46306. */
  46307. _this.twoSidedLighting = false;
  46308. /**
  46309. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46310. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46311. */
  46312. _this.useAlphaFresnel = false;
  46313. /**
  46314. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46315. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46316. */
  46317. _this.useLinearAlphaFresnel = false;
  46318. /**
  46319. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46320. * And/Or occlude the blended part.
  46321. */
  46322. _this.environmentBRDFTexture = null;
  46323. /**
  46324. * Force normal to face away from face.
  46325. */
  46326. _this.forceNormalForward = false;
  46327. /**
  46328. * Enables specular anti aliasing in the PBR shader.
  46329. * It will both interacts on the Geometry for analytical and IBL lighting.
  46330. * It also prefilter the roughness map based on the bump values.
  46331. */
  46332. _this.enableSpecularAntiAliasing = false;
  46333. /**
  46334. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46335. * makes the reflect vector face the model (under horizon).
  46336. */
  46337. _this.useHorizonOcclusion = true;
  46338. /**
  46339. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46340. * too much the area relying on ambient texture to define their ambient occlusion.
  46341. */
  46342. _this.useRadianceOcclusion = true;
  46343. /**
  46344. * If set to true, no lighting calculations will be applied.
  46345. */
  46346. _this.unlit = false;
  46347. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46348. return _this;
  46349. }
  46350. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  46351. /**
  46352. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  46353. */
  46354. get: function () {
  46355. return this._PBRMATERIAL_OPAQUE;
  46356. },
  46357. enumerable: true,
  46358. configurable: true
  46359. });
  46360. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  46361. /**
  46362. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46363. */
  46364. get: function () {
  46365. return this._PBRMATERIAL_ALPHATEST;
  46366. },
  46367. enumerable: true,
  46368. configurable: true
  46369. });
  46370. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  46371. /**
  46372. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46373. */
  46374. get: function () {
  46375. return this._PBRMATERIAL_ALPHABLEND;
  46376. },
  46377. enumerable: true,
  46378. configurable: true
  46379. });
  46380. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  46381. /**
  46382. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46383. * They are also discarded below the alpha cutoff threshold to improve performances.
  46384. */
  46385. get: function () {
  46386. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  46387. },
  46388. enumerable: true,
  46389. configurable: true
  46390. });
  46391. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46392. /**
  46393. * Gets the image processing configuration used either in this material.
  46394. */
  46395. get: function () {
  46396. return this._imageProcessingConfiguration;
  46397. },
  46398. /**
  46399. * Sets the Default image processing configuration used either in the this material.
  46400. *
  46401. * If sets to null, the scene one is in use.
  46402. */
  46403. set: function (value) {
  46404. this._attachImageProcessingConfiguration(value);
  46405. // Ensure the effect will be rebuilt.
  46406. this._markAllSubMeshesAsTexturesDirty();
  46407. },
  46408. enumerable: true,
  46409. configurable: true
  46410. });
  46411. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46412. /**
  46413. * Gets wether the color curves effect is enabled.
  46414. */
  46415. get: function () {
  46416. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46417. },
  46418. /**
  46419. * Sets wether the color curves effect is enabled.
  46420. */
  46421. set: function (value) {
  46422. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46423. },
  46424. enumerable: true,
  46425. configurable: true
  46426. });
  46427. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46428. /**
  46429. * Gets wether the color grading effect is enabled.
  46430. */
  46431. get: function () {
  46432. return this.imageProcessingConfiguration.colorGradingEnabled;
  46433. },
  46434. /**
  46435. * Gets wether the color grading effect is enabled.
  46436. */
  46437. set: function (value) {
  46438. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46439. },
  46440. enumerable: true,
  46441. configurable: true
  46442. });
  46443. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46444. /**
  46445. * Gets wether tonemapping is enabled or not.
  46446. */
  46447. get: function () {
  46448. return this._imageProcessingConfiguration.toneMappingEnabled;
  46449. },
  46450. /**
  46451. * Sets wether tonemapping is enabled or not
  46452. */
  46453. set: function (value) {
  46454. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46455. },
  46456. enumerable: true,
  46457. configurable: true
  46458. });
  46459. ;
  46460. ;
  46461. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46462. /**
  46463. * The camera exposure used on this material.
  46464. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46465. * This corresponds to a photographic exposure.
  46466. */
  46467. get: function () {
  46468. return this._imageProcessingConfiguration.exposure;
  46469. },
  46470. /**
  46471. * The camera exposure used on this material.
  46472. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46473. * This corresponds to a photographic exposure.
  46474. */
  46475. set: function (value) {
  46476. this._imageProcessingConfiguration.exposure = value;
  46477. },
  46478. enumerable: true,
  46479. configurable: true
  46480. });
  46481. ;
  46482. ;
  46483. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46484. /**
  46485. * Gets The camera contrast used on this material.
  46486. */
  46487. get: function () {
  46488. return this._imageProcessingConfiguration.contrast;
  46489. },
  46490. /**
  46491. * Sets The camera contrast used on this material.
  46492. */
  46493. set: function (value) {
  46494. this._imageProcessingConfiguration.contrast = value;
  46495. },
  46496. enumerable: true,
  46497. configurable: true
  46498. });
  46499. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46500. /**
  46501. * Gets the Color Grading 2D Lookup Texture.
  46502. */
  46503. get: function () {
  46504. return this._imageProcessingConfiguration.colorGradingTexture;
  46505. },
  46506. /**
  46507. * Sets the Color Grading 2D Lookup Texture.
  46508. */
  46509. set: function (value) {
  46510. this._imageProcessingConfiguration.colorGradingTexture = value;
  46511. },
  46512. enumerable: true,
  46513. configurable: true
  46514. });
  46515. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46516. /**
  46517. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46518. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46519. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  46520. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46521. */
  46522. get: function () {
  46523. return this._imageProcessingConfiguration.colorCurves;
  46524. },
  46525. /**
  46526. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46527. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46528. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  46529. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46530. */
  46531. set: function (value) {
  46532. this._imageProcessingConfiguration.colorCurves = value;
  46533. },
  46534. enumerable: true,
  46535. configurable: true
  46536. });
  46537. /**
  46538. * Returns the name of this material class.
  46539. */
  46540. PBRMaterial.prototype.getClassName = function () {
  46541. return "PBRMaterial";
  46542. };
  46543. /**
  46544. * Returns an array of the actively used textures.
  46545. * @returns - Array of BaseTextures
  46546. */
  46547. PBRMaterial.prototype.getActiveTextures = function () {
  46548. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46549. if (this._albedoTexture) {
  46550. activeTextures.push(this._albedoTexture);
  46551. }
  46552. if (this._ambientTexture) {
  46553. activeTextures.push(this._ambientTexture);
  46554. }
  46555. if (this._opacityTexture) {
  46556. activeTextures.push(this._opacityTexture);
  46557. }
  46558. if (this._reflectionTexture) {
  46559. activeTextures.push(this._reflectionTexture);
  46560. }
  46561. if (this._emissiveTexture) {
  46562. activeTextures.push(this._emissiveTexture);
  46563. }
  46564. if (this._reflectivityTexture) {
  46565. activeTextures.push(this._reflectivityTexture);
  46566. }
  46567. if (this._metallicTexture) {
  46568. activeTextures.push(this._metallicTexture);
  46569. }
  46570. if (this._microSurfaceTexture) {
  46571. activeTextures.push(this._microSurfaceTexture);
  46572. }
  46573. if (this._bumpTexture) {
  46574. activeTextures.push(this._bumpTexture);
  46575. }
  46576. if (this._lightmapTexture) {
  46577. activeTextures.push(this._lightmapTexture);
  46578. }
  46579. if (this._refractionTexture) {
  46580. activeTextures.push(this._refractionTexture);
  46581. }
  46582. return activeTextures;
  46583. };
  46584. /**
  46585. * Checks to see if a texture is used in the material.
  46586. * @param texture - Base texture to use.
  46587. * @returns - Boolean specifying if a texture is used in the material.
  46588. */
  46589. PBRMaterial.prototype.hasTexture = function (texture) {
  46590. if (_super.prototype.hasTexture.call(this, texture)) {
  46591. return true;
  46592. }
  46593. if (this._albedoTexture === texture) {
  46594. return true;
  46595. }
  46596. if (this._ambientTexture === texture) {
  46597. return true;
  46598. }
  46599. if (this._opacityTexture === texture) {
  46600. return true;
  46601. }
  46602. if (this._reflectionTexture === texture) {
  46603. return true;
  46604. }
  46605. if (this._reflectivityTexture === texture) {
  46606. return true;
  46607. }
  46608. if (this._metallicTexture === texture) {
  46609. return true;
  46610. }
  46611. if (this._microSurfaceTexture === texture) {
  46612. return true;
  46613. }
  46614. if (this._bumpTexture === texture) {
  46615. return true;
  46616. }
  46617. if (this._lightmapTexture === texture) {
  46618. return true;
  46619. }
  46620. if (this._refractionTexture === texture) {
  46621. return true;
  46622. }
  46623. return false;
  46624. };
  46625. /**
  46626. * Makes a duplicate of the current material.
  46627. * @param name - name to use for the new material.
  46628. */
  46629. PBRMaterial.prototype.clone = function (name) {
  46630. var _this = this;
  46631. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46632. clone.id = name;
  46633. clone.name = name;
  46634. return clone;
  46635. };
  46636. /**
  46637. * Serializes this PBR Material.
  46638. * @returns - An object with the serialized material.
  46639. */
  46640. PBRMaterial.prototype.serialize = function () {
  46641. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46642. serializationObject.customType = "BABYLON.PBRMaterial";
  46643. return serializationObject;
  46644. };
  46645. // Statics
  46646. /**
  46647. * Parses a PBR Material from a serialized object.
  46648. * @param source - Serialized object.
  46649. * @param scene - BJS scene instance.
  46650. * @param rootUrl - url for the scene object
  46651. * @returns - PBRMaterial
  46652. */
  46653. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46654. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46655. };
  46656. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46657. /**
  46658. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46659. */
  46660. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46661. /**
  46662. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46663. */
  46664. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46665. /**
  46666. * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46667. * They are also discarded below the alpha cutoff threshold to improve performances.
  46668. */
  46669. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46670. __decorate([
  46671. BABYLON.serialize(),
  46672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46673. ], PBRMaterial.prototype, "directIntensity", void 0);
  46674. __decorate([
  46675. BABYLON.serialize(),
  46676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46677. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46678. __decorate([
  46679. BABYLON.serialize(),
  46680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46681. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46682. __decorate([
  46683. BABYLON.serialize(),
  46684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46685. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46686. __decorate([
  46687. BABYLON.serialize(),
  46688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46689. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46690. __decorate([
  46691. BABYLON.serializeAsTexture(),
  46692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46693. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46694. __decorate([
  46695. BABYLON.serializeAsTexture(),
  46696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46697. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46698. __decorate([
  46699. BABYLON.serialize(),
  46700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46701. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46702. __decorate([
  46703. BABYLON.serializeAsTexture(),
  46704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46705. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46706. __decorate([
  46707. BABYLON.serializeAsTexture(),
  46708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46709. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46710. __decorate([
  46711. BABYLON.serializeAsTexture(),
  46712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46713. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46714. __decorate([
  46715. BABYLON.serializeAsTexture(),
  46716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46717. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46718. __decorate([
  46719. BABYLON.serializeAsTexture(),
  46720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46721. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46722. __decorate([
  46723. BABYLON.serialize(),
  46724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46725. ], PBRMaterial.prototype, "metallic", void 0);
  46726. __decorate([
  46727. BABYLON.serialize(),
  46728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46729. ], PBRMaterial.prototype, "roughness", void 0);
  46730. __decorate([
  46731. BABYLON.serializeAsTexture(),
  46732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46733. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46734. __decorate([
  46735. BABYLON.serializeAsTexture(),
  46736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46737. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46738. __decorate([
  46739. BABYLON.serializeAsTexture(),
  46740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46741. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46742. __decorate([
  46743. BABYLON.serializeAsTexture(),
  46744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46745. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46746. __decorate([
  46747. BABYLON.serializeAsColor3("ambient"),
  46748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46749. ], PBRMaterial.prototype, "ambientColor", void 0);
  46750. __decorate([
  46751. BABYLON.serializeAsColor3("albedo"),
  46752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46753. ], PBRMaterial.prototype, "albedoColor", void 0);
  46754. __decorate([
  46755. BABYLON.serializeAsColor3("reflectivity"),
  46756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46757. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46758. __decorate([
  46759. BABYLON.serializeAsColor3("reflection"),
  46760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46761. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46762. __decorate([
  46763. BABYLON.serializeAsColor3("emissive"),
  46764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46765. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46766. __decorate([
  46767. BABYLON.serialize(),
  46768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46769. ], PBRMaterial.prototype, "microSurface", void 0);
  46770. __decorate([
  46771. BABYLON.serialize(),
  46772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46773. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46774. __decorate([
  46775. BABYLON.serialize(),
  46776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46777. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46778. __decorate([
  46779. BABYLON.serialize(),
  46780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46781. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46782. __decorate([
  46783. BABYLON.serialize(),
  46784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46785. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46786. __decorate([
  46787. BABYLON.serialize(),
  46788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46789. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46790. __decorate([
  46791. BABYLON.serialize(),
  46792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46793. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46794. __decorate([
  46795. BABYLON.serialize(),
  46796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46797. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46798. __decorate([
  46799. BABYLON.serialize(),
  46800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46801. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46802. __decorate([
  46803. BABYLON.serialize(),
  46804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46805. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46806. __decorate([
  46807. BABYLON.serialize(),
  46808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46809. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46810. __decorate([
  46811. BABYLON.serialize(),
  46812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46813. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46814. __decorate([
  46815. BABYLON.serialize(),
  46816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46817. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46818. __decorate([
  46819. BABYLON.serialize(),
  46820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46821. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46822. __decorate([
  46823. BABYLON.serialize(),
  46824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46825. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46826. __decorate([
  46827. BABYLON.serialize(),
  46828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46829. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46830. __decorate([
  46831. BABYLON.serialize(),
  46832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46833. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46834. __decorate([
  46835. BABYLON.serialize(),
  46836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46837. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46838. __decorate([
  46839. BABYLON.serialize(),
  46840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46841. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46842. __decorate([
  46843. BABYLON.serialize(),
  46844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46845. ], PBRMaterial.prototype, "useParallax", void 0);
  46846. __decorate([
  46847. BABYLON.serialize(),
  46848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46849. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46850. __decorate([
  46851. BABYLON.serialize(),
  46852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46853. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46854. __decorate([
  46855. BABYLON.serialize(),
  46856. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46857. ], PBRMaterial.prototype, "disableLighting", void 0);
  46858. __decorate([
  46859. BABYLON.serialize(),
  46860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46861. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46862. __decorate([
  46863. BABYLON.serialize(),
  46864. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46865. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46866. __decorate([
  46867. BABYLON.serialize(),
  46868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46869. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46870. __decorate([
  46871. BABYLON.serialize(),
  46872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46873. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46874. __decorate([
  46875. BABYLON.serialize(),
  46876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46877. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46878. __decorate([
  46879. BABYLON.serialize(),
  46880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46881. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46882. __decorate([
  46883. BABYLON.serialize(),
  46884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46885. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46886. __decorate([
  46887. BABYLON.serializeAsTexture(),
  46888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46889. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46890. __decorate([
  46891. BABYLON.serialize(),
  46892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46893. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46894. __decorate([
  46895. BABYLON.serialize(),
  46896. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46897. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46898. __decorate([
  46899. BABYLON.serialize(),
  46900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46901. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46902. __decorate([
  46903. BABYLON.serialize(),
  46904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46905. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46906. __decorate([
  46907. BABYLON.serialize(),
  46908. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  46909. ], PBRMaterial.prototype, "unlit", void 0);
  46910. return PBRMaterial;
  46911. }(BABYLON.PBRBaseMaterial));
  46912. BABYLON.PBRMaterial = PBRMaterial;
  46913. })(BABYLON || (BABYLON = {}));
  46914. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46915. var BABYLON;
  46916. (function (BABYLON) {
  46917. /**
  46918. * The PBR material of BJS following the metal roughness convention.
  46919. *
  46920. * This fits to the PBR convention in the GLTF definition:
  46921. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46922. */
  46923. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46924. __extends(PBRMetallicRoughnessMaterial, _super);
  46925. /**
  46926. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46927. *
  46928. * @param name The material name
  46929. * @param scene The scene the material will be use in.
  46930. */
  46931. function PBRMetallicRoughnessMaterial(name, scene) {
  46932. var _this = _super.call(this, name, scene) || this;
  46933. _this._useRoughnessFromMetallicTextureAlpha = false;
  46934. _this._useRoughnessFromMetallicTextureGreen = true;
  46935. _this._useMetallnessFromMetallicTextureBlue = true;
  46936. _this.metallic = 1.0;
  46937. _this.roughness = 1.0;
  46938. return _this;
  46939. }
  46940. /**
  46941. * Return the currrent class name of the material.
  46942. */
  46943. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46944. return "PBRMetallicRoughnessMaterial";
  46945. };
  46946. /**
  46947. * Return the active textures of the material.
  46948. */
  46949. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46950. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46951. if (this.baseTexture) {
  46952. activeTextures.push(this.baseTexture);
  46953. }
  46954. if (this.metallicRoughnessTexture) {
  46955. activeTextures.push(this.metallicRoughnessTexture);
  46956. }
  46957. return activeTextures;
  46958. };
  46959. /**
  46960. * Checks to see if a texture is used in the material.
  46961. * @param texture - Base texture to use.
  46962. * @returns - Boolean specifying if a texture is used in the material.
  46963. */
  46964. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46965. if (_super.prototype.hasTexture.call(this, texture)) {
  46966. return true;
  46967. }
  46968. if (this.baseTexture === texture) {
  46969. return true;
  46970. }
  46971. if (this.metallicRoughnessTexture === texture) {
  46972. return true;
  46973. }
  46974. return false;
  46975. };
  46976. /**
  46977. * Makes a duplicate of the current material.
  46978. * @param name - name to use for the new material.
  46979. */
  46980. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46981. var _this = this;
  46982. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46983. clone.id = name;
  46984. clone.name = name;
  46985. return clone;
  46986. };
  46987. /**
  46988. * Serialize the material to a parsable JSON object.
  46989. */
  46990. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46991. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46992. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46993. return serializationObject;
  46994. };
  46995. /**
  46996. * Parses a JSON object correponding to the serialize function.
  46997. */
  46998. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46999. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  47000. };
  47001. __decorate([
  47002. BABYLON.serializeAsColor3(),
  47003. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47004. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  47005. __decorate([
  47006. BABYLON.serializeAsTexture(),
  47007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47008. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  47009. __decorate([
  47010. BABYLON.serialize(),
  47011. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47012. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  47013. __decorate([
  47014. BABYLON.serialize(),
  47015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47016. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  47017. __decorate([
  47018. BABYLON.serializeAsTexture(),
  47019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  47020. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  47021. return PBRMetallicRoughnessMaterial;
  47022. }(BABYLON.PBRBaseSimpleMaterial));
  47023. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  47024. })(BABYLON || (BABYLON = {}));
  47025. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  47026. var BABYLON;
  47027. (function (BABYLON) {
  47028. /**
  47029. * The PBR material of BJS following the specular glossiness convention.
  47030. *
  47031. * This fits to the PBR convention in the GLTF definition:
  47032. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  47033. */
  47034. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  47035. __extends(PBRSpecularGlossinessMaterial, _super);
  47036. /**
  47037. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  47038. *
  47039. * @param name The material name
  47040. * @param scene The scene the material will be use in.
  47041. */
  47042. function PBRSpecularGlossinessMaterial(name, scene) {
  47043. var _this = _super.call(this, name, scene) || this;
  47044. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  47045. return _this;
  47046. }
  47047. /**
  47048. * Return the currrent class name of the material.
  47049. */
  47050. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  47051. return "PBRSpecularGlossinessMaterial";
  47052. };
  47053. /**
  47054. * Return the active textures of the material.
  47055. */
  47056. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  47057. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47058. if (this.diffuseTexture) {
  47059. activeTextures.push(this.diffuseTexture);
  47060. }
  47061. if (this.specularGlossinessTexture) {
  47062. activeTextures.push(this.specularGlossinessTexture);
  47063. }
  47064. return activeTextures;
  47065. };
  47066. /**
  47067. * Checks to see if a texture is used in the material.
  47068. * @param texture - Base texture to use.
  47069. * @returns - Boolean specifying if a texture is used in the material.
  47070. */
  47071. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  47072. if (_super.prototype.hasTexture.call(this, texture)) {
  47073. return true;
  47074. }
  47075. if (this.diffuseTexture === texture) {
  47076. return true;
  47077. }
  47078. if (this.specularGlossinessTexture === texture) {
  47079. return true;
  47080. }
  47081. return false;
  47082. };
  47083. /**
  47084. * Makes a duplicate of the current material.
  47085. * @param name - name to use for the new material.
  47086. */
  47087. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  47088. var _this = this;
  47089. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  47090. clone.id = name;
  47091. clone.name = name;
  47092. return clone;
  47093. };
  47094. /**
  47095. * Serialize the material to a parsable JSON object.
  47096. */
  47097. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  47098. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47099. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  47100. return serializationObject;
  47101. };
  47102. /**
  47103. * Parses a JSON object correponding to the serialize function.
  47104. */
  47105. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  47106. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  47107. };
  47108. __decorate([
  47109. BABYLON.serializeAsColor3("diffuse"),
  47110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47111. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  47112. __decorate([
  47113. BABYLON.serializeAsTexture(),
  47114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47115. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  47116. __decorate([
  47117. BABYLON.serializeAsColor3("specular"),
  47118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  47119. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  47120. __decorate([
  47121. BABYLON.serialize(),
  47122. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  47123. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  47124. __decorate([
  47125. BABYLON.serializeAsTexture(),
  47126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  47127. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  47128. return PBRSpecularGlossinessMaterial;
  47129. }(BABYLON.PBRBaseSimpleMaterial));
  47130. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  47131. })(BABYLON || (BABYLON = {}));
  47132. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  47133. var BABYLON;
  47134. (function (BABYLON) {
  47135. BABYLON.CameraInputTypes = {};
  47136. var CameraInputsManager = /** @class */ (function () {
  47137. function CameraInputsManager(camera) {
  47138. this.attached = {};
  47139. this.camera = camera;
  47140. this.checkInputs = function () { };
  47141. }
  47142. /**
  47143. * Add an input method to a camera.
  47144. * builtin inputs example: camera.inputs.addGamepad();
  47145. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  47146. * @param input camera input method
  47147. */
  47148. CameraInputsManager.prototype.add = function (input) {
  47149. var type = input.getSimpleName();
  47150. if (this.attached[type]) {
  47151. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  47152. return;
  47153. }
  47154. this.attached[type] = input;
  47155. input.camera = this.camera;
  47156. //for checkInputs, we are dynamically creating a function
  47157. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  47158. if (input.checkInputs) {
  47159. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47160. }
  47161. if (this.attachedElement) {
  47162. input.attachControl(this.attachedElement);
  47163. }
  47164. };
  47165. /**
  47166. * Remove a specific input method from a camera
  47167. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  47168. * @param inputToRemove camera input method
  47169. */
  47170. CameraInputsManager.prototype.remove = function (inputToRemove) {
  47171. for (var cam in this.attached) {
  47172. var input = this.attached[cam];
  47173. if (input === inputToRemove) {
  47174. input.detachControl(this.attachedElement);
  47175. input.camera = null;
  47176. delete this.attached[cam];
  47177. this.rebuildInputCheck();
  47178. }
  47179. }
  47180. };
  47181. CameraInputsManager.prototype.removeByType = function (inputType) {
  47182. for (var cam in this.attached) {
  47183. var input = this.attached[cam];
  47184. if (input.getClassName() === inputType) {
  47185. input.detachControl(this.attachedElement);
  47186. input.camera = null;
  47187. delete this.attached[cam];
  47188. this.rebuildInputCheck();
  47189. }
  47190. }
  47191. };
  47192. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  47193. var current = this.checkInputs;
  47194. return function () {
  47195. current();
  47196. fn();
  47197. };
  47198. };
  47199. CameraInputsManager.prototype.attachInput = function (input) {
  47200. if (this.attachedElement) {
  47201. input.attachControl(this.attachedElement, this.noPreventDefault);
  47202. }
  47203. };
  47204. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47205. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47206. if (this.attachedElement) {
  47207. return;
  47208. }
  47209. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47210. this.attachedElement = element;
  47211. this.noPreventDefault = noPreventDefault;
  47212. for (var cam in this.attached) {
  47213. this.attached[cam].attachControl(element, noPreventDefault);
  47214. }
  47215. };
  47216. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47217. if (disconnect === void 0) { disconnect = false; }
  47218. if (this.attachedElement !== element) {
  47219. return;
  47220. }
  47221. for (var cam in this.attached) {
  47222. this.attached[cam].detachControl(element);
  47223. if (disconnect) {
  47224. this.attached[cam].camera = null;
  47225. }
  47226. }
  47227. this.attachedElement = null;
  47228. };
  47229. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47230. this.checkInputs = function () { };
  47231. for (var cam in this.attached) {
  47232. var input = this.attached[cam];
  47233. if (input.checkInputs) {
  47234. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47235. }
  47236. }
  47237. };
  47238. /**
  47239. * Remove all attached input methods from a camera
  47240. */
  47241. CameraInputsManager.prototype.clear = function () {
  47242. if (this.attachedElement) {
  47243. this.detachElement(this.attachedElement, true);
  47244. }
  47245. this.attached = {};
  47246. this.attachedElement = null;
  47247. this.checkInputs = function () { };
  47248. };
  47249. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47250. var inputs = {};
  47251. for (var cam in this.attached) {
  47252. var input = this.attached[cam];
  47253. var res = BABYLON.SerializationHelper.Serialize(input);
  47254. inputs[input.getClassName()] = res;
  47255. }
  47256. serializedCamera.inputsmgr = inputs;
  47257. };
  47258. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47259. var parsedInputs = parsedCamera.inputsmgr;
  47260. if (parsedInputs) {
  47261. this.clear();
  47262. for (var n in parsedInputs) {
  47263. var construct = BABYLON.CameraInputTypes[n];
  47264. if (construct) {
  47265. var parsedinput = parsedInputs[n];
  47266. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47267. this.add(input);
  47268. }
  47269. }
  47270. }
  47271. else {
  47272. //2016-03-08 this part is for managing backward compatibility
  47273. for (var n in this.attached) {
  47274. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47275. if (construct) {
  47276. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47277. this.remove(this.attached[n]);
  47278. this.add(input);
  47279. }
  47280. }
  47281. }
  47282. };
  47283. return CameraInputsManager;
  47284. }());
  47285. BABYLON.CameraInputsManager = CameraInputsManager;
  47286. })(BABYLON || (BABYLON = {}));
  47287. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47288. var BABYLON;
  47289. (function (BABYLON) {
  47290. var TargetCamera = /** @class */ (function (_super) {
  47291. __extends(TargetCamera, _super);
  47292. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47293. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47294. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47295. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47296. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47297. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47298. _this.speed = 2.0;
  47299. _this.noRotationConstraint = false;
  47300. _this.lockedTarget = null;
  47301. _this._currentTarget = BABYLON.Vector3.Zero();
  47302. _this._viewMatrix = BABYLON.Matrix.Zero();
  47303. _this._camMatrix = BABYLON.Matrix.Zero();
  47304. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  47305. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  47306. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47307. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  47308. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47309. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47310. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47311. return _this;
  47312. }
  47313. TargetCamera.prototype.getFrontPosition = function (distance) {
  47314. this.getWorldMatrix();
  47315. var direction = this.getTarget().subtract(this.position);
  47316. direction.normalize();
  47317. direction.scaleInPlace(distance);
  47318. return this.globalPosition.add(direction);
  47319. };
  47320. TargetCamera.prototype._getLockedTargetPosition = function () {
  47321. if (!this.lockedTarget) {
  47322. return null;
  47323. }
  47324. if (this.lockedTarget.absolutePosition) {
  47325. this.lockedTarget.computeWorldMatrix();
  47326. }
  47327. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47328. };
  47329. TargetCamera.prototype.storeState = function () {
  47330. this._storedPosition = this.position.clone();
  47331. this._storedRotation = this.rotation.clone();
  47332. if (this.rotationQuaternion) {
  47333. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47334. }
  47335. return _super.prototype.storeState.call(this);
  47336. };
  47337. /**
  47338. * Restored camera state. You must call storeState() first
  47339. */
  47340. TargetCamera.prototype._restoreStateValues = function () {
  47341. if (!_super.prototype._restoreStateValues.call(this)) {
  47342. return false;
  47343. }
  47344. this.position = this._storedPosition.clone();
  47345. this.rotation = this._storedRotation.clone();
  47346. if (this.rotationQuaternion) {
  47347. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47348. }
  47349. this.cameraDirection.copyFromFloats(0, 0, 0);
  47350. this.cameraRotation.copyFromFloats(0, 0);
  47351. return true;
  47352. };
  47353. // Cache
  47354. TargetCamera.prototype._initCache = function () {
  47355. _super.prototype._initCache.call(this);
  47356. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47357. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47358. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47359. };
  47360. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47361. if (!ignoreParentClass) {
  47362. _super.prototype._updateCache.call(this);
  47363. }
  47364. var lockedTargetPosition = this._getLockedTargetPosition();
  47365. if (!lockedTargetPosition) {
  47366. this._cache.lockedTarget = null;
  47367. }
  47368. else {
  47369. if (!this._cache.lockedTarget) {
  47370. this._cache.lockedTarget = lockedTargetPosition.clone();
  47371. }
  47372. else {
  47373. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47374. }
  47375. }
  47376. this._cache.rotation.copyFrom(this.rotation);
  47377. if (this.rotationQuaternion)
  47378. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47379. };
  47380. // Synchronized
  47381. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47382. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47383. return false;
  47384. }
  47385. var lockedTargetPosition = this._getLockedTargetPosition();
  47386. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47387. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47388. };
  47389. // Methods
  47390. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47391. var engine = this.getEngine();
  47392. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47393. };
  47394. // Target
  47395. TargetCamera.prototype.setTarget = function (target) {
  47396. this.upVector.normalize();
  47397. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  47398. this._camMatrix.invert();
  47399. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47400. var vDir = target.subtract(this.position);
  47401. if (vDir.x >= 0.0) {
  47402. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47403. }
  47404. else {
  47405. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47406. }
  47407. this.rotation.z = 0;
  47408. if (isNaN(this.rotation.x)) {
  47409. this.rotation.x = 0;
  47410. }
  47411. if (isNaN(this.rotation.y)) {
  47412. this.rotation.y = 0;
  47413. }
  47414. if (isNaN(this.rotation.z)) {
  47415. this.rotation.z = 0;
  47416. }
  47417. if (this.rotationQuaternion) {
  47418. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47419. }
  47420. };
  47421. /**
  47422. * Return the current target position of the camera. This value is expressed in local space.
  47423. */
  47424. TargetCamera.prototype.getTarget = function () {
  47425. return this._currentTarget;
  47426. };
  47427. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47428. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47429. };
  47430. TargetCamera.prototype._updatePosition = function () {
  47431. if (this.parent) {
  47432. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47433. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47434. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47435. return;
  47436. }
  47437. this.position.addInPlace(this.cameraDirection);
  47438. };
  47439. TargetCamera.prototype._checkInputs = function () {
  47440. var needToMove = this._decideIfNeedsToMove();
  47441. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47442. // Move
  47443. if (needToMove) {
  47444. this._updatePosition();
  47445. }
  47446. // Rotate
  47447. if (needToRotate) {
  47448. this.rotation.x += this.cameraRotation.x;
  47449. this.rotation.y += this.cameraRotation.y;
  47450. //rotate, if quaternion is set and rotation was used
  47451. if (this.rotationQuaternion) {
  47452. var len = this.rotation.lengthSquared();
  47453. if (len) {
  47454. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47455. }
  47456. }
  47457. if (!this.noRotationConstraint) {
  47458. var limit = (Math.PI / 2) * 0.95;
  47459. if (this.rotation.x > limit)
  47460. this.rotation.x = limit;
  47461. if (this.rotation.x < -limit)
  47462. this.rotation.x = -limit;
  47463. }
  47464. }
  47465. // Inertia
  47466. if (needToMove) {
  47467. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47468. this.cameraDirection.x = 0;
  47469. }
  47470. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47471. this.cameraDirection.y = 0;
  47472. }
  47473. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47474. this.cameraDirection.z = 0;
  47475. }
  47476. this.cameraDirection.scaleInPlace(this.inertia);
  47477. }
  47478. if (needToRotate) {
  47479. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47480. this.cameraRotation.x = 0;
  47481. }
  47482. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47483. this.cameraRotation.y = 0;
  47484. }
  47485. this.cameraRotation.scaleInPlace(this.inertia);
  47486. }
  47487. _super.prototype._checkInputs.call(this);
  47488. };
  47489. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47490. if (this.rotationQuaternion) {
  47491. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47492. }
  47493. else {
  47494. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47495. }
  47496. //update the up vector!
  47497. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47498. };
  47499. TargetCamera.prototype._getViewMatrix = function () {
  47500. if (this.lockedTarget) {
  47501. this.setTarget(this._getLockedTargetPosition());
  47502. }
  47503. // Compute
  47504. this._updateCameraRotationMatrix();
  47505. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47506. // Computing target and final matrix
  47507. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47508. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47509. return this._viewMatrix;
  47510. };
  47511. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47512. if (this.parent) {
  47513. var parentWorldMatrix = this.parent.getWorldMatrix();
  47514. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47515. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47516. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47517. this._markSyncedWithParent();
  47518. }
  47519. else {
  47520. this._globalPosition.copyFrom(this.position);
  47521. this._globalCurrentTarget.copyFrom(target);
  47522. this._globalCurrentUpVector.copyFrom(up);
  47523. }
  47524. if (this.getScene().useRightHandedSystem) {
  47525. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47526. }
  47527. else {
  47528. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47529. }
  47530. };
  47531. /**
  47532. * @override
  47533. * Override Camera.createRigCamera
  47534. */
  47535. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47536. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47537. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47538. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47539. if (!this.rotationQuaternion) {
  47540. this.rotationQuaternion = new BABYLON.Quaternion();
  47541. }
  47542. rigCamera._cameraRigParams = {};
  47543. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47544. }
  47545. return rigCamera;
  47546. }
  47547. return null;
  47548. };
  47549. /**
  47550. * @override
  47551. * Override Camera._updateRigCameras
  47552. */
  47553. TargetCamera.prototype._updateRigCameras = function () {
  47554. var camLeft = this._rigCameras[0];
  47555. var camRight = this._rigCameras[1];
  47556. switch (this.cameraRigMode) {
  47557. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47558. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47559. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47560. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47561. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47562. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47563. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47564. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47565. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47566. camLeft.setTarget(this.getTarget());
  47567. camRight.setTarget(this.getTarget());
  47568. break;
  47569. case BABYLON.Camera.RIG_MODE_VR:
  47570. if (camLeft.rotationQuaternion) {
  47571. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47572. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47573. }
  47574. else {
  47575. camLeft.rotation.copyFrom(this.rotation);
  47576. camRight.rotation.copyFrom(this.rotation);
  47577. }
  47578. camLeft.position.copyFrom(this.position);
  47579. camRight.position.copyFrom(this.position);
  47580. break;
  47581. }
  47582. _super.prototype._updateRigCameras.call(this);
  47583. };
  47584. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47585. if (!this._rigCamTransformMatrix) {
  47586. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47587. }
  47588. var target = this.getTarget();
  47589. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47590. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47591. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47592. };
  47593. TargetCamera.prototype.getClassName = function () {
  47594. return "TargetCamera";
  47595. };
  47596. __decorate([
  47597. BABYLON.serializeAsVector3()
  47598. ], TargetCamera.prototype, "rotation", void 0);
  47599. __decorate([
  47600. BABYLON.serialize()
  47601. ], TargetCamera.prototype, "speed", void 0);
  47602. __decorate([
  47603. BABYLON.serializeAsMeshReference("lockedTargetId")
  47604. ], TargetCamera.prototype, "lockedTarget", void 0);
  47605. return TargetCamera;
  47606. }(BABYLON.Camera));
  47607. BABYLON.TargetCamera = TargetCamera;
  47608. })(BABYLON || (BABYLON = {}));
  47609. //# sourceMappingURL=babylon.targetCamera.js.map
  47610. var BABYLON;
  47611. (function (BABYLON) {
  47612. var FreeCameraMouseInput = /** @class */ (function () {
  47613. function FreeCameraMouseInput(touchEnabled) {
  47614. if (touchEnabled === void 0) { touchEnabled = true; }
  47615. this.touchEnabled = touchEnabled;
  47616. this.buttons = [0, 1, 2];
  47617. this.angularSensibility = 2000.0;
  47618. this.previousPosition = null;
  47619. }
  47620. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47621. var _this = this;
  47622. var engine = this.camera.getEngine();
  47623. if (!this._pointerInput) {
  47624. this._pointerInput = function (p, s) {
  47625. var evt = p.event;
  47626. if (engine.isInVRExclusivePointerMode) {
  47627. return;
  47628. }
  47629. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47630. return;
  47631. }
  47632. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47633. return;
  47634. }
  47635. var srcElement = (evt.srcElement || evt.target);
  47636. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47637. try {
  47638. srcElement.setPointerCapture(evt.pointerId);
  47639. }
  47640. catch (e) {
  47641. //Nothing to do with the error. Execution will continue.
  47642. }
  47643. _this.previousPosition = {
  47644. x: evt.clientX,
  47645. y: evt.clientY
  47646. };
  47647. if (!noPreventDefault) {
  47648. evt.preventDefault();
  47649. element.focus();
  47650. }
  47651. }
  47652. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47653. try {
  47654. srcElement.releasePointerCapture(evt.pointerId);
  47655. }
  47656. catch (e) {
  47657. //Nothing to do with the error.
  47658. }
  47659. _this.previousPosition = null;
  47660. if (!noPreventDefault) {
  47661. evt.preventDefault();
  47662. }
  47663. }
  47664. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47665. if (!_this.previousPosition || engine.isPointerLock) {
  47666. return;
  47667. }
  47668. var offsetX = evt.clientX - _this.previousPosition.x;
  47669. if (_this.camera.getScene().useRightHandedSystem)
  47670. offsetX *= -1;
  47671. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47672. offsetX *= -1;
  47673. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47674. var offsetY = evt.clientY - _this.previousPosition.y;
  47675. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47676. _this.previousPosition = {
  47677. x: evt.clientX,
  47678. y: evt.clientY
  47679. };
  47680. if (!noPreventDefault) {
  47681. evt.preventDefault();
  47682. }
  47683. }
  47684. };
  47685. }
  47686. this._onMouseMove = function (evt) {
  47687. if (!engine.isPointerLock) {
  47688. return;
  47689. }
  47690. if (engine.isInVRExclusivePointerMode) {
  47691. return;
  47692. }
  47693. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47694. if (_this.camera.getScene().useRightHandedSystem)
  47695. offsetX *= -1;
  47696. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47697. offsetX *= -1;
  47698. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47699. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47700. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47701. _this.previousPosition = null;
  47702. if (!noPreventDefault) {
  47703. evt.preventDefault();
  47704. }
  47705. };
  47706. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47707. element.addEventListener("mousemove", this._onMouseMove, false);
  47708. };
  47709. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47710. if (this._observer && element) {
  47711. this.camera.getScene().onPointerObservable.remove(this._observer);
  47712. if (this._onMouseMove) {
  47713. element.removeEventListener("mousemove", this._onMouseMove);
  47714. }
  47715. this._observer = null;
  47716. this._onMouseMove = null;
  47717. this.previousPosition = null;
  47718. }
  47719. };
  47720. FreeCameraMouseInput.prototype.getClassName = function () {
  47721. return "FreeCameraMouseInput";
  47722. };
  47723. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47724. return "mouse";
  47725. };
  47726. __decorate([
  47727. BABYLON.serialize()
  47728. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47729. __decorate([
  47730. BABYLON.serialize()
  47731. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47732. return FreeCameraMouseInput;
  47733. }());
  47734. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47735. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47736. })(BABYLON || (BABYLON = {}));
  47737. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47738. var BABYLON;
  47739. (function (BABYLON) {
  47740. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47741. function FreeCameraKeyboardMoveInput() {
  47742. this._keys = new Array();
  47743. this.keysUp = [38];
  47744. this.keysDown = [40];
  47745. this.keysLeft = [37];
  47746. this.keysRight = [39];
  47747. }
  47748. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47749. var _this = this;
  47750. if (this._onCanvasBlurObserver) {
  47751. return;
  47752. }
  47753. this._scene = this.camera.getScene();
  47754. this._engine = this._scene.getEngine();
  47755. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47756. _this._keys = [];
  47757. });
  47758. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47759. var evt = info.event;
  47760. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47761. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47762. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47763. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47764. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47765. var index = _this._keys.indexOf(evt.keyCode);
  47766. if (index === -1) {
  47767. _this._keys.push(evt.keyCode);
  47768. }
  47769. if (!noPreventDefault) {
  47770. evt.preventDefault();
  47771. }
  47772. }
  47773. }
  47774. else {
  47775. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47776. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47777. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47778. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47779. var index = _this._keys.indexOf(evt.keyCode);
  47780. if (index >= 0) {
  47781. _this._keys.splice(index, 1);
  47782. }
  47783. if (!noPreventDefault) {
  47784. evt.preventDefault();
  47785. }
  47786. }
  47787. }
  47788. });
  47789. };
  47790. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47791. if (this._scene) {
  47792. if (this._onKeyboardObserver) {
  47793. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47794. }
  47795. if (this._onCanvasBlurObserver) {
  47796. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47797. }
  47798. this._onKeyboardObserver = null;
  47799. this._onCanvasBlurObserver = null;
  47800. }
  47801. this._keys = [];
  47802. };
  47803. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47804. if (this._onKeyboardObserver) {
  47805. var camera = this.camera;
  47806. // Keyboard
  47807. for (var index = 0; index < this._keys.length; index++) {
  47808. var keyCode = this._keys[index];
  47809. var speed = camera._computeLocalCameraSpeed();
  47810. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47811. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47812. }
  47813. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47814. camera._localDirection.copyFromFloats(0, 0, speed);
  47815. }
  47816. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47817. camera._localDirection.copyFromFloats(speed, 0, 0);
  47818. }
  47819. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47820. camera._localDirection.copyFromFloats(0, 0, -speed);
  47821. }
  47822. if (camera.getScene().useRightHandedSystem) {
  47823. camera._localDirection.z *= -1;
  47824. }
  47825. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47826. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47827. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47828. }
  47829. }
  47830. };
  47831. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47832. return "FreeCameraKeyboardMoveInput";
  47833. };
  47834. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47835. this._keys = [];
  47836. };
  47837. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47838. return "keyboard";
  47839. };
  47840. __decorate([
  47841. BABYLON.serialize()
  47842. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47843. __decorate([
  47844. BABYLON.serialize()
  47845. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47846. __decorate([
  47847. BABYLON.serialize()
  47848. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47849. __decorate([
  47850. BABYLON.serialize()
  47851. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47852. return FreeCameraKeyboardMoveInput;
  47853. }());
  47854. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47855. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47856. })(BABYLON || (BABYLON = {}));
  47857. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47858. var BABYLON;
  47859. (function (BABYLON) {
  47860. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47861. __extends(FreeCameraInputsManager, _super);
  47862. function FreeCameraInputsManager(camera) {
  47863. return _super.call(this, camera) || this;
  47864. }
  47865. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47866. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47867. return this;
  47868. };
  47869. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47870. if (touchEnabled === void 0) { touchEnabled = true; }
  47871. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47872. return this;
  47873. };
  47874. FreeCameraInputsManager.prototype.addGamepad = function () {
  47875. this.add(new BABYLON.FreeCameraGamepadInput());
  47876. return this;
  47877. };
  47878. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47879. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47880. return this;
  47881. };
  47882. FreeCameraInputsManager.prototype.addTouch = function () {
  47883. this.add(new BABYLON.FreeCameraTouchInput());
  47884. return this;
  47885. };
  47886. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47887. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47888. return this;
  47889. };
  47890. return FreeCameraInputsManager;
  47891. }(BABYLON.CameraInputsManager));
  47892. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47893. })(BABYLON || (BABYLON = {}));
  47894. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47895. var BABYLON;
  47896. (function (BABYLON) {
  47897. var FreeCamera = /** @class */ (function (_super) {
  47898. __extends(FreeCamera, _super);
  47899. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47900. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47901. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47902. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47903. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47904. _this.checkCollisions = false;
  47905. _this.applyGravity = false;
  47906. _this._needMoveForGravity = false;
  47907. _this._oldPosition = BABYLON.Vector3.Zero();
  47908. _this._diffPosition = BABYLON.Vector3.Zero();
  47909. _this._newPosition = BABYLON.Vector3.Zero();
  47910. // Collisions
  47911. _this._collisionMask = -1;
  47912. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47913. if (collidedMesh === void 0) { collidedMesh = null; }
  47914. //TODO move this to the collision coordinator!
  47915. if (_this.getScene().workerCollisions)
  47916. newPosition.multiplyInPlace(_this._collider._radius);
  47917. var updatePosition = function (newPos) {
  47918. _this._newPosition.copyFrom(newPos);
  47919. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47920. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47921. _this.position.addInPlace(_this._diffPosition);
  47922. if (_this.onCollide && collidedMesh) {
  47923. _this.onCollide(collidedMesh);
  47924. }
  47925. }
  47926. };
  47927. updatePosition(newPosition);
  47928. };
  47929. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47930. _this.inputs.addKeyboard().addMouse();
  47931. return _this;
  47932. }
  47933. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47934. //-- begin properties for backward compatibility for inputs
  47935. /**
  47936. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47937. * Higher values reduce sensitivity.
  47938. */
  47939. get: function () {
  47940. var mouse = this.inputs.attached["mouse"];
  47941. if (mouse)
  47942. return mouse.angularSensibility;
  47943. return 0;
  47944. },
  47945. /**
  47946. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47947. * Higher values reduce sensitivity.
  47948. */
  47949. set: function (value) {
  47950. var mouse = this.inputs.attached["mouse"];
  47951. if (mouse)
  47952. mouse.angularSensibility = value;
  47953. },
  47954. enumerable: true,
  47955. configurable: true
  47956. });
  47957. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47958. get: function () {
  47959. var keyboard = this.inputs.attached["keyboard"];
  47960. if (keyboard)
  47961. return keyboard.keysUp;
  47962. return [];
  47963. },
  47964. set: function (value) {
  47965. var keyboard = this.inputs.attached["keyboard"];
  47966. if (keyboard)
  47967. keyboard.keysUp = value;
  47968. },
  47969. enumerable: true,
  47970. configurable: true
  47971. });
  47972. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47973. get: function () {
  47974. var keyboard = this.inputs.attached["keyboard"];
  47975. if (keyboard)
  47976. return keyboard.keysDown;
  47977. return [];
  47978. },
  47979. set: function (value) {
  47980. var keyboard = this.inputs.attached["keyboard"];
  47981. if (keyboard)
  47982. keyboard.keysDown = value;
  47983. },
  47984. enumerable: true,
  47985. configurable: true
  47986. });
  47987. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47988. get: function () {
  47989. var keyboard = this.inputs.attached["keyboard"];
  47990. if (keyboard)
  47991. return keyboard.keysLeft;
  47992. return [];
  47993. },
  47994. set: function (value) {
  47995. var keyboard = this.inputs.attached["keyboard"];
  47996. if (keyboard)
  47997. keyboard.keysLeft = value;
  47998. },
  47999. enumerable: true,
  48000. configurable: true
  48001. });
  48002. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  48003. get: function () {
  48004. var keyboard = this.inputs.attached["keyboard"];
  48005. if (keyboard)
  48006. return keyboard.keysRight;
  48007. return [];
  48008. },
  48009. set: function (value) {
  48010. var keyboard = this.inputs.attached["keyboard"];
  48011. if (keyboard)
  48012. keyboard.keysRight = value;
  48013. },
  48014. enumerable: true,
  48015. configurable: true
  48016. });
  48017. // Controls
  48018. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  48019. this.inputs.attachElement(element, noPreventDefault);
  48020. };
  48021. FreeCamera.prototype.detachControl = function (element) {
  48022. this.inputs.detachElement(element);
  48023. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  48024. this.cameraRotation = new BABYLON.Vector2(0, 0);
  48025. };
  48026. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  48027. get: function () {
  48028. return this._collisionMask;
  48029. },
  48030. set: function (mask) {
  48031. this._collisionMask = !isNaN(mask) ? mask : -1;
  48032. },
  48033. enumerable: true,
  48034. configurable: true
  48035. });
  48036. FreeCamera.prototype._collideWithWorld = function (displacement) {
  48037. var globalPosition;
  48038. if (this.parent) {
  48039. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  48040. }
  48041. else {
  48042. globalPosition = this.position;
  48043. }
  48044. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  48045. this._oldPosition.addInPlace(this.ellipsoidOffset);
  48046. if (!this._collider) {
  48047. this._collider = new BABYLON.Collider();
  48048. }
  48049. this._collider._radius = this.ellipsoid;
  48050. this._collider.collisionMask = this._collisionMask;
  48051. //no need for clone, as long as gravity is not on.
  48052. var actualDisplacement = displacement;
  48053. //add gravity to the direction to prevent the dual-collision checking
  48054. if (this.applyGravity) {
  48055. //this prevents mending with cameraDirection, a global variable of the free camera class.
  48056. actualDisplacement = displacement.add(this.getScene().gravity);
  48057. }
  48058. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48059. };
  48060. FreeCamera.prototype._checkInputs = function () {
  48061. if (!this._localDirection) {
  48062. this._localDirection = BABYLON.Vector3.Zero();
  48063. this._transformedDirection = BABYLON.Vector3.Zero();
  48064. }
  48065. this.inputs.checkInputs();
  48066. _super.prototype._checkInputs.call(this);
  48067. };
  48068. FreeCamera.prototype._decideIfNeedsToMove = function () {
  48069. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48070. };
  48071. FreeCamera.prototype._updatePosition = function () {
  48072. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  48073. this._collideWithWorld(this.cameraDirection);
  48074. }
  48075. else {
  48076. _super.prototype._updatePosition.call(this);
  48077. }
  48078. };
  48079. FreeCamera.prototype.dispose = function () {
  48080. this.inputs.clear();
  48081. _super.prototype.dispose.call(this);
  48082. };
  48083. FreeCamera.prototype.getClassName = function () {
  48084. return "FreeCamera";
  48085. };
  48086. __decorate([
  48087. BABYLON.serializeAsVector3()
  48088. ], FreeCamera.prototype, "ellipsoid", void 0);
  48089. __decorate([
  48090. BABYLON.serializeAsVector3()
  48091. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  48092. __decorate([
  48093. BABYLON.serialize()
  48094. ], FreeCamera.prototype, "checkCollisions", void 0);
  48095. __decorate([
  48096. BABYLON.serialize()
  48097. ], FreeCamera.prototype, "applyGravity", void 0);
  48098. return FreeCamera;
  48099. }(BABYLON.TargetCamera));
  48100. BABYLON.FreeCamera = FreeCamera;
  48101. })(BABYLON || (BABYLON = {}));
  48102. //# sourceMappingURL=babylon.freeCamera.js.map
  48103. var BABYLON;
  48104. (function (BABYLON) {
  48105. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  48106. function ArcRotateCameraKeyboardMoveInput() {
  48107. this._keys = new Array();
  48108. this.keysUp = [38];
  48109. this.keysDown = [40];
  48110. this.keysLeft = [37];
  48111. this.keysRight = [39];
  48112. this.keysReset = [220];
  48113. this.panningSensibility = 50.0;
  48114. this.zoomingSensibility = 25.0;
  48115. this.useAltToZoom = true;
  48116. }
  48117. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48118. var _this = this;
  48119. if (this._onCanvasBlurObserver) {
  48120. return;
  48121. }
  48122. this._scene = this.camera.getScene();
  48123. this._engine = this._scene.getEngine();
  48124. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48125. _this._keys = [];
  48126. });
  48127. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48128. var evt = info.event;
  48129. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48130. _this._ctrlPressed = evt.ctrlKey;
  48131. _this._altPressed = evt.altKey;
  48132. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48133. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48134. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48135. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48136. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48137. var index = _this._keys.indexOf(evt.keyCode);
  48138. if (index === -1) {
  48139. _this._keys.push(evt.keyCode);
  48140. }
  48141. if (evt.preventDefault) {
  48142. if (!noPreventDefault) {
  48143. evt.preventDefault();
  48144. }
  48145. }
  48146. }
  48147. }
  48148. else {
  48149. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48150. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48151. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48152. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48153. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48154. var index = _this._keys.indexOf(evt.keyCode);
  48155. if (index >= 0) {
  48156. _this._keys.splice(index, 1);
  48157. }
  48158. if (evt.preventDefault) {
  48159. if (!noPreventDefault) {
  48160. evt.preventDefault();
  48161. }
  48162. }
  48163. }
  48164. }
  48165. });
  48166. };
  48167. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48168. if (this._scene) {
  48169. if (this._onKeyboardObserver) {
  48170. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48171. }
  48172. if (this._onCanvasBlurObserver) {
  48173. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48174. }
  48175. this._onKeyboardObserver = null;
  48176. this._onCanvasBlurObserver = null;
  48177. }
  48178. this._keys = [];
  48179. };
  48180. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48181. if (this._onKeyboardObserver) {
  48182. var camera = this.camera;
  48183. for (var index = 0; index < this._keys.length; index++) {
  48184. var keyCode = this._keys[index];
  48185. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48186. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48187. camera.inertialPanningX -= 1 / this.panningSensibility;
  48188. }
  48189. else {
  48190. camera.inertialAlphaOffset -= 0.01;
  48191. }
  48192. }
  48193. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48194. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48195. camera.inertialPanningY += 1 / this.panningSensibility;
  48196. }
  48197. else if (this._altPressed && this.useAltToZoom) {
  48198. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  48199. }
  48200. else {
  48201. camera.inertialBetaOffset -= 0.01;
  48202. }
  48203. }
  48204. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48205. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48206. camera.inertialPanningX += 1 / this.panningSensibility;
  48207. }
  48208. else {
  48209. camera.inertialAlphaOffset += 0.01;
  48210. }
  48211. }
  48212. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48213. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48214. camera.inertialPanningY -= 1 / this.panningSensibility;
  48215. }
  48216. else if (this._altPressed && this.useAltToZoom) {
  48217. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  48218. }
  48219. else {
  48220. camera.inertialBetaOffset += 0.01;
  48221. }
  48222. }
  48223. else if (this.keysReset.indexOf(keyCode) !== -1) {
  48224. camera.restoreState();
  48225. }
  48226. }
  48227. }
  48228. };
  48229. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  48230. return "ArcRotateCameraKeyboardMoveInput";
  48231. };
  48232. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48233. return "keyboard";
  48234. };
  48235. __decorate([
  48236. BABYLON.serialize()
  48237. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48238. __decorate([
  48239. BABYLON.serialize()
  48240. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48241. __decorate([
  48242. BABYLON.serialize()
  48243. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48244. __decorate([
  48245. BABYLON.serialize()
  48246. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48247. __decorate([
  48248. BABYLON.serialize()
  48249. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  48250. __decorate([
  48251. BABYLON.serialize()
  48252. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  48253. __decorate([
  48254. BABYLON.serialize()
  48255. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  48256. __decorate([
  48257. BABYLON.serialize()
  48258. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  48259. return ArcRotateCameraKeyboardMoveInput;
  48260. }());
  48261. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  48262. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  48263. })(BABYLON || (BABYLON = {}));
  48264. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  48265. var BABYLON;
  48266. (function (BABYLON) {
  48267. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  48268. function ArcRotateCameraMouseWheelInput() {
  48269. this.wheelPrecision = 3.0;
  48270. /**
  48271. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  48272. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  48273. */
  48274. this.wheelDeltaPercentage = 0;
  48275. }
  48276. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  48277. var _this = this;
  48278. this._wheel = function (p, s) {
  48279. //sanity check - this should be a PointerWheel event.
  48280. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  48281. return;
  48282. var event = p.event;
  48283. var delta = 0;
  48284. if (event.wheelDelta) {
  48285. if (_this.wheelDeltaPercentage) {
  48286. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  48287. if (event.wheelDelta > 0) {
  48288. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  48289. }
  48290. else {
  48291. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  48292. }
  48293. }
  48294. else {
  48295. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  48296. }
  48297. }
  48298. else if (event.detail) {
  48299. delta = -event.detail / _this.wheelPrecision;
  48300. }
  48301. if (delta)
  48302. _this.camera.inertialRadiusOffset += delta;
  48303. if (event.preventDefault) {
  48304. if (!noPreventDefault) {
  48305. event.preventDefault();
  48306. }
  48307. }
  48308. };
  48309. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  48310. };
  48311. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  48312. if (this._observer && element) {
  48313. this.camera.getScene().onPointerObservable.remove(this._observer);
  48314. this._observer = null;
  48315. this._wheel = null;
  48316. }
  48317. };
  48318. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  48319. return "ArcRotateCameraMouseWheelInput";
  48320. };
  48321. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  48322. return "mousewheel";
  48323. };
  48324. __decorate([
  48325. BABYLON.serialize()
  48326. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  48327. __decorate([
  48328. BABYLON.serialize()
  48329. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  48330. return ArcRotateCameraMouseWheelInput;
  48331. }());
  48332. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  48333. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48334. })(BABYLON || (BABYLON = {}));
  48335. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48336. var BABYLON;
  48337. (function (BABYLON) {
  48338. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48339. function ArcRotateCameraPointersInput() {
  48340. this.buttons = [0, 1, 2];
  48341. this.angularSensibilityX = 1000.0;
  48342. this.angularSensibilityY = 1000.0;
  48343. this.pinchPrecision = 12.0;
  48344. /**
  48345. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48346. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48347. */
  48348. this.pinchDeltaPercentage = 0;
  48349. this.panningSensibility = 1000.0;
  48350. this.multiTouchPanning = true;
  48351. this.multiTouchPanAndZoom = true;
  48352. this._isPanClick = false;
  48353. this.pinchInwards = true;
  48354. }
  48355. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48356. var _this = this;
  48357. var engine = this.camera.getEngine();
  48358. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48359. var pointA = null;
  48360. var pointB = null;
  48361. var previousPinchSquaredDistance = 0;
  48362. var initialDistance = 0;
  48363. var twoFingerActivityCount = 0;
  48364. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48365. this._pointerInput = function (p, s) {
  48366. var evt = p.event;
  48367. var isTouch = p.event.pointerType === "touch";
  48368. if (engine.isInVRExclusivePointerMode) {
  48369. return;
  48370. }
  48371. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48372. return;
  48373. }
  48374. var srcElement = (evt.srcElement || evt.target);
  48375. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48376. try {
  48377. srcElement.setPointerCapture(evt.pointerId);
  48378. }
  48379. catch (e) {
  48380. //Nothing to do with the error. Execution will continue.
  48381. }
  48382. // Manage panning with pan button click
  48383. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48384. // manage pointers
  48385. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48386. if (pointA === null) {
  48387. pointA = cacheSoloPointer;
  48388. }
  48389. else if (pointB === null) {
  48390. pointB = cacheSoloPointer;
  48391. }
  48392. if (!noPreventDefault) {
  48393. evt.preventDefault();
  48394. element.focus();
  48395. }
  48396. }
  48397. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48398. _this.camera.restoreState();
  48399. }
  48400. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48401. try {
  48402. srcElement.releasePointerCapture(evt.pointerId);
  48403. }
  48404. catch (e) {
  48405. //Nothing to do with the error.
  48406. }
  48407. cacheSoloPointer = null;
  48408. previousPinchSquaredDistance = 0;
  48409. previousMultiTouchPanPosition.isPaning = false;
  48410. previousMultiTouchPanPosition.isPinching = false;
  48411. twoFingerActivityCount = 0;
  48412. initialDistance = 0;
  48413. if (!isTouch) {
  48414. pointB = null; // Mouse and pen are mono pointer
  48415. }
  48416. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48417. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48418. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48419. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48420. if (engine._badOS) {
  48421. pointA = pointB = null;
  48422. }
  48423. else {
  48424. //only remove the impacted pointer in case of multitouch allowing on most
  48425. //platforms switching from rotate to zoom and pan seamlessly.
  48426. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48427. pointA = pointB;
  48428. pointB = null;
  48429. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48430. }
  48431. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48432. pointB = null;
  48433. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48434. }
  48435. else {
  48436. pointA = pointB = null;
  48437. }
  48438. }
  48439. if (!noPreventDefault) {
  48440. evt.preventDefault();
  48441. }
  48442. }
  48443. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48444. if (!noPreventDefault) {
  48445. evt.preventDefault();
  48446. }
  48447. // One button down
  48448. if (pointA && pointB === null && cacheSoloPointer) {
  48449. if (_this.panningSensibility !== 0 &&
  48450. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48451. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48452. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48453. }
  48454. else {
  48455. var offsetX = evt.clientX - cacheSoloPointer.x;
  48456. var offsetY = evt.clientY - cacheSoloPointer.y;
  48457. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48458. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48459. }
  48460. cacheSoloPointer.x = evt.clientX;
  48461. cacheSoloPointer.y = evt.clientY;
  48462. }
  48463. // Two buttons down: pinch/pan
  48464. else if (pointA && pointB) {
  48465. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48466. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48467. ed.x = evt.clientX;
  48468. ed.y = evt.clientY;
  48469. var direction = _this.pinchInwards ? 1 : -1;
  48470. var distX = pointA.x - pointB.x;
  48471. var distY = pointA.y - pointB.y;
  48472. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48473. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48474. if (previousPinchSquaredDistance === 0) {
  48475. initialDistance = pinchDistance;
  48476. previousPinchSquaredDistance = pinchSquaredDistance;
  48477. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48478. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48479. return;
  48480. }
  48481. if (_this.multiTouchPanAndZoom) {
  48482. if (_this.pinchDeltaPercentage) {
  48483. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48484. }
  48485. else {
  48486. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48487. (_this.pinchPrecision *
  48488. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48489. direction);
  48490. }
  48491. if (_this.panningSensibility !== 0) {
  48492. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48493. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48494. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48495. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48496. previousMultiTouchPanPosition.x = pointersCenterX;
  48497. previousMultiTouchPanPosition.y = pointersCenterY;
  48498. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48499. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48500. }
  48501. }
  48502. else {
  48503. twoFingerActivityCount++;
  48504. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48505. if (_this.pinchDeltaPercentage) {
  48506. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48507. }
  48508. else {
  48509. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48510. (_this.pinchPrecision *
  48511. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48512. direction);
  48513. }
  48514. previousMultiTouchPanPosition.isPaning = false;
  48515. previousMultiTouchPanPosition.isPinching = true;
  48516. }
  48517. else {
  48518. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48519. if (!previousMultiTouchPanPosition.isPaning) {
  48520. previousMultiTouchPanPosition.isPaning = true;
  48521. previousMultiTouchPanPosition.isPinching = false;
  48522. previousMultiTouchPanPosition.x = ed.x;
  48523. previousMultiTouchPanPosition.y = ed.y;
  48524. return;
  48525. }
  48526. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48527. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48528. }
  48529. }
  48530. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48531. previousMultiTouchPanPosition.x = ed.x;
  48532. previousMultiTouchPanPosition.y = ed.y;
  48533. }
  48534. }
  48535. previousPinchSquaredDistance = pinchSquaredDistance;
  48536. }
  48537. }
  48538. };
  48539. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48540. this._onContextMenu = function (evt) {
  48541. evt.preventDefault();
  48542. };
  48543. if (!this.camera._useCtrlForPanning) {
  48544. element.addEventListener("contextmenu", this._onContextMenu, false);
  48545. }
  48546. this._onLostFocus = function () {
  48547. //this._keys = [];
  48548. pointA = pointB = null;
  48549. previousPinchSquaredDistance = 0;
  48550. previousMultiTouchPanPosition.isPaning = false;
  48551. previousMultiTouchPanPosition.isPinching = false;
  48552. twoFingerActivityCount = 0;
  48553. cacheSoloPointer = null;
  48554. initialDistance = 0;
  48555. };
  48556. this._onMouseMove = function (evt) {
  48557. if (!engine.isPointerLock) {
  48558. return;
  48559. }
  48560. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48561. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48562. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48563. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48564. if (!noPreventDefault) {
  48565. evt.preventDefault();
  48566. }
  48567. };
  48568. this._onGestureStart = function (e) {
  48569. if (window.MSGesture === undefined) {
  48570. return;
  48571. }
  48572. if (!_this._MSGestureHandler) {
  48573. _this._MSGestureHandler = new MSGesture();
  48574. _this._MSGestureHandler.target = element;
  48575. }
  48576. _this._MSGestureHandler.addPointer(e.pointerId);
  48577. };
  48578. this._onGesture = function (e) {
  48579. _this.camera.radius *= e.scale;
  48580. if (e.preventDefault) {
  48581. if (!noPreventDefault) {
  48582. e.stopPropagation();
  48583. e.preventDefault();
  48584. }
  48585. }
  48586. };
  48587. element.addEventListener("mousemove", this._onMouseMove, false);
  48588. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48589. element.addEventListener("MSGestureChange", this._onGesture, false);
  48590. BABYLON.Tools.RegisterTopRootEvents([
  48591. { name: "blur", handler: this._onLostFocus }
  48592. ]);
  48593. };
  48594. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48595. if (this._onLostFocus) {
  48596. BABYLON.Tools.UnregisterTopRootEvents([
  48597. { name: "blur", handler: this._onLostFocus }
  48598. ]);
  48599. }
  48600. if (element && this._observer) {
  48601. this.camera.getScene().onPointerObservable.remove(this._observer);
  48602. this._observer = null;
  48603. if (this._onContextMenu) {
  48604. element.removeEventListener("contextmenu", this._onContextMenu);
  48605. }
  48606. if (this._onMouseMove) {
  48607. element.removeEventListener("mousemove", this._onMouseMove);
  48608. }
  48609. if (this._onGestureStart) {
  48610. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48611. }
  48612. if (this._onGesture) {
  48613. element.removeEventListener("MSGestureChange", this._onGesture);
  48614. }
  48615. this._isPanClick = false;
  48616. this.pinchInwards = true;
  48617. this._onMouseMove = null;
  48618. this._onGestureStart = null;
  48619. this._onGesture = null;
  48620. this._MSGestureHandler = null;
  48621. this._onLostFocus = null;
  48622. this._onContextMenu = null;
  48623. }
  48624. };
  48625. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48626. return "ArcRotateCameraPointersInput";
  48627. };
  48628. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48629. return "pointers";
  48630. };
  48631. __decorate([
  48632. BABYLON.serialize()
  48633. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48634. __decorate([
  48635. BABYLON.serialize()
  48636. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48637. __decorate([
  48638. BABYLON.serialize()
  48639. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48640. __decorate([
  48641. BABYLON.serialize()
  48642. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48643. __decorate([
  48644. BABYLON.serialize()
  48645. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48646. __decorate([
  48647. BABYLON.serialize()
  48648. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48649. __decorate([
  48650. BABYLON.serialize()
  48651. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48652. __decorate([
  48653. BABYLON.serialize()
  48654. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48655. return ArcRotateCameraPointersInput;
  48656. }());
  48657. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48658. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48659. })(BABYLON || (BABYLON = {}));
  48660. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48661. var BABYLON;
  48662. (function (BABYLON) {
  48663. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48664. __extends(ArcRotateCameraInputsManager, _super);
  48665. function ArcRotateCameraInputsManager(camera) {
  48666. return _super.call(this, camera) || this;
  48667. }
  48668. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48669. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48670. return this;
  48671. };
  48672. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48673. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48674. return this;
  48675. };
  48676. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48677. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48678. return this;
  48679. };
  48680. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48681. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48682. return this;
  48683. };
  48684. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48685. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48686. return this;
  48687. };
  48688. return ArcRotateCameraInputsManager;
  48689. }(BABYLON.CameraInputsManager));
  48690. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48691. })(BABYLON || (BABYLON = {}));
  48692. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48693. var BABYLON;
  48694. (function (BABYLON) {
  48695. var ArcRotateCamera = /** @class */ (function (_super) {
  48696. __extends(ArcRotateCamera, _super);
  48697. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48698. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48699. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48700. _this.inertialAlphaOffset = 0;
  48701. _this.inertialBetaOffset = 0;
  48702. _this.inertialRadiusOffset = 0;
  48703. _this.lowerAlphaLimit = null;
  48704. _this.upperAlphaLimit = null;
  48705. _this.lowerBetaLimit = 0.01;
  48706. _this.upperBetaLimit = Math.PI;
  48707. _this.lowerRadiusLimit = null;
  48708. _this.upperRadiusLimit = null;
  48709. _this.inertialPanningX = 0;
  48710. _this.inertialPanningY = 0;
  48711. _this.pinchToPanMaxDistance = 20;
  48712. _this.panningDistanceLimit = null;
  48713. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48714. _this.panningInertia = 0.9;
  48715. //-- end properties for backward compatibility for inputs
  48716. _this.zoomOnFactor = 1;
  48717. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48718. _this.allowUpsideDown = true;
  48719. _this._viewMatrix = new BABYLON.Matrix();
  48720. // Panning
  48721. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48722. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48723. _this.checkCollisions = false;
  48724. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48725. _this._previousPosition = BABYLON.Vector3.Zero();
  48726. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48727. _this._newPosition = BABYLON.Vector3.Zero();
  48728. _this._computationVector = BABYLON.Vector3.Zero();
  48729. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48730. if (collidedMesh === void 0) { collidedMesh = null; }
  48731. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48732. newPosition.multiplyInPlace(_this._collider._radius);
  48733. }
  48734. if (!collidedMesh) {
  48735. _this._previousPosition.copyFrom(_this.position);
  48736. }
  48737. else {
  48738. _this.setPosition(newPosition);
  48739. if (_this.onCollide) {
  48740. _this.onCollide(collidedMesh);
  48741. }
  48742. }
  48743. // Recompute because of constraints
  48744. var cosa = Math.cos(_this.alpha);
  48745. var sina = Math.sin(_this.alpha);
  48746. var cosb = Math.cos(_this.beta);
  48747. var sinb = Math.sin(_this.beta);
  48748. if (sinb === 0) {
  48749. sinb = 0.0001;
  48750. }
  48751. var target = _this._getTargetPosition();
  48752. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48753. target.addToRef(_this._computationVector, _this._newPosition);
  48754. _this.position.copyFrom(_this._newPosition);
  48755. var up = _this.upVector;
  48756. if (_this.allowUpsideDown && _this.beta < 0) {
  48757. up = up.clone();
  48758. up = up.negate();
  48759. }
  48760. _this._computeViewMatrix(_this.position, target, up);
  48761. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48762. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48763. _this._collisionTriggered = false;
  48764. };
  48765. _this._target = BABYLON.Vector3.Zero();
  48766. if (target) {
  48767. _this.setTarget(target);
  48768. }
  48769. _this.alpha = alpha;
  48770. _this.beta = beta;
  48771. _this.radius = radius;
  48772. _this.getViewMatrix();
  48773. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48774. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48775. return _this;
  48776. }
  48777. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48778. get: function () {
  48779. return this._target;
  48780. },
  48781. set: function (value) {
  48782. this.setTarget(value);
  48783. },
  48784. enumerable: true,
  48785. configurable: true
  48786. });
  48787. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48788. //-- begin properties for backward compatibility for inputs
  48789. get: function () {
  48790. var pointers = this.inputs.attached["pointers"];
  48791. if (pointers)
  48792. return pointers.angularSensibilityX;
  48793. return 0;
  48794. },
  48795. set: function (value) {
  48796. var pointers = this.inputs.attached["pointers"];
  48797. if (pointers) {
  48798. pointers.angularSensibilityX = value;
  48799. }
  48800. },
  48801. enumerable: true,
  48802. configurable: true
  48803. });
  48804. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48805. get: function () {
  48806. var pointers = this.inputs.attached["pointers"];
  48807. if (pointers)
  48808. return pointers.angularSensibilityY;
  48809. return 0;
  48810. },
  48811. set: function (value) {
  48812. var pointers = this.inputs.attached["pointers"];
  48813. if (pointers) {
  48814. pointers.angularSensibilityY = value;
  48815. }
  48816. },
  48817. enumerable: true,
  48818. configurable: true
  48819. });
  48820. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48821. get: function () {
  48822. var pointers = this.inputs.attached["pointers"];
  48823. if (pointers)
  48824. return pointers.pinchPrecision;
  48825. return 0;
  48826. },
  48827. set: function (value) {
  48828. var pointers = this.inputs.attached["pointers"];
  48829. if (pointers) {
  48830. pointers.pinchPrecision = value;
  48831. }
  48832. },
  48833. enumerable: true,
  48834. configurable: true
  48835. });
  48836. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48837. get: function () {
  48838. var pointers = this.inputs.attached["pointers"];
  48839. if (pointers)
  48840. return pointers.pinchDeltaPercentage;
  48841. return 0;
  48842. },
  48843. set: function (value) {
  48844. var pointers = this.inputs.attached["pointers"];
  48845. if (pointers) {
  48846. pointers.pinchDeltaPercentage = value;
  48847. }
  48848. },
  48849. enumerable: true,
  48850. configurable: true
  48851. });
  48852. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48853. get: function () {
  48854. var pointers = this.inputs.attached["pointers"];
  48855. if (pointers)
  48856. return pointers.panningSensibility;
  48857. return 0;
  48858. },
  48859. set: function (value) {
  48860. var pointers = this.inputs.attached["pointers"];
  48861. if (pointers) {
  48862. pointers.panningSensibility = value;
  48863. }
  48864. },
  48865. enumerable: true,
  48866. configurable: true
  48867. });
  48868. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48869. get: function () {
  48870. var keyboard = this.inputs.attached["keyboard"];
  48871. if (keyboard)
  48872. return keyboard.keysUp;
  48873. return [];
  48874. },
  48875. set: function (value) {
  48876. var keyboard = this.inputs.attached["keyboard"];
  48877. if (keyboard)
  48878. keyboard.keysUp = value;
  48879. },
  48880. enumerable: true,
  48881. configurable: true
  48882. });
  48883. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48884. get: function () {
  48885. var keyboard = this.inputs.attached["keyboard"];
  48886. if (keyboard)
  48887. return keyboard.keysDown;
  48888. return [];
  48889. },
  48890. set: function (value) {
  48891. var keyboard = this.inputs.attached["keyboard"];
  48892. if (keyboard)
  48893. keyboard.keysDown = value;
  48894. },
  48895. enumerable: true,
  48896. configurable: true
  48897. });
  48898. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48899. get: function () {
  48900. var keyboard = this.inputs.attached["keyboard"];
  48901. if (keyboard)
  48902. return keyboard.keysLeft;
  48903. return [];
  48904. },
  48905. set: function (value) {
  48906. var keyboard = this.inputs.attached["keyboard"];
  48907. if (keyboard)
  48908. keyboard.keysLeft = value;
  48909. },
  48910. enumerable: true,
  48911. configurable: true
  48912. });
  48913. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48914. get: function () {
  48915. var keyboard = this.inputs.attached["keyboard"];
  48916. if (keyboard)
  48917. return keyboard.keysRight;
  48918. return [];
  48919. },
  48920. set: function (value) {
  48921. var keyboard = this.inputs.attached["keyboard"];
  48922. if (keyboard)
  48923. keyboard.keysRight = value;
  48924. },
  48925. enumerable: true,
  48926. configurable: true
  48927. });
  48928. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48929. get: function () {
  48930. var mousewheel = this.inputs.attached["mousewheel"];
  48931. if (mousewheel)
  48932. return mousewheel.wheelPrecision;
  48933. return 0;
  48934. },
  48935. set: function (value) {
  48936. var mousewheel = this.inputs.attached["mousewheel"];
  48937. if (mousewheel)
  48938. mousewheel.wheelPrecision = value;
  48939. },
  48940. enumerable: true,
  48941. configurable: true
  48942. });
  48943. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48944. get: function () {
  48945. var mousewheel = this.inputs.attached["mousewheel"];
  48946. if (mousewheel)
  48947. return mousewheel.wheelDeltaPercentage;
  48948. return 0;
  48949. },
  48950. set: function (value) {
  48951. var mousewheel = this.inputs.attached["mousewheel"];
  48952. if (mousewheel)
  48953. mousewheel.wheelDeltaPercentage = value;
  48954. },
  48955. enumerable: true,
  48956. configurable: true
  48957. });
  48958. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48959. get: function () {
  48960. return this._bouncingBehavior;
  48961. },
  48962. enumerable: true,
  48963. configurable: true
  48964. });
  48965. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48966. get: function () {
  48967. return this._bouncingBehavior != null;
  48968. },
  48969. set: function (value) {
  48970. if (value === this.useBouncingBehavior) {
  48971. return;
  48972. }
  48973. if (value) {
  48974. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48975. this.addBehavior(this._bouncingBehavior);
  48976. }
  48977. else if (this._bouncingBehavior) {
  48978. this.removeBehavior(this._bouncingBehavior);
  48979. this._bouncingBehavior = null;
  48980. }
  48981. },
  48982. enumerable: true,
  48983. configurable: true
  48984. });
  48985. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48986. get: function () {
  48987. return this._framingBehavior;
  48988. },
  48989. enumerable: true,
  48990. configurable: true
  48991. });
  48992. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48993. get: function () {
  48994. return this._framingBehavior != null;
  48995. },
  48996. set: function (value) {
  48997. if (value === this.useFramingBehavior) {
  48998. return;
  48999. }
  49000. if (value) {
  49001. this._framingBehavior = new BABYLON.FramingBehavior();
  49002. this.addBehavior(this._framingBehavior);
  49003. }
  49004. else if (this._framingBehavior) {
  49005. this.removeBehavior(this._framingBehavior);
  49006. this._framingBehavior = null;
  49007. }
  49008. },
  49009. enumerable: true,
  49010. configurable: true
  49011. });
  49012. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  49013. get: function () {
  49014. return this._autoRotationBehavior;
  49015. },
  49016. enumerable: true,
  49017. configurable: true
  49018. });
  49019. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  49020. get: function () {
  49021. return this._autoRotationBehavior != null;
  49022. },
  49023. set: function (value) {
  49024. if (value === this.useAutoRotationBehavior) {
  49025. return;
  49026. }
  49027. if (value) {
  49028. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  49029. this.addBehavior(this._autoRotationBehavior);
  49030. }
  49031. else if (this._autoRotationBehavior) {
  49032. this.removeBehavior(this._autoRotationBehavior);
  49033. this._autoRotationBehavior = null;
  49034. }
  49035. },
  49036. enumerable: true,
  49037. configurable: true
  49038. });
  49039. // Cache
  49040. ArcRotateCamera.prototype._initCache = function () {
  49041. _super.prototype._initCache.call(this);
  49042. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  49043. this._cache.alpha = undefined;
  49044. this._cache.beta = undefined;
  49045. this._cache.radius = undefined;
  49046. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  49047. };
  49048. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  49049. if (!ignoreParentClass) {
  49050. _super.prototype._updateCache.call(this);
  49051. }
  49052. this._cache._target.copyFrom(this._getTargetPosition());
  49053. this._cache.alpha = this.alpha;
  49054. this._cache.beta = this.beta;
  49055. this._cache.radius = this.radius;
  49056. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  49057. };
  49058. ArcRotateCamera.prototype._getTargetPosition = function () {
  49059. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  49060. var pos = this._targetHost.getAbsolutePosition();
  49061. if (this._targetBoundingCenter) {
  49062. pos.addToRef(this._targetBoundingCenter, this._target);
  49063. }
  49064. else {
  49065. this._target.copyFrom(pos);
  49066. }
  49067. }
  49068. var lockedTargetPosition = this._getLockedTargetPosition();
  49069. if (lockedTargetPosition) {
  49070. return lockedTargetPosition;
  49071. }
  49072. return this._target;
  49073. };
  49074. ArcRotateCamera.prototype.storeState = function () {
  49075. this._storedAlpha = this.alpha;
  49076. this._storedBeta = this.beta;
  49077. this._storedRadius = this.radius;
  49078. this._storedTarget = this._getTargetPosition().clone();
  49079. return _super.prototype.storeState.call(this);
  49080. };
  49081. /**
  49082. * Restored camera state. You must call storeState() first
  49083. */
  49084. ArcRotateCamera.prototype._restoreStateValues = function () {
  49085. if (!_super.prototype._restoreStateValues.call(this)) {
  49086. return false;
  49087. }
  49088. this.alpha = this._storedAlpha;
  49089. this.beta = this._storedBeta;
  49090. this.radius = this._storedRadius;
  49091. this.setTarget(this._storedTarget.clone());
  49092. this.inertialAlphaOffset = 0;
  49093. this.inertialBetaOffset = 0;
  49094. this.inertialRadiusOffset = 0;
  49095. this.inertialPanningX = 0;
  49096. this.inertialPanningY = 0;
  49097. return true;
  49098. };
  49099. // Synchronized
  49100. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  49101. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  49102. return false;
  49103. return this._cache._target.equals(this._getTargetPosition())
  49104. && this._cache.alpha === this.alpha
  49105. && this._cache.beta === this.beta
  49106. && this._cache.radius === this.radius
  49107. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  49108. };
  49109. // Methods
  49110. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  49111. var _this = this;
  49112. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  49113. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  49114. this._useCtrlForPanning = useCtrlForPanning;
  49115. this._panningMouseButton = panningMouseButton;
  49116. this.inputs.attachElement(element, noPreventDefault);
  49117. this._reset = function () {
  49118. _this.inertialAlphaOffset = 0;
  49119. _this.inertialBetaOffset = 0;
  49120. _this.inertialRadiusOffset = 0;
  49121. _this.inertialPanningX = 0;
  49122. _this.inertialPanningY = 0;
  49123. };
  49124. };
  49125. ArcRotateCamera.prototype.detachControl = function (element) {
  49126. this.inputs.detachElement(element);
  49127. if (this._reset) {
  49128. this._reset();
  49129. }
  49130. };
  49131. ArcRotateCamera.prototype._checkInputs = function () {
  49132. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  49133. if (this._collisionTriggered) {
  49134. return;
  49135. }
  49136. this.inputs.checkInputs();
  49137. // Inertia
  49138. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  49139. var inertialAlphaOffset = this.inertialAlphaOffset;
  49140. if (this.beta <= 0)
  49141. inertialAlphaOffset *= -1;
  49142. if (this.getScene().useRightHandedSystem)
  49143. inertialAlphaOffset *= -1;
  49144. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  49145. inertialAlphaOffset *= -1;
  49146. this.alpha += inertialAlphaOffset;
  49147. this.beta += this.inertialBetaOffset;
  49148. this.radius -= this.inertialRadiusOffset;
  49149. this.inertialAlphaOffset *= this.inertia;
  49150. this.inertialBetaOffset *= this.inertia;
  49151. this.inertialRadiusOffset *= this.inertia;
  49152. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  49153. this.inertialAlphaOffset = 0;
  49154. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  49155. this.inertialBetaOffset = 0;
  49156. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  49157. this.inertialRadiusOffset = 0;
  49158. }
  49159. // Panning inertia
  49160. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  49161. if (!this._localDirection) {
  49162. this._localDirection = BABYLON.Vector3.Zero();
  49163. this._transformedDirection = BABYLON.Vector3.Zero();
  49164. }
  49165. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  49166. this._localDirection.multiplyInPlace(this.panningAxis);
  49167. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  49168. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  49169. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  49170. if (!this.panningAxis.y) {
  49171. this._transformedDirection.y = 0;
  49172. }
  49173. if (!this._targetHost) {
  49174. if (this.panningDistanceLimit) {
  49175. this._transformedDirection.addInPlace(this._target);
  49176. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  49177. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  49178. this._target.copyFrom(this._transformedDirection);
  49179. }
  49180. }
  49181. else {
  49182. this._target.addInPlace(this._transformedDirection);
  49183. }
  49184. }
  49185. this.inertialPanningX *= this.panningInertia;
  49186. this.inertialPanningY *= this.panningInertia;
  49187. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  49188. this.inertialPanningX = 0;
  49189. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  49190. this.inertialPanningY = 0;
  49191. }
  49192. // Limits
  49193. this._checkLimits();
  49194. _super.prototype._checkInputs.call(this);
  49195. };
  49196. ArcRotateCamera.prototype._checkLimits = function () {
  49197. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  49198. if (this.allowUpsideDown && this.beta > Math.PI) {
  49199. this.beta = this.beta - (2 * Math.PI);
  49200. }
  49201. }
  49202. else {
  49203. if (this.beta < this.lowerBetaLimit) {
  49204. this.beta = this.lowerBetaLimit;
  49205. }
  49206. }
  49207. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  49208. if (this.allowUpsideDown && this.beta < -Math.PI) {
  49209. this.beta = this.beta + (2 * Math.PI);
  49210. }
  49211. }
  49212. else {
  49213. if (this.beta > this.upperBetaLimit) {
  49214. this.beta = this.upperBetaLimit;
  49215. }
  49216. }
  49217. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  49218. this.alpha = this.lowerAlphaLimit;
  49219. }
  49220. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  49221. this.alpha = this.upperAlphaLimit;
  49222. }
  49223. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  49224. this.radius = this.lowerRadiusLimit;
  49225. }
  49226. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  49227. this.radius = this.upperRadiusLimit;
  49228. }
  49229. };
  49230. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  49231. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  49232. this.radius = this._computationVector.length();
  49233. if (this.radius === 0) {
  49234. this.radius = 0.0001; // Just to avoid division by zero
  49235. }
  49236. // Alpha
  49237. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  49238. if (this._computationVector.z < 0) {
  49239. this.alpha = 2 * Math.PI - this.alpha;
  49240. }
  49241. // Beta
  49242. this.beta = Math.acos(this._computationVector.y / this.radius);
  49243. this._checkLimits();
  49244. };
  49245. ArcRotateCamera.prototype.setPosition = function (position) {
  49246. if (this.position.equals(position)) {
  49247. return;
  49248. }
  49249. this.position.copyFrom(position);
  49250. this.rebuildAnglesAndRadius();
  49251. };
  49252. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  49253. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  49254. if (allowSamePosition === void 0) { allowSamePosition = false; }
  49255. if (target.getBoundingInfo) {
  49256. if (toBoundingCenter) {
  49257. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  49258. }
  49259. else {
  49260. this._targetBoundingCenter = null;
  49261. }
  49262. this._targetHost = target;
  49263. this._target = this._getTargetPosition();
  49264. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  49265. }
  49266. else {
  49267. var newTarget = target;
  49268. var currentTarget = this._getTargetPosition();
  49269. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  49270. return;
  49271. }
  49272. this._targetHost = null;
  49273. this._target = newTarget;
  49274. this._targetBoundingCenter = null;
  49275. this.onMeshTargetChangedObservable.notifyObservers(null);
  49276. }
  49277. this.rebuildAnglesAndRadius();
  49278. };
  49279. ArcRotateCamera.prototype._getViewMatrix = function () {
  49280. // Compute
  49281. var cosa = Math.cos(this.alpha);
  49282. var sina = Math.sin(this.alpha);
  49283. var cosb = Math.cos(this.beta);
  49284. var sinb = Math.sin(this.beta);
  49285. if (sinb === 0) {
  49286. sinb = 0.0001;
  49287. }
  49288. var target = this._getTargetPosition();
  49289. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49290. target.addToRef(this._computationVector, this._newPosition);
  49291. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49292. if (!this._collider) {
  49293. this._collider = new BABYLON.Collider();
  49294. }
  49295. this._collider._radius = this.collisionRadius;
  49296. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49297. this._collisionTriggered = true;
  49298. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49299. }
  49300. else {
  49301. this.position.copyFrom(this._newPosition);
  49302. var up = this.upVector;
  49303. if (this.allowUpsideDown && sinb < 0) {
  49304. up = up.clone();
  49305. up = up.negate();
  49306. }
  49307. this._computeViewMatrix(this.position, target, up);
  49308. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49309. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49310. }
  49311. this._currentTarget = target;
  49312. return this._viewMatrix;
  49313. };
  49314. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49315. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49316. meshes = meshes || this.getScene().meshes;
  49317. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49318. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49319. this.radius = distance * this.zoomOnFactor;
  49320. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49321. };
  49322. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  49323. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49324. var meshesOrMinMaxVector;
  49325. var distance;
  49326. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  49327. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  49328. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  49329. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  49330. }
  49331. else { //minMaxVector and distance
  49332. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  49333. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49334. distance = minMaxVectorAndDistance.distance;
  49335. }
  49336. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49337. if (!doNotUpdateMaxZ) {
  49338. this.maxZ = distance * 2;
  49339. }
  49340. };
  49341. /**
  49342. * @override
  49343. * Override Camera.createRigCamera
  49344. */
  49345. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49346. var alphaShift = 0;
  49347. switch (this.cameraRigMode) {
  49348. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49349. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49350. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49351. case BABYLON.Camera.RIG_MODE_VR:
  49352. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49353. break;
  49354. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49355. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49356. break;
  49357. }
  49358. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49359. rigCam._cameraRigParams = {};
  49360. return rigCam;
  49361. };
  49362. /**
  49363. * @override
  49364. * Override Camera._updateRigCameras
  49365. */
  49366. ArcRotateCamera.prototype._updateRigCameras = function () {
  49367. var camLeft = this._rigCameras[0];
  49368. var camRight = this._rigCameras[1];
  49369. camLeft.beta = camRight.beta = this.beta;
  49370. camLeft.radius = camRight.radius = this.radius;
  49371. switch (this.cameraRigMode) {
  49372. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49373. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49374. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49375. case BABYLON.Camera.RIG_MODE_VR:
  49376. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49377. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49378. break;
  49379. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49380. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49381. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49382. break;
  49383. }
  49384. _super.prototype._updateRigCameras.call(this);
  49385. };
  49386. ArcRotateCamera.prototype.dispose = function () {
  49387. this.inputs.clear();
  49388. _super.prototype.dispose.call(this);
  49389. };
  49390. ArcRotateCamera.prototype.getClassName = function () {
  49391. return "ArcRotateCamera";
  49392. };
  49393. __decorate([
  49394. BABYLON.serialize()
  49395. ], ArcRotateCamera.prototype, "alpha", void 0);
  49396. __decorate([
  49397. BABYLON.serialize()
  49398. ], ArcRotateCamera.prototype, "beta", void 0);
  49399. __decorate([
  49400. BABYLON.serialize()
  49401. ], ArcRotateCamera.prototype, "radius", void 0);
  49402. __decorate([
  49403. BABYLON.serializeAsVector3("target")
  49404. ], ArcRotateCamera.prototype, "_target", void 0);
  49405. __decorate([
  49406. BABYLON.serialize()
  49407. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49408. __decorate([
  49409. BABYLON.serialize()
  49410. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49411. __decorate([
  49412. BABYLON.serialize()
  49413. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49414. __decorate([
  49415. BABYLON.serialize()
  49416. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49417. __decorate([
  49418. BABYLON.serialize()
  49419. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49420. __decorate([
  49421. BABYLON.serialize()
  49422. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49423. __decorate([
  49424. BABYLON.serialize()
  49425. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49426. __decorate([
  49427. BABYLON.serialize()
  49428. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49429. __decorate([
  49430. BABYLON.serialize()
  49431. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49432. __decorate([
  49433. BABYLON.serialize()
  49434. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49435. __decorate([
  49436. BABYLON.serialize()
  49437. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49438. __decorate([
  49439. BABYLON.serialize()
  49440. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49441. __decorate([
  49442. BABYLON.serialize()
  49443. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49444. __decorate([
  49445. BABYLON.serializeAsVector3()
  49446. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49447. __decorate([
  49448. BABYLON.serialize()
  49449. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49450. __decorate([
  49451. BABYLON.serialize()
  49452. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49453. __decorate([
  49454. BABYLON.serialize()
  49455. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49456. return ArcRotateCamera;
  49457. }(BABYLON.TargetCamera));
  49458. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49459. })(BABYLON || (BABYLON = {}));
  49460. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49461. var BABYLON;
  49462. (function (BABYLON) {
  49463. /**
  49464. * The HemisphericLight simulates the ambient environment light,
  49465. * so the passed direction is the light reflection direction, not the incoming direction.
  49466. */
  49467. var HemisphericLight = /** @class */ (function (_super) {
  49468. __extends(HemisphericLight, _super);
  49469. /**
  49470. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49471. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49472. * The HemisphericLight can't cast shadows.
  49473. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49474. * @param name The friendly name of the light
  49475. * @param direction The direction of the light reflection
  49476. * @param scene The scene the light belongs to
  49477. */
  49478. function HemisphericLight(name, direction, scene) {
  49479. var _this = _super.call(this, name, scene) || this;
  49480. /**
  49481. * The groundColor is the light in the opposite direction to the one specified during creation.
  49482. * You can think of the diffuse and specular light as coming from the centre of the object in the given direction and the groundColor light in the opposite direction.
  49483. */
  49484. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49485. _this.direction = direction || BABYLON.Vector3.Up();
  49486. return _this;
  49487. }
  49488. HemisphericLight.prototype._buildUniformLayout = function () {
  49489. this._uniformBuffer.addUniform("vLightData", 4);
  49490. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49491. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49492. this._uniformBuffer.addUniform("vLightGround", 3);
  49493. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49494. this._uniformBuffer.addUniform("depthValues", 2);
  49495. this._uniformBuffer.create();
  49496. };
  49497. /**
  49498. * Returns the string "HemisphericLight".
  49499. * @return The class name
  49500. */
  49501. HemisphericLight.prototype.getClassName = function () {
  49502. return "HemisphericLight";
  49503. };
  49504. /**
  49505. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49506. * Returns the updated direction.
  49507. * @param target The target the direction should point to
  49508. * @return The computed direction
  49509. */
  49510. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49511. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49512. return this.direction;
  49513. };
  49514. /**
  49515. * Returns the shadow generator associated to the light.
  49516. * @returns Always null for hemispheric lights because it does not support shadows.
  49517. */
  49518. HemisphericLight.prototype.getShadowGenerator = function () {
  49519. return null;
  49520. };
  49521. /**
  49522. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49523. * @param effect The effect to update
  49524. * @param lightIndex The index of the light in the effect to update
  49525. * @returns The hemispheric light
  49526. */
  49527. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49528. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49529. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49530. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49531. return this;
  49532. };
  49533. /**
  49534. * @hidden internal use only.
  49535. */
  49536. HemisphericLight.prototype._getWorldMatrix = function () {
  49537. if (!this._worldMatrix) {
  49538. this._worldMatrix = BABYLON.Matrix.Identity();
  49539. }
  49540. return this._worldMatrix;
  49541. };
  49542. /**
  49543. * Returns the integer 3.
  49544. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49545. */
  49546. HemisphericLight.prototype.getTypeID = function () {
  49547. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49548. };
  49549. __decorate([
  49550. BABYLON.serializeAsColor3()
  49551. ], HemisphericLight.prototype, "groundColor", void 0);
  49552. __decorate([
  49553. BABYLON.serializeAsVector3()
  49554. ], HemisphericLight.prototype, "direction", void 0);
  49555. return HemisphericLight;
  49556. }(BABYLON.Light));
  49557. BABYLON.HemisphericLight = HemisphericLight;
  49558. })(BABYLON || (BABYLON = {}));
  49559. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49560. var BABYLON;
  49561. (function (BABYLON) {
  49562. /**
  49563. * Base implementation IShadowLight
  49564. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49565. */
  49566. var ShadowLight = /** @class */ (function (_super) {
  49567. __extends(ShadowLight, _super);
  49568. function ShadowLight() {
  49569. var _this = _super !== null && _super.apply(this, arguments) || this;
  49570. _this._needProjectionMatrixCompute = true;
  49571. return _this;
  49572. }
  49573. ShadowLight.prototype._setPosition = function (value) {
  49574. this._position = value;
  49575. };
  49576. Object.defineProperty(ShadowLight.prototype, "position", {
  49577. /**
  49578. * Sets the position the shadow will be casted from. Also use as the light position for both
  49579. * point and spot lights.
  49580. */
  49581. get: function () {
  49582. return this._position;
  49583. },
  49584. /**
  49585. * Sets the position the shadow will be casted from. Also use as the light position for both
  49586. * point and spot lights.
  49587. */
  49588. set: function (value) {
  49589. this._setPosition(value);
  49590. },
  49591. enumerable: true,
  49592. configurable: true
  49593. });
  49594. ShadowLight.prototype._setDirection = function (value) {
  49595. this._direction = value;
  49596. };
  49597. Object.defineProperty(ShadowLight.prototype, "direction", {
  49598. /**
  49599. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49600. * Also use as the light direction on spot and directional lights.
  49601. */
  49602. get: function () {
  49603. return this._direction;
  49604. },
  49605. /**
  49606. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49607. * Also use as the light direction on spot and directional lights.
  49608. */
  49609. set: function (value) {
  49610. this._setDirection(value);
  49611. },
  49612. enumerable: true,
  49613. configurable: true
  49614. });
  49615. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49616. /**
  49617. * Gets the shadow projection clipping minimum z value.
  49618. */
  49619. get: function () {
  49620. return this._shadowMinZ;
  49621. },
  49622. /**
  49623. * Sets the shadow projection clipping minimum z value.
  49624. */
  49625. set: function (value) {
  49626. this._shadowMinZ = value;
  49627. this.forceProjectionMatrixCompute();
  49628. },
  49629. enumerable: true,
  49630. configurable: true
  49631. });
  49632. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49633. /**
  49634. * Sets the shadow projection clipping maximum z value.
  49635. */
  49636. get: function () {
  49637. return this._shadowMaxZ;
  49638. },
  49639. /**
  49640. * Gets the shadow projection clipping maximum z value.
  49641. */
  49642. set: function (value) {
  49643. this._shadowMaxZ = value;
  49644. this.forceProjectionMatrixCompute();
  49645. },
  49646. enumerable: true,
  49647. configurable: true
  49648. });
  49649. /**
  49650. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49651. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49652. */
  49653. ShadowLight.prototype.computeTransformedInformation = function () {
  49654. if (this.parent && this.parent.getWorldMatrix) {
  49655. if (!this.transformedPosition) {
  49656. this.transformedPosition = BABYLON.Vector3.Zero();
  49657. }
  49658. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49659. // In case the direction is present.
  49660. if (this.direction) {
  49661. if (!this.transformedDirection) {
  49662. this.transformedDirection = BABYLON.Vector3.Zero();
  49663. }
  49664. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49665. }
  49666. return true;
  49667. }
  49668. return false;
  49669. };
  49670. /**
  49671. * Return the depth scale used for the shadow map.
  49672. * @returns the depth scale.
  49673. */
  49674. ShadowLight.prototype.getDepthScale = function () {
  49675. return 50.0;
  49676. };
  49677. /**
  49678. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49679. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49680. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49681. */
  49682. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49683. return this.transformedDirection ? this.transformedDirection : this.direction;
  49684. };
  49685. /**
  49686. * Returns the ShadowLight absolute position in the World.
  49687. * @returns the position vector in world space
  49688. */
  49689. ShadowLight.prototype.getAbsolutePosition = function () {
  49690. return this.transformedPosition ? this.transformedPosition : this.position;
  49691. };
  49692. /**
  49693. * Sets the ShadowLight direction toward the passed target.
  49694. * @param target The point tot target in local space
  49695. * @returns the updated ShadowLight direction
  49696. */
  49697. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49698. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49699. return this.direction;
  49700. };
  49701. /**
  49702. * Returns the light rotation in euler definition.
  49703. * @returns the x y z rotation in local space.
  49704. */
  49705. ShadowLight.prototype.getRotation = function () {
  49706. this.direction.normalize();
  49707. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49708. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49709. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49710. };
  49711. /**
  49712. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49713. * @returns true if a cube texture needs to be use
  49714. */
  49715. ShadowLight.prototype.needCube = function () {
  49716. return false;
  49717. };
  49718. /**
  49719. * Detects if the projection matrix requires to be recomputed this frame.
  49720. * @returns true if it requires to be recomputed otherwise, false.
  49721. */
  49722. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49723. return this._needProjectionMatrixCompute;
  49724. };
  49725. /**
  49726. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49727. */
  49728. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49729. this._needProjectionMatrixCompute = true;
  49730. };
  49731. /**
  49732. * Get the world matrix of the sahdow lights.
  49733. * @hidden Internal Use Only
  49734. */
  49735. ShadowLight.prototype._getWorldMatrix = function () {
  49736. if (!this._worldMatrix) {
  49737. this._worldMatrix = BABYLON.Matrix.Identity();
  49738. }
  49739. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49740. return this._worldMatrix;
  49741. };
  49742. /**
  49743. * Gets the minZ used for shadow according to both the scene and the light.
  49744. * @param activeCamera The camera we are returning the min for
  49745. * @returns the depth min z
  49746. */
  49747. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49748. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49749. };
  49750. /**
  49751. * Gets the maxZ used for shadow according to both the scene and the light.
  49752. * @param activeCamera The camera we are returning the max for
  49753. * @returns the depth max z
  49754. */
  49755. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49756. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49757. };
  49758. /**
  49759. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49760. * @param matrix The materix to updated with the projection information
  49761. * @param viewMatrix The transform matrix of the light
  49762. * @param renderList The list of mesh to render in the map
  49763. * @returns The current light
  49764. */
  49765. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49766. if (this.customProjectionMatrixBuilder) {
  49767. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49768. }
  49769. else {
  49770. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49771. }
  49772. return this;
  49773. };
  49774. __decorate([
  49775. BABYLON.serializeAsVector3()
  49776. ], ShadowLight.prototype, "position", null);
  49777. __decorate([
  49778. BABYLON.serializeAsVector3()
  49779. ], ShadowLight.prototype, "direction", null);
  49780. __decorate([
  49781. BABYLON.serialize()
  49782. ], ShadowLight.prototype, "shadowMinZ", null);
  49783. __decorate([
  49784. BABYLON.serialize()
  49785. ], ShadowLight.prototype, "shadowMaxZ", null);
  49786. return ShadowLight;
  49787. }(BABYLON.Light));
  49788. BABYLON.ShadowLight = ShadowLight;
  49789. })(BABYLON || (BABYLON = {}));
  49790. //# sourceMappingURL=babylon.shadowLight.js.map
  49791. var BABYLON;
  49792. (function (BABYLON) {
  49793. /**
  49794. * A point light is a light defined by an unique point in world space.
  49795. * The light is emitted in every direction from this point.
  49796. * A good example of a point light is a standard light bulb.
  49797. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49798. */
  49799. var PointLight = /** @class */ (function (_super) {
  49800. __extends(PointLight, _super);
  49801. /**
  49802. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49803. * A PointLight emits the light in every direction.
  49804. * It can cast shadows.
  49805. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49806. * ```javascript
  49807. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49808. * ```
  49809. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49810. * @param name The light friendly name
  49811. * @param position The position of the point light in the scene
  49812. * @param scene The scene the lights belongs to
  49813. */
  49814. function PointLight(name, position, scene) {
  49815. var _this = _super.call(this, name, scene) || this;
  49816. _this._shadowAngle = Math.PI / 2;
  49817. _this.position = position;
  49818. return _this;
  49819. }
  49820. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49821. /**
  49822. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49823. * This specifies what angle the shadow will use to be created.
  49824. *
  49825. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49826. */
  49827. get: function () {
  49828. return this._shadowAngle;
  49829. },
  49830. /**
  49831. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49832. * This specifies what angle the shadow will use to be created.
  49833. *
  49834. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49835. */
  49836. set: function (value) {
  49837. this._shadowAngle = value;
  49838. this.forceProjectionMatrixCompute();
  49839. },
  49840. enumerable: true,
  49841. configurable: true
  49842. });
  49843. Object.defineProperty(PointLight.prototype, "direction", {
  49844. /**
  49845. * Gets the direction if it has been set.
  49846. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49847. */
  49848. get: function () {
  49849. return this._direction;
  49850. },
  49851. /**
  49852. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49853. */
  49854. set: function (value) {
  49855. var previousNeedCube = this.needCube();
  49856. this._direction = value;
  49857. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49858. this._shadowGenerator.recreateShadowMap();
  49859. }
  49860. },
  49861. enumerable: true,
  49862. configurable: true
  49863. });
  49864. /**
  49865. * Returns the string "PointLight"
  49866. * @returns the class name
  49867. */
  49868. PointLight.prototype.getClassName = function () {
  49869. return "PointLight";
  49870. };
  49871. /**
  49872. * Returns the integer 0.
  49873. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49874. */
  49875. PointLight.prototype.getTypeID = function () {
  49876. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49877. };
  49878. /**
  49879. * Specifies wether or not the shadowmap should be a cube texture.
  49880. * @returns true if the shadowmap needs to be a cube texture.
  49881. */
  49882. PointLight.prototype.needCube = function () {
  49883. return !this.direction;
  49884. };
  49885. /**
  49886. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49887. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49888. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49889. */
  49890. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49891. if (this.direction) {
  49892. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49893. }
  49894. else {
  49895. switch (faceIndex) {
  49896. case 0:
  49897. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49898. case 1:
  49899. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49900. case 2:
  49901. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49902. case 3:
  49903. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49904. case 4:
  49905. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49906. case 5:
  49907. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49908. }
  49909. }
  49910. return BABYLON.Vector3.Zero();
  49911. };
  49912. /**
  49913. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49914. * - fov = PI / 2
  49915. * - aspect ratio : 1.0
  49916. * - z-near and far equal to the active camera minZ and maxZ.
  49917. * Returns the PointLight.
  49918. */
  49919. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49920. var activeCamera = this.getScene().activeCamera;
  49921. if (!activeCamera) {
  49922. return;
  49923. }
  49924. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49925. };
  49926. PointLight.prototype._buildUniformLayout = function () {
  49927. this._uniformBuffer.addUniform("vLightData", 4);
  49928. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49929. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49930. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49931. this._uniformBuffer.addUniform("depthValues", 2);
  49932. this._uniformBuffer.create();
  49933. };
  49934. /**
  49935. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49936. * @param effect The effect to update
  49937. * @param lightIndex The index of the light in the effect to update
  49938. * @returns The point light
  49939. */
  49940. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49941. if (this.computeTransformedInformation()) {
  49942. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49943. return this;
  49944. }
  49945. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49946. return this;
  49947. };
  49948. __decorate([
  49949. BABYLON.serialize()
  49950. ], PointLight.prototype, "shadowAngle", null);
  49951. return PointLight;
  49952. }(BABYLON.ShadowLight));
  49953. BABYLON.PointLight = PointLight;
  49954. })(BABYLON || (BABYLON = {}));
  49955. //# sourceMappingURL=babylon.pointLight.js.map
  49956. var BABYLON;
  49957. (function (BABYLON) {
  49958. /**
  49959. * A directional light is defined by a direction (what a surprise!).
  49960. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49961. * An example of a directional light is when a distance planet is lit by the apparently parallel lines of light from its sun. Light in a downward direction will light the top of an object.
  49962. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49963. */
  49964. var DirectionalLight = /** @class */ (function (_super) {
  49965. __extends(DirectionalLight, _super);
  49966. /**
  49967. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49968. * The directional light is emitted from everywhere in the given direction.
  49969. * It can cast shawdows.
  49970. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49971. * @param name The friendly name of the light
  49972. * @param direction The direction of the light
  49973. * @param scene The scene the light belongs to
  49974. */
  49975. function DirectionalLight(name, direction, scene) {
  49976. var _this = _super.call(this, name, scene) || this;
  49977. _this._shadowFrustumSize = 0;
  49978. _this._shadowOrthoScale = 0.1;
  49979. /**
  49980. * Automatically compute the projection matrix to best fit (including all the casters)
  49981. * on each frame.
  49982. */
  49983. _this.autoUpdateExtends = true;
  49984. // Cache
  49985. _this._orthoLeft = Number.MAX_VALUE;
  49986. _this._orthoRight = Number.MIN_VALUE;
  49987. _this._orthoTop = Number.MIN_VALUE;
  49988. _this._orthoBottom = Number.MAX_VALUE;
  49989. _this.position = direction.scale(-1.0);
  49990. _this.direction = direction;
  49991. return _this;
  49992. }
  49993. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49994. /**
  49995. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49996. */
  49997. get: function () {
  49998. return this._shadowFrustumSize;
  49999. },
  50000. /**
  50001. * Specifies a fix frustum size for the shadow generation.
  50002. */
  50003. set: function (value) {
  50004. this._shadowFrustumSize = value;
  50005. this.forceProjectionMatrixCompute();
  50006. },
  50007. enumerable: true,
  50008. configurable: true
  50009. });
  50010. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  50011. /**
  50012. * Gets the shadow projection scale against the optimal computed one.
  50013. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50014. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50015. */
  50016. get: function () {
  50017. return this._shadowOrthoScale;
  50018. },
  50019. /**
  50020. * Sets the shadow projection scale against the optimal computed one.
  50021. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50022. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50023. */
  50024. set: function (value) {
  50025. this._shadowOrthoScale = value;
  50026. this.forceProjectionMatrixCompute();
  50027. },
  50028. enumerable: true,
  50029. configurable: true
  50030. });
  50031. /**
  50032. * Returns the string "DirectionalLight".
  50033. * @return The class name
  50034. */
  50035. DirectionalLight.prototype.getClassName = function () {
  50036. return "DirectionalLight";
  50037. };
  50038. /**
  50039. * Returns the integer 1.
  50040. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50041. */
  50042. DirectionalLight.prototype.getTypeID = function () {
  50043. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  50044. };
  50045. /**
  50046. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  50047. * Returns the DirectionalLight Shadow projection matrix.
  50048. */
  50049. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50050. if (this.shadowFrustumSize > 0) {
  50051. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  50052. }
  50053. else {
  50054. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  50055. }
  50056. };
  50057. /**
  50058. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  50059. * Returns the DirectionalLight Shadow projection matrix.
  50060. */
  50061. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  50062. var activeCamera = this.getScene().activeCamera;
  50063. if (!activeCamera) {
  50064. return;
  50065. }
  50066. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  50067. };
  50068. /**
  50069. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  50070. * Returns the DirectionalLight Shadow projection matrix.
  50071. */
  50072. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50073. var activeCamera = this.getScene().activeCamera;
  50074. if (!activeCamera) {
  50075. return;
  50076. }
  50077. // Check extends
  50078. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  50079. var tempVector3 = BABYLON.Vector3.Zero();
  50080. this._orthoLeft = Number.MAX_VALUE;
  50081. this._orthoRight = Number.MIN_VALUE;
  50082. this._orthoTop = Number.MIN_VALUE;
  50083. this._orthoBottom = Number.MAX_VALUE;
  50084. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  50085. var mesh = renderList[meshIndex];
  50086. if (!mesh) {
  50087. continue;
  50088. }
  50089. var boundingInfo = mesh.getBoundingInfo();
  50090. var boundingBox = boundingInfo.boundingBox;
  50091. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  50092. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  50093. if (tempVector3.x < this._orthoLeft)
  50094. this._orthoLeft = tempVector3.x;
  50095. if (tempVector3.y < this._orthoBottom)
  50096. this._orthoBottom = tempVector3.y;
  50097. if (tempVector3.x > this._orthoRight)
  50098. this._orthoRight = tempVector3.x;
  50099. if (tempVector3.y > this._orthoTop)
  50100. this._orthoTop = tempVector3.y;
  50101. }
  50102. }
  50103. }
  50104. var xOffset = this._orthoRight - this._orthoLeft;
  50105. var yOffset = this._orthoTop - this._orthoBottom;
  50106. BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  50107. };
  50108. DirectionalLight.prototype._buildUniformLayout = function () {
  50109. this._uniformBuffer.addUniform("vLightData", 4);
  50110. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50111. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50112. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50113. this._uniformBuffer.addUniform("depthValues", 2);
  50114. this._uniformBuffer.create();
  50115. };
  50116. /**
  50117. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  50118. * @param effect The effect to update
  50119. * @param lightIndex The index of the light in the effect to update
  50120. * @returns The directional light
  50121. */
  50122. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  50123. if (this.computeTransformedInformation()) {
  50124. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  50125. return this;
  50126. }
  50127. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  50128. return this;
  50129. };
  50130. /**
  50131. * Gets the minZ used for shadow according to both the scene and the light.
  50132. *
  50133. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50134. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50135. * @param activeCamera The camera we are returning the min for
  50136. * @returns the depth min z
  50137. */
  50138. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  50139. return 1;
  50140. };
  50141. /**
  50142. * Gets the maxZ used for shadow according to both the scene and the light.
  50143. *
  50144. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50145. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50146. * @param activeCamera The camera we are returning the max for
  50147. * @returns the depth max z
  50148. */
  50149. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  50150. return 1;
  50151. };
  50152. __decorate([
  50153. BABYLON.serialize()
  50154. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  50155. __decorate([
  50156. BABYLON.serialize()
  50157. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  50158. __decorate([
  50159. BABYLON.serialize()
  50160. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  50161. return DirectionalLight;
  50162. }(BABYLON.ShadowLight));
  50163. BABYLON.DirectionalLight = DirectionalLight;
  50164. })(BABYLON || (BABYLON = {}));
  50165. //# sourceMappingURL=babylon.directionalLight.js.map
  50166. var BABYLON;
  50167. (function (BABYLON) {
  50168. /**
  50169. * A spot light is defined by a position, a direction, an angle, and an exponent.
  50170. * These values define a cone of light starting from the position, emitting toward the direction.
  50171. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  50172. * and the exponent defines the speed of the decay of the light with distance (reach).
  50173. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50174. */
  50175. var SpotLight = /** @class */ (function (_super) {
  50176. __extends(SpotLight, _super);
  50177. /**
  50178. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  50179. * It can cast shadows.
  50180. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50181. * @param name The light friendly name
  50182. * @param position The position of the spot light in the scene
  50183. * @param direction The direction of the light in the scene
  50184. * @param angle The cone angle of the light in Radians
  50185. * @param exponent The light decay speed with the distance from the emission spot
  50186. * @param scene The scene the lights belongs to
  50187. */
  50188. function SpotLight(name, position, direction, angle, exponent, scene) {
  50189. var _this = _super.call(this, name, scene) || this;
  50190. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  50191. _this._projectionTextureLightNear = 1e-6;
  50192. _this._projectionTextureLightFar = 1000.0;
  50193. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  50194. _this._projectionTextureViewLightDirty = true;
  50195. _this._projectionTextureProjectionLightDirty = true;
  50196. _this._projectionTextureDirty = true;
  50197. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  50198. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  50199. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  50200. _this._projectionTextureScalingMatrix = BABYLON.Matrix.FromValues(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);
  50201. _this.position = position;
  50202. _this.direction = direction;
  50203. _this.angle = angle;
  50204. _this.exponent = exponent;
  50205. return _this;
  50206. }
  50207. Object.defineProperty(SpotLight.prototype, "angle", {
  50208. /**
  50209. * Gets the cone angle of the spot light in Radians.
  50210. */
  50211. get: function () {
  50212. return this._angle;
  50213. },
  50214. /**
  50215. * Sets the cone angle of the spot light in Radians.
  50216. */
  50217. set: function (value) {
  50218. this._angle = value;
  50219. this._projectionTextureProjectionLightDirty = true;
  50220. this.forceProjectionMatrixCompute();
  50221. },
  50222. enumerable: true,
  50223. configurable: true
  50224. });
  50225. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  50226. /**
  50227. * Allows scaling the angle of the light for shadow generation only.
  50228. */
  50229. get: function () {
  50230. return this._shadowAngleScale;
  50231. },
  50232. /**
  50233. * Allows scaling the angle of the light for shadow generation only.
  50234. */
  50235. set: function (value) {
  50236. this._shadowAngleScale = value;
  50237. this.forceProjectionMatrixCompute();
  50238. },
  50239. enumerable: true,
  50240. configurable: true
  50241. });
  50242. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  50243. /**
  50244. * Allows reading the projecton texture
  50245. */
  50246. get: function () {
  50247. return this._projectionTextureMatrix;
  50248. },
  50249. enumerable: true,
  50250. configurable: true
  50251. });
  50252. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  50253. /**
  50254. * Gets the near clip of the Spotlight for texture projection.
  50255. */
  50256. get: function () {
  50257. return this._projectionTextureLightNear;
  50258. },
  50259. /**
  50260. * Sets the near clip of the Spotlight for texture projection.
  50261. */
  50262. set: function (value) {
  50263. this._projectionTextureLightNear = value;
  50264. this._projectionTextureProjectionLightDirty = true;
  50265. },
  50266. enumerable: true,
  50267. configurable: true
  50268. });
  50269. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  50270. /**
  50271. * Gets the far clip of the Spotlight for texture projection.
  50272. */
  50273. get: function () {
  50274. return this._projectionTextureLightFar;
  50275. },
  50276. /**
  50277. * Sets the far clip of the Spotlight for texture projection.
  50278. */
  50279. set: function (value) {
  50280. this._projectionTextureLightFar = value;
  50281. this._projectionTextureProjectionLightDirty = true;
  50282. },
  50283. enumerable: true,
  50284. configurable: true
  50285. });
  50286. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  50287. /**
  50288. * Gets the Up vector of the Spotlight for texture projection.
  50289. */
  50290. get: function () {
  50291. return this._projectionTextureUpDirection;
  50292. },
  50293. /**
  50294. * Sets the Up vector of the Spotlight for texture projection.
  50295. */
  50296. set: function (value) {
  50297. this._projectionTextureUpDirection = value;
  50298. this._projectionTextureProjectionLightDirty = true;
  50299. },
  50300. enumerable: true,
  50301. configurable: true
  50302. });
  50303. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50304. /**
  50305. * Gets the projection texture of the light.
  50306. */
  50307. get: function () {
  50308. return this._projectionTexture;
  50309. },
  50310. /**
  50311. * Sets the projection texture of the light.
  50312. */
  50313. set: function (value) {
  50314. this._projectionTexture = value;
  50315. this._projectionTextureDirty = true;
  50316. },
  50317. enumerable: true,
  50318. configurable: true
  50319. });
  50320. /**
  50321. * Returns the string "SpotLight".
  50322. * @returns the class name
  50323. */
  50324. SpotLight.prototype.getClassName = function () {
  50325. return "SpotLight";
  50326. };
  50327. /**
  50328. * Returns the integer 2.
  50329. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50330. */
  50331. SpotLight.prototype.getTypeID = function () {
  50332. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50333. };
  50334. /**
  50335. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50336. */
  50337. SpotLight.prototype._setDirection = function (value) {
  50338. _super.prototype._setDirection.call(this, value);
  50339. this._projectionTextureViewLightDirty = true;
  50340. };
  50341. /**
  50342. * Overrides the position setter to recompute the projection texture view light Matrix.
  50343. */
  50344. SpotLight.prototype._setPosition = function (value) {
  50345. _super.prototype._setPosition.call(this, value);
  50346. this._projectionTextureViewLightDirty = true;
  50347. };
  50348. /**
  50349. * Sets the passed matrix "matrix" as perspective projection matrix for the shadows and the passed view matrix with the fov equal to the SpotLight angle and and aspect ratio of 1.0.
  50350. * Returns the SpotLight.
  50351. */
  50352. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50353. var activeCamera = this.getScene().activeCamera;
  50354. if (!activeCamera) {
  50355. return;
  50356. }
  50357. this._shadowAngleScale = this._shadowAngleScale || 1;
  50358. var angle = this._shadowAngleScale * this._angle;
  50359. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50360. };
  50361. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50362. this._projectionTextureViewLightDirty = false;
  50363. this._projectionTextureDirty = true;
  50364. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50365. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50366. };
  50367. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50368. this._projectionTextureProjectionLightDirty = false;
  50369. this._projectionTextureDirty = true;
  50370. var light_far = this.projectionTextureLightFar;
  50371. var light_near = this.projectionTextureLightNear;
  50372. var P = light_far / (light_far - light_near);
  50373. var Q = -P * light_near;
  50374. var S = 1.0 / Math.tan(this._angle / 2.0);
  50375. var A = 1.0;
  50376. BABYLON.Matrix.FromValuesToRef(S / A, 0.0, 0.0, 0.0, 0.0, S, 0.0, 0.0, 0.0, 0.0, P, 1.0, 0.0, 0.0, Q, 0.0, this._projectionTextureProjectionLightMatrix);
  50377. };
  50378. /**
  50379. * Main function for light texture projection matrix computing.
  50380. */
  50381. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50382. this._projectionTextureDirty = false;
  50383. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50384. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50385. };
  50386. SpotLight.prototype._buildUniformLayout = function () {
  50387. this._uniformBuffer.addUniform("vLightData", 4);
  50388. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50389. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50390. this._uniformBuffer.addUniform("vLightDirection", 3);
  50391. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50392. this._uniformBuffer.addUniform("depthValues", 2);
  50393. this._uniformBuffer.create();
  50394. };
  50395. /**
  50396. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50397. * @param effect The effect to update
  50398. * @param lightIndex The index of the light in the effect to update
  50399. * @returns The spot light
  50400. */
  50401. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50402. var normalizeDirection;
  50403. if (this.computeTransformedInformation()) {
  50404. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50405. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50406. }
  50407. else {
  50408. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50409. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50410. }
  50411. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  50412. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50413. if (this._projectionTextureViewLightDirty) {
  50414. this._computeProjectionTextureViewLightMatrix();
  50415. }
  50416. if (this._projectionTextureProjectionLightDirty) {
  50417. this._computeProjectionTextureProjectionLightMatrix();
  50418. }
  50419. if (this._projectionTextureDirty) {
  50420. this._computeProjectionTextureMatrix();
  50421. }
  50422. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50423. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50424. }
  50425. return this;
  50426. };
  50427. /**
  50428. * Disposes the light and the associated resources.
  50429. */
  50430. SpotLight.prototype.dispose = function () {
  50431. _super.prototype.dispose.call(this);
  50432. if (this._projectionTexture) {
  50433. this._projectionTexture.dispose();
  50434. }
  50435. };
  50436. __decorate([
  50437. BABYLON.serialize()
  50438. ], SpotLight.prototype, "angle", null);
  50439. __decorate([
  50440. BABYLON.serialize()
  50441. ], SpotLight.prototype, "shadowAngleScale", null);
  50442. __decorate([
  50443. BABYLON.serialize()
  50444. ], SpotLight.prototype, "exponent", void 0);
  50445. __decorate([
  50446. BABYLON.serialize()
  50447. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50448. __decorate([
  50449. BABYLON.serialize()
  50450. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50451. __decorate([
  50452. BABYLON.serialize()
  50453. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50454. __decorate([
  50455. BABYLON.serializeAsTexture("projectedLightTexture")
  50456. ], SpotLight.prototype, "_projectionTexture", void 0);
  50457. return SpotLight;
  50458. }(BABYLON.ShadowLight));
  50459. BABYLON.SpotLight = SpotLight;
  50460. })(BABYLON || (BABYLON = {}));
  50461. //# sourceMappingURL=babylon.spotLight.js.map
  50462. var BABYLON;
  50463. (function (BABYLON) {
  50464. /**
  50465. * Class used to override all child animations of a given target
  50466. */
  50467. var AnimationPropertiesOverride = /** @class */ (function () {
  50468. function AnimationPropertiesOverride() {
  50469. /**
  50470. * Gets or sets a value indicating if animation blending must be used
  50471. */
  50472. this.enableBlending = false;
  50473. /**
  50474. * Gets or sets the blending speed to use when enableBlending is true
  50475. */
  50476. this.blendingSpeed = 0.01;
  50477. /**
  50478. * Gets or sets the default loop mode to use
  50479. */
  50480. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50481. }
  50482. return AnimationPropertiesOverride;
  50483. }());
  50484. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50485. })(BABYLON || (BABYLON = {}));
  50486. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50487. var BABYLON;
  50488. (function (BABYLON) {
  50489. /**
  50490. * Represents the range of an animation
  50491. */
  50492. var AnimationRange = /** @class */ (function () {
  50493. /**
  50494. * Initializes the range of an animation
  50495. * @param name The name of the animation range
  50496. * @param from The starting frame of the animation
  50497. * @param to The ending frame of the animation
  50498. */
  50499. function AnimationRange(
  50500. /**The name of the animation range**/
  50501. name,
  50502. /**The starting frame of the animation */
  50503. from,
  50504. /**The ending frame of the animation*/
  50505. to) {
  50506. this.name = name;
  50507. this.from = from;
  50508. this.to = to;
  50509. }
  50510. /**
  50511. * Makes a copy of the animation range
  50512. * @returns A copy of the animation range
  50513. */
  50514. AnimationRange.prototype.clone = function () {
  50515. return new AnimationRange(this.name, this.from, this.to);
  50516. };
  50517. return AnimationRange;
  50518. }());
  50519. BABYLON.AnimationRange = AnimationRange;
  50520. /**
  50521. * Composed of a frame, and an action function
  50522. */
  50523. var AnimationEvent = /** @class */ (function () {
  50524. /**
  50525. * Initializes the animation event
  50526. * @param frame The frame for which the event is triggered
  50527. * @param action The event to perform when triggered
  50528. * @param onlyOnce Specifies if the event should be triggered only once
  50529. */
  50530. function AnimationEvent(
  50531. /** The frame for which the event is triggered **/
  50532. frame,
  50533. /** The event to perform when triggered **/
  50534. action,
  50535. /** Specifies if the event should be triggered only once**/
  50536. onlyOnce) {
  50537. this.frame = frame;
  50538. this.action = action;
  50539. this.onlyOnce = onlyOnce;
  50540. /**
  50541. * Specifies if the animation event is done
  50542. */
  50543. this.isDone = false;
  50544. }
  50545. /** @hidden */
  50546. AnimationEvent.prototype._clone = function () {
  50547. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  50548. };
  50549. return AnimationEvent;
  50550. }());
  50551. BABYLON.AnimationEvent = AnimationEvent;
  50552. /**
  50553. * A cursor which tracks a point on a path
  50554. */
  50555. var PathCursor = /** @class */ (function () {
  50556. /**
  50557. * Initializes the path cursor
  50558. * @param path The path to track
  50559. */
  50560. function PathCursor(path) {
  50561. this.path = path;
  50562. /**
  50563. * Stores path cursor callbacks for when an onchange event is triggered
  50564. */
  50565. this._onchange = new Array();
  50566. /**
  50567. * The value of the path cursor
  50568. */
  50569. this.value = 0;
  50570. /**
  50571. * The animation array of the path cursor
  50572. */
  50573. this.animations = new Array();
  50574. }
  50575. /**
  50576. * Gets the cursor point on the path
  50577. * @returns A point on the path cursor at the cursor location
  50578. */
  50579. PathCursor.prototype.getPoint = function () {
  50580. var point = this.path.getPointAtLengthPosition(this.value);
  50581. return new BABYLON.Vector3(point.x, 0, point.y);
  50582. };
  50583. /**
  50584. * Moves the cursor ahead by the step amount
  50585. * @param step The amount to move the cursor forward
  50586. * @returns This path cursor
  50587. */
  50588. PathCursor.prototype.moveAhead = function (step) {
  50589. if (step === void 0) { step = 0.002; }
  50590. this.move(step);
  50591. return this;
  50592. };
  50593. /**
  50594. * Moves the cursor behind by the step amount
  50595. * @param step The amount to move the cursor back
  50596. * @returns This path cursor
  50597. */
  50598. PathCursor.prototype.moveBack = function (step) {
  50599. if (step === void 0) { step = 0.002; }
  50600. this.move(-step);
  50601. return this;
  50602. };
  50603. /**
  50604. * Moves the cursor by the step amount
  50605. * If the step amount is greater than one, an exception is thrown
  50606. * @param step The amount to move the cursor
  50607. * @returns This path cursor
  50608. */
  50609. PathCursor.prototype.move = function (step) {
  50610. if (Math.abs(step) > 1) {
  50611. throw "step size should be less than 1.";
  50612. }
  50613. this.value += step;
  50614. this.ensureLimits();
  50615. this.raiseOnChange();
  50616. return this;
  50617. };
  50618. /**
  50619. * Ensures that the value is limited between zero and one
  50620. * @returns This path cursor
  50621. */
  50622. PathCursor.prototype.ensureLimits = function () {
  50623. while (this.value > 1) {
  50624. this.value -= 1;
  50625. }
  50626. while (this.value < 0) {
  50627. this.value += 1;
  50628. }
  50629. return this;
  50630. };
  50631. /**
  50632. * Runs onchange callbacks on change (used by the animation engine)
  50633. * @returns This path cursor
  50634. */
  50635. PathCursor.prototype.raiseOnChange = function () {
  50636. var _this = this;
  50637. this._onchange.forEach(function (f) { return f(_this); });
  50638. return this;
  50639. };
  50640. /**
  50641. * Executes a function on change
  50642. * @param f A path cursor onchange callback
  50643. * @returns This path cursor
  50644. */
  50645. PathCursor.prototype.onchange = function (f) {
  50646. this._onchange.push(f);
  50647. return this;
  50648. };
  50649. return PathCursor;
  50650. }());
  50651. BABYLON.PathCursor = PathCursor;
  50652. /**
  50653. * Enum for the animation key frame interpolation type
  50654. */
  50655. var AnimationKeyInterpolation;
  50656. (function (AnimationKeyInterpolation) {
  50657. /**
  50658. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50659. */
  50660. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50661. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50662. /**
  50663. * Class used to store any kind of animation
  50664. */
  50665. var Animation = /** @class */ (function () {
  50666. /**
  50667. * Initializes the animation
  50668. * @param name Name of the animation
  50669. * @param targetProperty Property to animate
  50670. * @param framePerSecond The frames per second of the animation
  50671. * @param dataType The data type of the animation
  50672. * @param loopMode The loop mode of the animation
  50673. * @param enableBlendings Specifies if blending should be enabled
  50674. */
  50675. function Animation(
  50676. /**Name of the animation */
  50677. name,
  50678. /**Property to animate */
  50679. targetProperty,
  50680. /**The frames per second of the animation */
  50681. framePerSecond,
  50682. /**The data type of the animation */
  50683. dataType,
  50684. /**The loop mode of the animation */
  50685. loopMode,
  50686. /**Specifies if blending should be enabled */
  50687. enableBlending) {
  50688. this.name = name;
  50689. this.targetProperty = targetProperty;
  50690. this.framePerSecond = framePerSecond;
  50691. this.dataType = dataType;
  50692. this.loopMode = loopMode;
  50693. this.enableBlending = enableBlending;
  50694. /**
  50695. * @hidden Internal use only
  50696. */
  50697. this._runtimeAnimations = new Array();
  50698. /**
  50699. * The set of event that will be linked to this animation
  50700. */
  50701. this._events = new Array();
  50702. /**
  50703. * Stores the blending speed of the animation
  50704. */
  50705. this.blendingSpeed = 0.01;
  50706. /**
  50707. * Stores the animation ranges for the animation
  50708. */
  50709. this._ranges = {};
  50710. this.targetPropertyPath = targetProperty.split(".");
  50711. this.dataType = dataType;
  50712. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50713. }
  50714. /**
  50715. * @hidden Internal use
  50716. */
  50717. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50718. var dataType = undefined;
  50719. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50720. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50721. }
  50722. else if (from instanceof BABYLON.Quaternion) {
  50723. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50724. }
  50725. else if (from instanceof BABYLON.Vector3) {
  50726. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50727. }
  50728. else if (from instanceof BABYLON.Vector2) {
  50729. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50730. }
  50731. else if (from instanceof BABYLON.Color3) {
  50732. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50733. }
  50734. else if (from instanceof BABYLON.Size) {
  50735. dataType = Animation.ANIMATIONTYPE_SIZE;
  50736. }
  50737. if (dataType == undefined) {
  50738. return null;
  50739. }
  50740. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50741. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50742. animation.setKeys(keys);
  50743. if (easingFunction !== undefined) {
  50744. animation.setEasingFunction(easingFunction);
  50745. }
  50746. return animation;
  50747. };
  50748. /**
  50749. * Sets up an animation
  50750. * @param property The property to animate
  50751. * @param animationType The animation type to apply
  50752. * @param framePerSecond The frames per second of the animation
  50753. * @param easingFunction The easing function used in the animation
  50754. * @returns The created animation
  50755. */
  50756. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50757. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50758. animation.setEasingFunction(easingFunction);
  50759. return animation;
  50760. };
  50761. /**
  50762. * Create and start an animation on a node
  50763. * @param name defines the name of the global animation that will be run on all nodes
  50764. * @param node defines the root node where the animation will take place
  50765. * @param targetProperty defines property to animate
  50766. * @param framePerSecond defines the number of frame per second yo use
  50767. * @param totalFrame defines the number of frames in total
  50768. * @param from defines the initial value
  50769. * @param to defines the final value
  50770. * @param loopMode defines which loop mode you want to use (off by default)
  50771. * @param easingFunction defines the easing function to use (linear by default)
  50772. * @param onAnimationEnd defines the callback to call when animation end
  50773. * @returns the animatable created for this animation
  50774. */
  50775. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50776. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50777. if (!animation) {
  50778. return null;
  50779. }
  50780. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50781. };
  50782. /**
  50783. * Create and start an animation on a node and its descendants
  50784. * @param name defines the name of the global animation that will be run on all nodes
  50785. * @param node defines the root node where the animation will take place
  50786. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used
  50787. * @param targetProperty defines property to animate
  50788. * @param framePerSecond defines the number of frame per second to use
  50789. * @param totalFrame defines the number of frames in total
  50790. * @param from defines the initial value
  50791. * @param to defines the final value
  50792. * @param loopMode defines which loop mode you want to use (off by default)
  50793. * @param easingFunction defines the easing function to use (linear by default)
  50794. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50795. * @returns the list of animatables created for all nodes
  50796. * @example https://www.babylonjs-playground.com/#MH0VLI
  50797. */
  50798. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50799. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50800. if (!animation) {
  50801. return null;
  50802. }
  50803. var scene = node.getScene();
  50804. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50805. };
  50806. /**
  50807. * Creates a new animation, merges it with the existing animations and starts it
  50808. * @param name Name of the animation
  50809. * @param node Node which contains the scene that begins the animations
  50810. * @param targetProperty Specifies which property to animate
  50811. * @param framePerSecond The frames per second of the animation
  50812. * @param totalFrame The total number of frames
  50813. * @param from The frame at the beginning of the animation
  50814. * @param to The frame at the end of the animation
  50815. * @param loopMode Specifies the loop mode of the animation
  50816. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50817. * @param onAnimationEnd Callback to run once the animation is complete
  50818. * @returns Nullable animation
  50819. */
  50820. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50821. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50822. if (!animation) {
  50823. return null;
  50824. }
  50825. node.animations.push(animation);
  50826. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50827. };
  50828. /**
  50829. * Transition property of an host to the target Value
  50830. * @param property The property to transition
  50831. * @param targetValue The target Value of the property
  50832. * @param host The object where the property to animate belongs
  50833. * @param scene Scene used to run the animation
  50834. * @param frameRate Framerate (in frame/s) to use
  50835. * @param transition The transition type we want to use
  50836. * @param duration The duration of the animation, in milliseconds
  50837. * @param onAnimationEnd Callback trigger at the end of the animation
  50838. * @returns Nullable animation
  50839. */
  50840. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50841. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50842. if (duration <= 0) {
  50843. host[property] = targetValue;
  50844. if (onAnimationEnd) {
  50845. onAnimationEnd();
  50846. }
  50847. return null;
  50848. }
  50849. var endFrame = frameRate * (duration / 1000);
  50850. transition.setKeys([{
  50851. frame: 0,
  50852. value: host[property].clone ? host[property].clone() : host[property]
  50853. },
  50854. {
  50855. frame: endFrame,
  50856. value: targetValue
  50857. }]);
  50858. if (!host.animations) {
  50859. host.animations = [];
  50860. }
  50861. host.animations.push(transition);
  50862. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50863. animation.onAnimationEnd = onAnimationEnd;
  50864. return animation;
  50865. };
  50866. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50867. /**
  50868. * Return the array of runtime animations currently using this animation
  50869. */
  50870. get: function () {
  50871. return this._runtimeAnimations;
  50872. },
  50873. enumerable: true,
  50874. configurable: true
  50875. });
  50876. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50877. /**
  50878. * Specifies if any of the runtime animations are currently running
  50879. */
  50880. get: function () {
  50881. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50882. var runtimeAnimation = _a[_i];
  50883. if (!runtimeAnimation.isStopped) {
  50884. return true;
  50885. }
  50886. }
  50887. return false;
  50888. },
  50889. enumerable: true,
  50890. configurable: true
  50891. });
  50892. // Methods
  50893. /**
  50894. * Converts the animation to a string
  50895. * @param fullDetails support for multiple levels of logging within scene loading
  50896. * @returns String form of the animation
  50897. */
  50898. Animation.prototype.toString = function (fullDetails) {
  50899. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50900. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50901. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50902. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50903. if (fullDetails) {
  50904. ret += ", Ranges: {";
  50905. var first = true;
  50906. for (var name in this._ranges) {
  50907. if (first) {
  50908. ret += ", ";
  50909. first = false;
  50910. }
  50911. ret += name;
  50912. }
  50913. ret += "}";
  50914. }
  50915. return ret;
  50916. };
  50917. /**
  50918. * Add an event to this animation
  50919. * @param event Event to add
  50920. */
  50921. Animation.prototype.addEvent = function (event) {
  50922. this._events.push(event);
  50923. };
  50924. /**
  50925. * Remove all events found at the given frame
  50926. * @param frame The frame to remove events from
  50927. */
  50928. Animation.prototype.removeEvents = function (frame) {
  50929. for (var index = 0; index < this._events.length; index++) {
  50930. if (this._events[index].frame === frame) {
  50931. this._events.splice(index, 1);
  50932. index--;
  50933. }
  50934. }
  50935. };
  50936. /**
  50937. * Retrieves all the events from the animation
  50938. * @returns Events from the animation
  50939. */
  50940. Animation.prototype.getEvents = function () {
  50941. return this._events;
  50942. };
  50943. /**
  50944. * Creates an animation range
  50945. * @param name Name of the animation range
  50946. * @param from Starting frame of the animation range
  50947. * @param to Ending frame of the animation
  50948. */
  50949. Animation.prototype.createRange = function (name, from, to) {
  50950. // check name not already in use; could happen for bones after serialized
  50951. if (!this._ranges[name]) {
  50952. this._ranges[name] = new AnimationRange(name, from, to);
  50953. }
  50954. };
  50955. /**
  50956. * Deletes an animation range by name
  50957. * @param name Name of the animation range to delete
  50958. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50959. */
  50960. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50961. if (deleteFrames === void 0) { deleteFrames = true; }
  50962. var range = this._ranges[name];
  50963. if (!range) {
  50964. return;
  50965. }
  50966. if (deleteFrames) {
  50967. var from = range.from;
  50968. var to = range.to;
  50969. // this loop MUST go high to low for multiple splices to work
  50970. for (var key = this._keys.length - 1; key >= 0; key--) {
  50971. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50972. this._keys.splice(key, 1);
  50973. }
  50974. }
  50975. }
  50976. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50977. };
  50978. /**
  50979. * Gets the animation range by name, or null if not defined
  50980. * @param name Name of the animation range
  50981. * @returns Nullable animation range
  50982. */
  50983. Animation.prototype.getRange = function (name) {
  50984. return this._ranges[name];
  50985. };
  50986. /**
  50987. * Gets the key frames from the animation
  50988. * @returns The key frames of the animation
  50989. */
  50990. Animation.prototype.getKeys = function () {
  50991. return this._keys;
  50992. };
  50993. /**
  50994. * Gets the highest frame rate of the animation
  50995. * @returns Highest frame rate of the animation
  50996. */
  50997. Animation.prototype.getHighestFrame = function () {
  50998. var ret = 0;
  50999. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  51000. if (ret < this._keys[key].frame) {
  51001. ret = this._keys[key].frame;
  51002. }
  51003. }
  51004. return ret;
  51005. };
  51006. /**
  51007. * Gets the easing function of the animation
  51008. * @returns Easing function of the animation
  51009. */
  51010. Animation.prototype.getEasingFunction = function () {
  51011. return this._easingFunction;
  51012. };
  51013. /**
  51014. * Sets the easing function of the animation
  51015. * @param easingFunction A custom mathematical formula for animation
  51016. */
  51017. Animation.prototype.setEasingFunction = function (easingFunction) {
  51018. this._easingFunction = easingFunction;
  51019. };
  51020. /**
  51021. * Interpolates a scalar linearly
  51022. * @param startValue Start value of the animation curve
  51023. * @param endValue End value of the animation curve
  51024. * @param gradient Scalar amount to interpolate
  51025. * @returns Interpolated scalar value
  51026. */
  51027. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  51028. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  51029. };
  51030. /**
  51031. * Interpolates a scalar cubically
  51032. * @param startValue Start value of the animation curve
  51033. * @param outTangent End tangent of the animation
  51034. * @param endValue End value of the animation curve
  51035. * @param inTangent Start tangent of the animation curve
  51036. * @param gradient Scalar amount to interpolate
  51037. * @returns Interpolated scalar value
  51038. */
  51039. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51040. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51041. };
  51042. /**
  51043. * Interpolates a quaternion using a spherical linear interpolation
  51044. * @param startValue Start value of the animation curve
  51045. * @param endValue End value of the animation curve
  51046. * @param gradient Scalar amount to interpolate
  51047. * @returns Interpolated quaternion value
  51048. */
  51049. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  51050. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  51051. };
  51052. /**
  51053. * Interpolates a quaternion cubically
  51054. * @param startValue Start value of the animation curve
  51055. * @param outTangent End tangent of the animation curve
  51056. * @param endValue End value of the animation curve
  51057. * @param inTangent Start tangent of the animation curve
  51058. * @param gradient Scalar amount to interpolate
  51059. * @returns Interpolated quaternion value
  51060. */
  51061. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51062. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  51063. };
  51064. /**
  51065. * Interpolates a Vector3 linearl
  51066. * @param startValue Start value of the animation curve
  51067. * @param endValue End value of the animation curve
  51068. * @param gradient Scalar amount to interpolate
  51069. * @returns Interpolated scalar value
  51070. */
  51071. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  51072. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  51073. };
  51074. /**
  51075. * Interpolates a Vector3 cubically
  51076. * @param startValue Start value of the animation curve
  51077. * @param outTangent End tangent of the animation
  51078. * @param endValue End value of the animation curve
  51079. * @param inTangent Start tangent of the animation curve
  51080. * @param gradient Scalar amount to interpolate
  51081. * @returns InterpolatedVector3 value
  51082. */
  51083. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51084. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51085. };
  51086. /**
  51087. * Interpolates a Vector2 linearly
  51088. * @param startValue Start value of the animation curve
  51089. * @param endValue End value of the animation curve
  51090. * @param gradient Scalar amount to interpolate
  51091. * @returns Interpolated Vector2 value
  51092. */
  51093. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  51094. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  51095. };
  51096. /**
  51097. * Interpolates a Vector2 cubically
  51098. * @param startValue Start value of the animation curve
  51099. * @param outTangent End tangent of the animation
  51100. * @param endValue End value of the animation curve
  51101. * @param inTangent Start tangent of the animation curve
  51102. * @param gradient Scalar amount to interpolate
  51103. * @returns Interpolated Vector2 value
  51104. */
  51105. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51106. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51107. };
  51108. /**
  51109. * Interpolates a size linearly
  51110. * @param startValue Start value of the animation curve
  51111. * @param endValue End value of the animation curve
  51112. * @param gradient Scalar amount to interpolate
  51113. * @returns Interpolated Size value
  51114. */
  51115. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  51116. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  51117. };
  51118. /**
  51119. * Interpolates a Color3 linearly
  51120. * @param startValue Start value of the animation curve
  51121. * @param endValue End value of the animation curve
  51122. * @param gradient Scalar amount to interpolate
  51123. * @returns Interpolated Color3 value
  51124. */
  51125. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  51126. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  51127. };
  51128. /**
  51129. * @hidden Internal use only
  51130. */
  51131. Animation.prototype._getKeyValue = function (value) {
  51132. if (typeof value === "function") {
  51133. return value();
  51134. }
  51135. return value;
  51136. };
  51137. /**
  51138. * @hidden Internal use only
  51139. */
  51140. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  51141. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  51142. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  51143. }
  51144. var keys = this.getKeys();
  51145. // Try to get a hash to find the right key
  51146. var startKeyIndex = Math.max(0, Math.min(keys.length - 1, Math.floor(keys.length * (currentFrame - keys[0].frame) / (keys[keys.length - 1].frame - keys[0].frame)) - 1));
  51147. if (keys[startKeyIndex].frame >= currentFrame) {
  51148. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  51149. startKeyIndex--;
  51150. }
  51151. }
  51152. for (var key = startKeyIndex; key < keys.length; key++) {
  51153. var endKey = keys[key + 1];
  51154. if (endKey.frame >= currentFrame) {
  51155. var startKey = keys[key];
  51156. var startValue = this._getKeyValue(startKey.value);
  51157. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  51158. return startValue;
  51159. }
  51160. var endValue = this._getKeyValue(endKey.value);
  51161. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  51162. var frameDelta = endKey.frame - startKey.frame;
  51163. // gradient : percent of currentFrame between the frame inf and the frame sup
  51164. var gradient = (currentFrame - startKey.frame) / frameDelta;
  51165. // check for easingFunction and correction of gradient
  51166. var easingFunction = this.getEasingFunction();
  51167. if (easingFunction != null) {
  51168. gradient = easingFunction.ease(gradient);
  51169. }
  51170. switch (this.dataType) {
  51171. // Float
  51172. case Animation.ANIMATIONTYPE_FLOAT:
  51173. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  51174. switch (loopMode) {
  51175. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51176. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51177. return floatValue;
  51178. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51179. return offsetValue * repeatCount + floatValue;
  51180. }
  51181. break;
  51182. // Quaternion
  51183. case Animation.ANIMATIONTYPE_QUATERNION:
  51184. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  51185. switch (loopMode) {
  51186. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51187. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51188. return quatValue;
  51189. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51190. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  51191. }
  51192. return quatValue;
  51193. // Vector3
  51194. case Animation.ANIMATIONTYPE_VECTOR3:
  51195. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  51196. switch (loopMode) {
  51197. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51198. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51199. return vec3Value;
  51200. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51201. return vec3Value.add(offsetValue.scale(repeatCount));
  51202. }
  51203. // Vector2
  51204. case Animation.ANIMATIONTYPE_VECTOR2:
  51205. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  51206. switch (loopMode) {
  51207. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51208. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51209. return vec2Value;
  51210. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51211. return vec2Value.add(offsetValue.scale(repeatCount));
  51212. }
  51213. // Size
  51214. case Animation.ANIMATIONTYPE_SIZE:
  51215. switch (loopMode) {
  51216. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51217. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51218. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  51219. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51220. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51221. }
  51222. // Color3
  51223. case Animation.ANIMATIONTYPE_COLOR3:
  51224. switch (loopMode) {
  51225. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51226. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51227. return this.color3InterpolateFunction(startValue, endValue, gradient);
  51228. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51229. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51230. }
  51231. // Matrix
  51232. case Animation.ANIMATIONTYPE_MATRIX:
  51233. switch (loopMode) {
  51234. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51235. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51236. if (Animation.AllowMatricesInterpolation) {
  51237. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  51238. }
  51239. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51240. return startValue;
  51241. }
  51242. default:
  51243. break;
  51244. }
  51245. break;
  51246. }
  51247. }
  51248. return this._getKeyValue(keys[keys.length - 1].value);
  51249. };
  51250. /**
  51251. * Defines the function to use to interpolate matrices
  51252. * @param startValue defines the start matrix
  51253. * @param endValue defines the end matrix
  51254. * @param gradient defines the gradient between both matrices
  51255. * @param result defines an optional target matrix where to store the interpolation
  51256. * @returns the interpolated matrix
  51257. */
  51258. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  51259. if (Animation.AllowMatrixDecomposeForInterpolation) {
  51260. if (result) {
  51261. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  51262. return result;
  51263. }
  51264. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  51265. }
  51266. if (result) {
  51267. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  51268. return result;
  51269. }
  51270. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  51271. };
  51272. /**
  51273. * Makes a copy of the animation
  51274. * @returns Cloned animation
  51275. */
  51276. Animation.prototype.clone = function () {
  51277. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  51278. clone.enableBlending = this.enableBlending;
  51279. clone.blendingSpeed = this.blendingSpeed;
  51280. if (this._keys) {
  51281. clone.setKeys(this._keys);
  51282. }
  51283. if (this._ranges) {
  51284. clone._ranges = {};
  51285. for (var name in this._ranges) {
  51286. var range = this._ranges[name];
  51287. if (!range) {
  51288. continue;
  51289. }
  51290. clone._ranges[name] = range.clone();
  51291. }
  51292. }
  51293. return clone;
  51294. };
  51295. /**
  51296. * Sets the key frames of the animation
  51297. * @param values The animation key frames to set
  51298. */
  51299. Animation.prototype.setKeys = function (values) {
  51300. this._keys = values.slice(0);
  51301. };
  51302. /**
  51303. * Serializes the animation to an object
  51304. * @returns Serialized object
  51305. */
  51306. Animation.prototype.serialize = function () {
  51307. var serializationObject = {};
  51308. serializationObject.name = this.name;
  51309. serializationObject.property = this.targetProperty;
  51310. serializationObject.framePerSecond = this.framePerSecond;
  51311. serializationObject.dataType = this.dataType;
  51312. serializationObject.loopBehavior = this.loopMode;
  51313. serializationObject.enableBlending = this.enableBlending;
  51314. serializationObject.blendingSpeed = this.blendingSpeed;
  51315. var dataType = this.dataType;
  51316. serializationObject.keys = [];
  51317. var keys = this.getKeys();
  51318. for (var index = 0; index < keys.length; index++) {
  51319. var animationKey = keys[index];
  51320. var key = {};
  51321. key.frame = animationKey.frame;
  51322. switch (dataType) {
  51323. case Animation.ANIMATIONTYPE_FLOAT:
  51324. key.values = [animationKey.value];
  51325. break;
  51326. case Animation.ANIMATIONTYPE_QUATERNION:
  51327. case Animation.ANIMATIONTYPE_MATRIX:
  51328. case Animation.ANIMATIONTYPE_VECTOR3:
  51329. case Animation.ANIMATIONTYPE_COLOR3:
  51330. key.values = animationKey.value.asArray();
  51331. break;
  51332. }
  51333. serializationObject.keys.push(key);
  51334. }
  51335. serializationObject.ranges = [];
  51336. for (var name in this._ranges) {
  51337. var source = this._ranges[name];
  51338. if (!source) {
  51339. continue;
  51340. }
  51341. var range = {};
  51342. range.name = name;
  51343. range.from = source.from;
  51344. range.to = source.to;
  51345. serializationObject.ranges.push(range);
  51346. }
  51347. return serializationObject;
  51348. };
  51349. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51350. /**
  51351. * Get the float animation type
  51352. */
  51353. get: function () {
  51354. return Animation._ANIMATIONTYPE_FLOAT;
  51355. },
  51356. enumerable: true,
  51357. configurable: true
  51358. });
  51359. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51360. /**
  51361. * Get the Vector3 animation type
  51362. */
  51363. get: function () {
  51364. return Animation._ANIMATIONTYPE_VECTOR3;
  51365. },
  51366. enumerable: true,
  51367. configurable: true
  51368. });
  51369. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51370. /**
  51371. * Get the Vectpr2 animation type
  51372. */
  51373. get: function () {
  51374. return Animation._ANIMATIONTYPE_VECTOR2;
  51375. },
  51376. enumerable: true,
  51377. configurable: true
  51378. });
  51379. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51380. /**
  51381. * Get the Size animation type
  51382. */
  51383. get: function () {
  51384. return Animation._ANIMATIONTYPE_SIZE;
  51385. },
  51386. enumerable: true,
  51387. configurable: true
  51388. });
  51389. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51390. /**
  51391. * Get the Quaternion animation type
  51392. */
  51393. get: function () {
  51394. return Animation._ANIMATIONTYPE_QUATERNION;
  51395. },
  51396. enumerable: true,
  51397. configurable: true
  51398. });
  51399. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51400. /**
  51401. * Get the Matrix animation type
  51402. */
  51403. get: function () {
  51404. return Animation._ANIMATIONTYPE_MATRIX;
  51405. },
  51406. enumerable: true,
  51407. configurable: true
  51408. });
  51409. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51410. /**
  51411. * Get the Color3 animation type
  51412. */
  51413. get: function () {
  51414. return Animation._ANIMATIONTYPE_COLOR3;
  51415. },
  51416. enumerable: true,
  51417. configurable: true
  51418. });
  51419. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51420. /**
  51421. * Get the Relative Loop Mode
  51422. */
  51423. get: function () {
  51424. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51425. },
  51426. enumerable: true,
  51427. configurable: true
  51428. });
  51429. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51430. /**
  51431. * Get the Cycle Loop Mode
  51432. */
  51433. get: function () {
  51434. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51435. },
  51436. enumerable: true,
  51437. configurable: true
  51438. });
  51439. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51440. /**
  51441. * Get the Constant Loop Mode
  51442. */
  51443. get: function () {
  51444. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51445. },
  51446. enumerable: true,
  51447. configurable: true
  51448. });
  51449. /** @hidden */
  51450. Animation._UniversalLerp = function (left, right, amount) {
  51451. var constructor = left.constructor;
  51452. if (constructor.Lerp) { // Lerp supported
  51453. return constructor.Lerp(left, right, amount);
  51454. }
  51455. else if (constructor.Slerp) { // Slerp supported
  51456. return constructor.Slerp(left, right, amount);
  51457. }
  51458. else if (left.toFixed) { // Number
  51459. return left * (1.0 - amount) + amount * right;
  51460. }
  51461. else { // Blending not supported
  51462. return right;
  51463. }
  51464. };
  51465. /**
  51466. * Parses an animation object and creates an animation
  51467. * @param parsedAnimation Parsed animation object
  51468. * @returns Animation object
  51469. */
  51470. Animation.Parse = function (parsedAnimation) {
  51471. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51472. var dataType = parsedAnimation.dataType;
  51473. var keys = [];
  51474. var data;
  51475. var index;
  51476. if (parsedAnimation.enableBlending) {
  51477. animation.enableBlending = parsedAnimation.enableBlending;
  51478. }
  51479. if (parsedAnimation.blendingSpeed) {
  51480. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51481. }
  51482. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51483. var key = parsedAnimation.keys[index];
  51484. var inTangent;
  51485. var outTangent;
  51486. switch (dataType) {
  51487. case Animation.ANIMATIONTYPE_FLOAT:
  51488. data = key.values[0];
  51489. if (key.values.length >= 1) {
  51490. inTangent = key.values[1];
  51491. }
  51492. if (key.values.length >= 2) {
  51493. outTangent = key.values[2];
  51494. }
  51495. break;
  51496. case Animation.ANIMATIONTYPE_QUATERNION:
  51497. data = BABYLON.Quaternion.FromArray(key.values);
  51498. if (key.values.length >= 8) {
  51499. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51500. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51501. inTangent = _inTangent;
  51502. }
  51503. }
  51504. if (key.values.length >= 12) {
  51505. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51506. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51507. outTangent = _outTangent;
  51508. }
  51509. }
  51510. break;
  51511. case Animation.ANIMATIONTYPE_MATRIX:
  51512. data = BABYLON.Matrix.FromArray(key.values);
  51513. break;
  51514. case Animation.ANIMATIONTYPE_COLOR3:
  51515. data = BABYLON.Color3.FromArray(key.values);
  51516. break;
  51517. case Animation.ANIMATIONTYPE_VECTOR3:
  51518. default:
  51519. data = BABYLON.Vector3.FromArray(key.values);
  51520. break;
  51521. }
  51522. var keyData = {};
  51523. keyData.frame = key.frame;
  51524. keyData.value = data;
  51525. if (inTangent != undefined) {
  51526. keyData.inTangent = inTangent;
  51527. }
  51528. if (outTangent != undefined) {
  51529. keyData.outTangent = outTangent;
  51530. }
  51531. keys.push(keyData);
  51532. }
  51533. animation.setKeys(keys);
  51534. if (parsedAnimation.ranges) {
  51535. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51536. data = parsedAnimation.ranges[index];
  51537. animation.createRange(data.name, data.from, data.to);
  51538. }
  51539. }
  51540. return animation;
  51541. };
  51542. /**
  51543. * Appends the serialized animations from the source animations
  51544. * @param source Source containing the animations
  51545. * @param destination Target to store the animations
  51546. */
  51547. Animation.AppendSerializedAnimations = function (source, destination) {
  51548. if (source.animations) {
  51549. destination.animations = [];
  51550. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51551. var animation = source.animations[animationIndex];
  51552. destination.animations.push(animation.serialize());
  51553. }
  51554. }
  51555. };
  51556. /**
  51557. * Use matrix interpolation instead of using direct key value when animating matrices
  51558. */
  51559. Animation.AllowMatricesInterpolation = false;
  51560. /**
  51561. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51562. */
  51563. Animation.AllowMatrixDecomposeForInterpolation = true;
  51564. // Statics
  51565. /**
  51566. * Float animation type
  51567. */
  51568. Animation._ANIMATIONTYPE_FLOAT = 0;
  51569. /**
  51570. * Vector3 animation type
  51571. */
  51572. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51573. /**
  51574. * Quaternion animation type
  51575. */
  51576. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51577. /**
  51578. * Matrix animation type
  51579. */
  51580. Animation._ANIMATIONTYPE_MATRIX = 3;
  51581. /**
  51582. * Color3 animation type
  51583. */
  51584. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51585. /**
  51586. * Vector2 animation type
  51587. */
  51588. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51589. /**
  51590. * Size animation type
  51591. */
  51592. Animation._ANIMATIONTYPE_SIZE = 6;
  51593. /**
  51594. * Relative Loop Mode
  51595. */
  51596. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51597. /**
  51598. * Cycle Loop Mode
  51599. */
  51600. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51601. /**
  51602. * Constant Loop Mode
  51603. */
  51604. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51605. return Animation;
  51606. }());
  51607. BABYLON.Animation = Animation;
  51608. })(BABYLON || (BABYLON = {}));
  51609. //# sourceMappingURL=babylon.animation.js.map
  51610. var BABYLON;
  51611. (function (BABYLON) {
  51612. /**
  51613. * This class defines the direct association between an animation and a target
  51614. */
  51615. var TargetedAnimation = /** @class */ (function () {
  51616. function TargetedAnimation() {
  51617. }
  51618. return TargetedAnimation;
  51619. }());
  51620. BABYLON.TargetedAnimation = TargetedAnimation;
  51621. /**
  51622. * Use this class to create coordinated animations on multiple targets
  51623. */
  51624. var AnimationGroup = /** @class */ (function () {
  51625. function AnimationGroup(name, scene) {
  51626. if (scene === void 0) { scene = null; }
  51627. this.name = name;
  51628. this._targetedAnimations = new Array();
  51629. this._animatables = new Array();
  51630. this._from = Number.MAX_VALUE;
  51631. this._to = -Number.MAX_VALUE;
  51632. this._speedRatio = 1;
  51633. this.onAnimationEndObservable = new BABYLON.Observable();
  51634. /**
  51635. * This observable will notify when all animations have ended.
  51636. */
  51637. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  51638. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51639. this._scene.animationGroups.push(this);
  51640. }
  51641. Object.defineProperty(AnimationGroup.prototype, "from", {
  51642. /**
  51643. * Gets the first frame
  51644. */
  51645. get: function () {
  51646. return this._from;
  51647. },
  51648. enumerable: true,
  51649. configurable: true
  51650. });
  51651. Object.defineProperty(AnimationGroup.prototype, "to", {
  51652. /**
  51653. * Gets the last frame
  51654. */
  51655. get: function () {
  51656. return this._to;
  51657. },
  51658. enumerable: true,
  51659. configurable: true
  51660. });
  51661. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51662. /**
  51663. * Define if the animations are started
  51664. */
  51665. get: function () {
  51666. return this._isStarted;
  51667. },
  51668. enumerable: true,
  51669. configurable: true
  51670. });
  51671. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51672. /**
  51673. * Gets or sets the speed ratio to use for all animations
  51674. */
  51675. get: function () {
  51676. return this._speedRatio;
  51677. },
  51678. /**
  51679. * Gets or sets the speed ratio to use for all animations
  51680. */
  51681. set: function (value) {
  51682. if (this._speedRatio === value) {
  51683. return;
  51684. }
  51685. this._speedRatio = value;
  51686. for (var index = 0; index < this._animatables.length; index++) {
  51687. var animatable = this._animatables[index];
  51688. animatable.speedRatio = this._speedRatio;
  51689. }
  51690. },
  51691. enumerable: true,
  51692. configurable: true
  51693. });
  51694. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51695. /**
  51696. * Gets the targeted animations for this animation group
  51697. */
  51698. get: function () {
  51699. return this._targetedAnimations;
  51700. },
  51701. enumerable: true,
  51702. configurable: true
  51703. });
  51704. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51705. /**
  51706. * returning the list of animatables controlled by this animation group.
  51707. */
  51708. get: function () {
  51709. return this._animatables;
  51710. },
  51711. enumerable: true,
  51712. configurable: true
  51713. });
  51714. /**
  51715. * Add an animation (with its target) in the group
  51716. * @param animation defines the animation we want to add
  51717. * @param target defines the target of the animation
  51718. * @returns the {BABYLON.TargetedAnimation} object
  51719. */
  51720. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51721. var targetedAnimation = {
  51722. animation: animation,
  51723. target: target
  51724. };
  51725. var keys = animation.getKeys();
  51726. if (this._from > keys[0].frame) {
  51727. this._from = keys[0].frame;
  51728. }
  51729. if (this._to < keys[keys.length - 1].frame) {
  51730. this._to = keys[keys.length - 1].frame;
  51731. }
  51732. this._targetedAnimations.push(targetedAnimation);
  51733. return targetedAnimation;
  51734. };
  51735. /**
  51736. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51737. * It can add constant keys at begin or end
  51738. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51739. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51740. */
  51741. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51742. if (beginFrame === void 0) { beginFrame = null; }
  51743. if (endFrame === void 0) { endFrame = null; }
  51744. if (beginFrame == null)
  51745. beginFrame = this._from;
  51746. if (endFrame == null)
  51747. endFrame = this._to;
  51748. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51749. var targetedAnimation = this._targetedAnimations[index];
  51750. var keys = targetedAnimation.animation.getKeys();
  51751. var startKey = keys[0];
  51752. var endKey = keys[keys.length - 1];
  51753. if (startKey.frame > beginFrame) {
  51754. var newKey = {
  51755. frame: beginFrame,
  51756. value: startKey.value,
  51757. inTangent: startKey.inTangent,
  51758. outTangent: startKey.outTangent,
  51759. interpolation: startKey.interpolation
  51760. };
  51761. keys.splice(0, 0, newKey);
  51762. }
  51763. if (endKey.frame < endFrame) {
  51764. var newKey = {
  51765. frame: endFrame,
  51766. value: endKey.value,
  51767. inTangent: endKey.outTangent,
  51768. outTangent: endKey.outTangent,
  51769. interpolation: endKey.interpolation
  51770. };
  51771. keys.push(newKey);
  51772. }
  51773. }
  51774. this._from = beginFrame;
  51775. this._to = endFrame;
  51776. return this;
  51777. };
  51778. /**
  51779. * Start all animations on given targets
  51780. * @param loop defines if animations must loop
  51781. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51782. * @param from defines the from key (optional)
  51783. * @param to defines the to key (optional)
  51784. * @returns the current animation group
  51785. */
  51786. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51787. var _this = this;
  51788. if (loop === void 0) { loop = false; }
  51789. if (speedRatio === void 0) { speedRatio = 1; }
  51790. if (this._isStarted || this._targetedAnimations.length === 0) {
  51791. return this;
  51792. }
  51793. var _loop_1 = function (targetedAnimation) {
  51794. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  51795. animatable.onAnimationEnd = function () {
  51796. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51797. _this._checkAnimationGroupEnded(animatable);
  51798. };
  51799. this_1._animatables.push(animatable);
  51800. };
  51801. var this_1 = this;
  51802. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51803. var targetedAnimation = _a[_i];
  51804. _loop_1(targetedAnimation);
  51805. }
  51806. this._speedRatio = speedRatio;
  51807. this._isStarted = true;
  51808. return this;
  51809. };
  51810. /**
  51811. * Pause all animations
  51812. */
  51813. AnimationGroup.prototype.pause = function () {
  51814. if (!this._isStarted) {
  51815. return this;
  51816. }
  51817. for (var index = 0; index < this._animatables.length; index++) {
  51818. var animatable = this._animatables[index];
  51819. animatable.pause();
  51820. }
  51821. return this;
  51822. };
  51823. /**
  51824. * Play all animations to initial state
  51825. * This function will start() the animations if they were not started or will restart() them if they were paused
  51826. * @param loop defines if animations must loop
  51827. */
  51828. AnimationGroup.prototype.play = function (loop) {
  51829. // only if all animatables are ready and exist
  51830. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  51831. if (loop !== undefined) {
  51832. for (var index = 0; index < this._animatables.length; index++) {
  51833. var animatable = this._animatables[index];
  51834. animatable.loopAnimation = loop;
  51835. }
  51836. }
  51837. this.restart();
  51838. }
  51839. else {
  51840. this.stop();
  51841. this.start(loop, this._speedRatio);
  51842. }
  51843. return this;
  51844. };
  51845. /**
  51846. * Reset all animations to initial state
  51847. */
  51848. AnimationGroup.prototype.reset = function () {
  51849. if (!this._isStarted) {
  51850. return this;
  51851. }
  51852. for (var index = 0; index < this._animatables.length; index++) {
  51853. var animatable = this._animatables[index];
  51854. animatable.reset();
  51855. }
  51856. return this;
  51857. };
  51858. /**
  51859. * Restart animations from key 0
  51860. */
  51861. AnimationGroup.prototype.restart = function () {
  51862. if (!this._isStarted) {
  51863. return this;
  51864. }
  51865. for (var index = 0; index < this._animatables.length; index++) {
  51866. var animatable = this._animatables[index];
  51867. animatable.restart();
  51868. }
  51869. return this;
  51870. };
  51871. /**
  51872. * Stop all animations
  51873. */
  51874. AnimationGroup.prototype.stop = function () {
  51875. if (!this._isStarted) {
  51876. return this;
  51877. }
  51878. for (var index = 0; index < this._animatables.length; index++) {
  51879. var animatable = this._animatables[index];
  51880. animatable.stop();
  51881. }
  51882. this._isStarted = false;
  51883. return this;
  51884. };
  51885. /**
  51886. * Set animation weight for all animatables
  51887. * @param weight defines the weight to use
  51888. * @return the animationGroup
  51889. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51890. */
  51891. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51892. for (var index = 0; index < this._animatables.length; index++) {
  51893. var animatable = this._animatables[index];
  51894. animatable.weight = weight;
  51895. }
  51896. return this;
  51897. };
  51898. /**
  51899. * Synchronize and normalize all animatables with a source animatable
  51900. * @param root defines the root animatable to synchronize with
  51901. * @return the animationGroup
  51902. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51903. */
  51904. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51905. for (var index = 0; index < this._animatables.length; index++) {
  51906. var animatable = this._animatables[index];
  51907. animatable.syncWith(root);
  51908. }
  51909. return this;
  51910. };
  51911. /**
  51912. * Goes to a specific frame in this animation group
  51913. * @param frame the frame number to go to
  51914. * @return the animationGroup
  51915. */
  51916. AnimationGroup.prototype.goToFrame = function (frame) {
  51917. if (!this._isStarted) {
  51918. return this;
  51919. }
  51920. for (var index = 0; index < this._animatables.length; index++) {
  51921. var animatable = this._animatables[index];
  51922. animatable.goToFrame(frame);
  51923. }
  51924. return this;
  51925. };
  51926. /**
  51927. * Dispose all associated resources
  51928. */
  51929. AnimationGroup.prototype.dispose = function () {
  51930. this._targetedAnimations = [];
  51931. this._animatables = [];
  51932. var index = this._scene.animationGroups.indexOf(this);
  51933. if (index > -1) {
  51934. this._scene.animationGroups.splice(index, 1);
  51935. }
  51936. };
  51937. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  51938. // animatable should be taken out of the array
  51939. var idx = this._animatables.indexOf(animatable);
  51940. if (idx > -1) {
  51941. this._animatables.splice(idx, 1);
  51942. }
  51943. // all animatables were removed? animation group ended!
  51944. if (this._animatables.length === 0) {
  51945. this._isStarted = false;
  51946. this.onAnimationGroupEndObservable.notifyObservers(this);
  51947. }
  51948. };
  51949. return AnimationGroup;
  51950. }());
  51951. BABYLON.AnimationGroup = AnimationGroup;
  51952. })(BABYLON || (BABYLON = {}));
  51953. //# sourceMappingURL=babylon.animationGroup.js.map
  51954. var BABYLON;
  51955. (function (BABYLON) {
  51956. /**
  51957. * Defines a runtime animation
  51958. */
  51959. var RuntimeAnimation = /** @class */ (function () {
  51960. /**
  51961. * Create a new RuntimeAnimation object
  51962. * @param target defines the target of the animation
  51963. * @param animation defines the source animation object
  51964. * @param scene defines the hosting scene
  51965. * @param host defines the initiating Animatable
  51966. */
  51967. function RuntimeAnimation(target, animation, scene, host) {
  51968. var _this = this;
  51969. this._events = new Array();
  51970. /**
  51971. * The current frame of the runtime animation
  51972. */
  51973. this._currentFrame = 0;
  51974. /**
  51975. * The original value of the runtime animation
  51976. */
  51977. this._originalValue = new Array();
  51978. /**
  51979. * The offsets cache of the runtime animation
  51980. */
  51981. this._offsetsCache = {};
  51982. /**
  51983. * The high limits cache of the runtime animation
  51984. */
  51985. this._highLimitsCache = {};
  51986. /**
  51987. * Specifies if the runtime animation has been stopped
  51988. */
  51989. this._stopped = false;
  51990. /**
  51991. * The blending factor of the runtime animation
  51992. */
  51993. this._blendingFactor = 0;
  51994. /**
  51995. * The target path of the runtime animation
  51996. */
  51997. this._targetPath = "";
  51998. /**
  51999. * The weight of the runtime animation
  52000. */
  52001. this._weight = 1.0;
  52002. /**
  52003. * The ratio offset of the runtime animation
  52004. */
  52005. this._ratioOffset = 0;
  52006. /**
  52007. * The previous delay of the runtime animation
  52008. */
  52009. this._previousDelay = 0;
  52010. /**
  52011. * The previous ratio of the runtime animation
  52012. */
  52013. this._previousRatio = 0;
  52014. this._animation = animation;
  52015. this._target = target;
  52016. this._scene = scene;
  52017. this._host = host;
  52018. animation._runtimeAnimations.push(this);
  52019. // Cloning events locally
  52020. var events = animation.getEvents();
  52021. if (events && events.length > 0) {
  52022. events.forEach(function (e) {
  52023. _this._events.push(e._clone());
  52024. });
  52025. }
  52026. }
  52027. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  52028. /**
  52029. * Gets the current frame of the runtime animation
  52030. */
  52031. get: function () {
  52032. return this._currentFrame;
  52033. },
  52034. enumerable: true,
  52035. configurable: true
  52036. });
  52037. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  52038. /**
  52039. * Gets the weight of the runtime animation
  52040. */
  52041. get: function () {
  52042. return this._weight;
  52043. },
  52044. enumerable: true,
  52045. configurable: true
  52046. });
  52047. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  52048. /**
  52049. * Gets the current value of the runtime animation
  52050. */
  52051. get: function () {
  52052. return this._currentValue;
  52053. },
  52054. enumerable: true,
  52055. configurable: true
  52056. });
  52057. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  52058. /**
  52059. * Gets the target path of the runtime animation
  52060. */
  52061. get: function () {
  52062. return this._targetPath;
  52063. },
  52064. enumerable: true,
  52065. configurable: true
  52066. });
  52067. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  52068. /**
  52069. * Gets the actual target of the runtime animation
  52070. */
  52071. get: function () {
  52072. return this._activeTarget;
  52073. },
  52074. enumerable: true,
  52075. configurable: true
  52076. });
  52077. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  52078. /**
  52079. * Gets the animation from the runtime animation
  52080. */
  52081. get: function () {
  52082. return this._animation;
  52083. },
  52084. enumerable: true,
  52085. configurable: true
  52086. });
  52087. /**
  52088. * Resets the runtime animation to the beginning
  52089. * @param restoreOriginal defines whether to restore the target property to the original value
  52090. */
  52091. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  52092. if (restoreOriginal === void 0) { restoreOriginal = false; }
  52093. if (restoreOriginal) {
  52094. if (this._target instanceof Array) {
  52095. var index = 0;
  52096. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52097. var target = _a[_i];
  52098. if (this._originalValue[index] !== undefined) {
  52099. this._setValue(target, this._originalValue[index], -1);
  52100. }
  52101. index++;
  52102. }
  52103. }
  52104. else {
  52105. if (this._originalValue[0] !== undefined) {
  52106. this._setValue(this._target, this._originalValue[0], -1);
  52107. }
  52108. }
  52109. }
  52110. this._offsetsCache = {};
  52111. this._highLimitsCache = {};
  52112. this._currentFrame = 0;
  52113. this._blendingFactor = 0;
  52114. this._originalValue = new Array();
  52115. // Events
  52116. for (var index = 0; index < this._events.length; index++) {
  52117. this._events[index].isDone = false;
  52118. }
  52119. };
  52120. /**
  52121. * Specifies if the runtime animation is stopped
  52122. * @returns Boolean specifying if the runtime animation is stopped
  52123. */
  52124. RuntimeAnimation.prototype.isStopped = function () {
  52125. return this._stopped;
  52126. };
  52127. /**
  52128. * Disposes of the runtime animation
  52129. */
  52130. RuntimeAnimation.prototype.dispose = function () {
  52131. var index = this._animation.runtimeAnimations.indexOf(this);
  52132. if (index > -1) {
  52133. this._animation.runtimeAnimations.splice(index, 1);
  52134. }
  52135. };
  52136. /**
  52137. * Interpolates the animation from the current frame
  52138. * @param currentFrame The frame to interpolate the animation to
  52139. * @param repeatCount The number of times that the animation should loop
  52140. * @param loopMode The type of looping mode to use
  52141. * @param offsetValue Animation offset value
  52142. * @param highLimitValue The high limit value
  52143. * @returns The interpolated value
  52144. */
  52145. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  52146. this._currentFrame = currentFrame;
  52147. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  52148. this._workValue = BABYLON.Matrix.Zero();
  52149. }
  52150. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  52151. };
  52152. /**
  52153. * Apply the interpolated value to the target
  52154. * @param currentValue defines the value computed by the animation
  52155. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  52156. */
  52157. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  52158. if (weight === void 0) { weight = 1.0; }
  52159. if (this._target instanceof Array) {
  52160. var index = 0;
  52161. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52162. var target = _a[_i];
  52163. this._setValue(target, currentValue, weight, index);
  52164. index++;
  52165. }
  52166. }
  52167. else {
  52168. this._setValue(this._target, currentValue, weight);
  52169. }
  52170. };
  52171. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  52172. if (targetIndex === void 0) { targetIndex = 0; }
  52173. // Set value
  52174. var path;
  52175. var destination;
  52176. var targetPropertyPath = this._animation.targetPropertyPath;
  52177. if (targetPropertyPath.length > 1) {
  52178. var property = target[targetPropertyPath[0]];
  52179. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  52180. property = property[targetPropertyPath[index]];
  52181. }
  52182. path = targetPropertyPath[targetPropertyPath.length - 1];
  52183. destination = property;
  52184. }
  52185. else {
  52186. path = targetPropertyPath[0];
  52187. destination = target;
  52188. }
  52189. this._targetPath = path;
  52190. this._activeTarget = destination;
  52191. this._weight = weight;
  52192. if (this._originalValue[targetIndex] === undefined) {
  52193. var originalValue = void 0;
  52194. if (destination.getRestPose && path === "_matrix") { // For bones
  52195. originalValue = destination.getRestPose();
  52196. }
  52197. else {
  52198. originalValue = destination[path];
  52199. }
  52200. if (originalValue && originalValue.clone) {
  52201. this._originalValue[targetIndex] = originalValue.clone();
  52202. }
  52203. else {
  52204. this._originalValue[targetIndex] = originalValue;
  52205. }
  52206. }
  52207. // Blending
  52208. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  52209. if (enableBlending && this._blendingFactor <= 1.0) {
  52210. if (!this._originalBlendValue) {
  52211. var originalValue = destination[path];
  52212. if (originalValue.clone) {
  52213. this._originalBlendValue = originalValue.clone();
  52214. }
  52215. else {
  52216. this._originalBlendValue = originalValue;
  52217. }
  52218. }
  52219. if (this._originalBlendValue.m) { // Matrix
  52220. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  52221. if (this._currentValue) {
  52222. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52223. }
  52224. else {
  52225. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52226. }
  52227. }
  52228. else {
  52229. if (this._currentValue) {
  52230. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52231. }
  52232. else {
  52233. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52234. }
  52235. }
  52236. }
  52237. else {
  52238. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52239. }
  52240. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  52241. this._blendingFactor += blendingSpeed;
  52242. }
  52243. else {
  52244. this._currentValue = currentValue;
  52245. }
  52246. if (weight !== -1.0) {
  52247. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  52248. }
  52249. else {
  52250. destination[path] = this._currentValue;
  52251. }
  52252. if (target.markAsDirty) {
  52253. target.markAsDirty(this._animation.targetProperty);
  52254. }
  52255. };
  52256. /**
  52257. * Gets the loop pmode of the runtime animation
  52258. * @returns Loop Mode
  52259. */
  52260. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  52261. if (this._target && this._target.animationPropertiesOverride) {
  52262. return this._target.animationPropertiesOverride.loopMode;
  52263. }
  52264. return this._animation.loopMode;
  52265. };
  52266. /**
  52267. * Move the current animation to a given frame
  52268. * @param frame defines the frame to move to
  52269. */
  52270. RuntimeAnimation.prototype.goToFrame = function (frame) {
  52271. var keys = this._animation.getKeys();
  52272. if (frame < keys[0].frame) {
  52273. frame = keys[0].frame;
  52274. }
  52275. else if (frame > keys[keys.length - 1].frame) {
  52276. frame = keys[keys.length - 1].frame;
  52277. }
  52278. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  52279. this.setValue(currentValue, -1);
  52280. };
  52281. /**
  52282. * @hidden Internal use only
  52283. */
  52284. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52285. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52286. this._ratioOffset = this._previousRatio - newRatio;
  52287. };
  52288. /**
  52289. * Execute the current animation
  52290. * @param delay defines the delay to add to the current frame
  52291. * @param from defines the lower bound of the animation range
  52292. * @param to defines the upper bound of the animation range
  52293. * @param loop defines if the current animation must loop
  52294. * @param speedRatio defines the current speed ratio
  52295. * @param weight defines the weight of the animation (default is -1 so no weight)
  52296. * @returns a boolean indicating if the animation has ended
  52297. */
  52298. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52299. if (weight === void 0) { weight = -1.0; }
  52300. var targetPropertyPath = this._animation.targetPropertyPath;
  52301. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52302. this._stopped = true;
  52303. return false;
  52304. }
  52305. var returnValue = true;
  52306. var keys = this._animation.getKeys();
  52307. // Adding a start key at frame 0 if missing
  52308. if (keys[0].frame !== 0) {
  52309. var newKey = { frame: 0, value: keys[0].value };
  52310. keys.splice(0, 0, newKey);
  52311. }
  52312. // Check limits
  52313. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52314. from = keys[0].frame;
  52315. }
  52316. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52317. to = keys[keys.length - 1].frame;
  52318. }
  52319. //to and from cannot be the same key
  52320. if (from === to) {
  52321. if (from > keys[0].frame) {
  52322. from--;
  52323. }
  52324. else if (to < keys[keys.length - 1].frame) {
  52325. to++;
  52326. }
  52327. }
  52328. // Compute ratio
  52329. var range = to - from;
  52330. var offsetValue;
  52331. // ratio represents the frame delta between from and to
  52332. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52333. var highLimitValue = 0;
  52334. this._previousDelay = delay;
  52335. this._previousRatio = ratio;
  52336. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { // If we are out of range and not looping get back to caller
  52337. returnValue = false;
  52338. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52339. }
  52340. else {
  52341. // Get max value if required
  52342. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52343. var keyOffset = to.toString() + from.toString();
  52344. if (!this._offsetsCache[keyOffset]) {
  52345. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52346. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52347. switch (this._animation.dataType) {
  52348. // Float
  52349. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52350. this._offsetsCache[keyOffset] = toValue - fromValue;
  52351. break;
  52352. // Quaternion
  52353. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52354. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52355. break;
  52356. // Vector3
  52357. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52358. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52359. // Vector2
  52360. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52361. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52362. // Size
  52363. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52364. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52365. // Color3
  52366. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52367. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52368. default:
  52369. break;
  52370. }
  52371. this._highLimitsCache[keyOffset] = toValue;
  52372. }
  52373. highLimitValue = this._highLimitsCache[keyOffset];
  52374. offsetValue = this._offsetsCache[keyOffset];
  52375. }
  52376. }
  52377. if (offsetValue === undefined) {
  52378. switch (this._animation.dataType) {
  52379. // Float
  52380. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52381. offsetValue = 0;
  52382. break;
  52383. // Quaternion
  52384. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52385. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  52386. break;
  52387. // Vector3
  52388. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52389. offsetValue = BABYLON.Vector3.Zero();
  52390. break;
  52391. // Vector2
  52392. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52393. offsetValue = BABYLON.Vector2.Zero();
  52394. break;
  52395. // Size
  52396. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52397. offsetValue = BABYLON.Size.Zero();
  52398. break;
  52399. // Color3
  52400. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52401. offsetValue = BABYLON.Color3.Black();
  52402. }
  52403. }
  52404. // Compute value
  52405. var repeatCount = (ratio / range) >> 0;
  52406. var currentFrame = returnValue ? from + ratio % range : to;
  52407. // Need to normalize?
  52408. if (this._host && this._host.syncRoot) {
  52409. var syncRoot = this._host.syncRoot;
  52410. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52411. currentFrame = from + (to - from) * hostNormalizedFrame;
  52412. }
  52413. // Reset events if looping
  52414. var events = this._events;
  52415. if (range > 0 && this.currentFrame > currentFrame ||
  52416. range < 0 && this.currentFrame < currentFrame) {
  52417. // Need to reset animation events
  52418. for (var index = 0; index < events.length; index++) {
  52419. if (!events[index].onlyOnce) {
  52420. // reset event, the animation is looping
  52421. events[index].isDone = false;
  52422. }
  52423. }
  52424. }
  52425. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52426. // Set value
  52427. this.setValue(currentValue, weight);
  52428. // Check events
  52429. for (var index = 0; index < events.length; index++) {
  52430. // Make sure current frame has passed event frame and that event frame is within the current range
  52431. // Also, handle both forward and reverse animations
  52432. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52433. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52434. var event = events[index];
  52435. if (!event.isDone) {
  52436. // If event should be done only once, remove it.
  52437. if (event.onlyOnce) {
  52438. events.splice(index, 1);
  52439. index--;
  52440. }
  52441. event.isDone = true;
  52442. event.action();
  52443. } // Don't do anything if the event has already be done.
  52444. }
  52445. }
  52446. if (!returnValue) {
  52447. this._stopped = true;
  52448. }
  52449. return returnValue;
  52450. };
  52451. return RuntimeAnimation;
  52452. }());
  52453. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52454. })(BABYLON || (BABYLON = {}));
  52455. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52456. var BABYLON;
  52457. (function (BABYLON) {
  52458. var Animatable = /** @class */ (function () {
  52459. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  52460. if (fromFrame === void 0) { fromFrame = 0; }
  52461. if (toFrame === void 0) { toFrame = 100; }
  52462. if (loopAnimation === void 0) { loopAnimation = false; }
  52463. if (speedRatio === void 0) { speedRatio = 1.0; }
  52464. this.target = target;
  52465. this.fromFrame = fromFrame;
  52466. this.toFrame = toFrame;
  52467. this.loopAnimation = loopAnimation;
  52468. this.onAnimationEnd = onAnimationEnd;
  52469. this._localDelayOffset = null;
  52470. this._pausedDelay = null;
  52471. this._runtimeAnimations = new Array();
  52472. this._paused = false;
  52473. this._speedRatio = 1;
  52474. this._weight = -1.0;
  52475. this.animationStarted = false;
  52476. /**
  52477. * Observer raised when the animation ends
  52478. */
  52479. this.onAnimationEndObservable = new BABYLON.Observable();
  52480. this._scene = scene;
  52481. if (animations) {
  52482. this.appendAnimations(target, animations);
  52483. }
  52484. this._speedRatio = speedRatio;
  52485. scene._activeAnimatables.push(this);
  52486. }
  52487. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52488. /**
  52489. * Gets the root Animatable used to synchronize and normalize animations
  52490. */
  52491. get: function () {
  52492. return this._syncRoot;
  52493. },
  52494. enumerable: true,
  52495. configurable: true
  52496. });
  52497. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52498. /**
  52499. * Gets the current frame of the first RuntimeAnimation
  52500. * Used to synchronize Animatables
  52501. */
  52502. get: function () {
  52503. if (this._runtimeAnimations.length === 0) {
  52504. return 0;
  52505. }
  52506. return this._runtimeAnimations[0].currentFrame;
  52507. },
  52508. enumerable: true,
  52509. configurable: true
  52510. });
  52511. Object.defineProperty(Animatable.prototype, "weight", {
  52512. /**
  52513. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52514. */
  52515. get: function () {
  52516. return this._weight;
  52517. },
  52518. set: function (value) {
  52519. if (value === -1) { // -1 is ok and means no weight
  52520. this._weight = -1;
  52521. return;
  52522. }
  52523. // Else weight must be in [0, 1] range
  52524. this._weight = Math.min(Math.max(value, 0), 1.0);
  52525. },
  52526. enumerable: true,
  52527. configurable: true
  52528. });
  52529. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52530. /**
  52531. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52532. */
  52533. get: function () {
  52534. return this._speedRatio;
  52535. },
  52536. set: function (value) {
  52537. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52538. var animation = this._runtimeAnimations[index];
  52539. animation._prepareForSpeedRatioChange(value);
  52540. }
  52541. this._speedRatio = value;
  52542. },
  52543. enumerable: true,
  52544. configurable: true
  52545. });
  52546. // Methods
  52547. /**
  52548. * Synchronize and normalize current Animatable with a source Animatable
  52549. * This is useful when using animation weights and when animations are not of the same length
  52550. * @param root defines the root Animatable to synchronize with
  52551. * @returns the current Animatable
  52552. */
  52553. Animatable.prototype.syncWith = function (root) {
  52554. this._syncRoot = root;
  52555. if (root) {
  52556. // Make sure this animatable will animate after the root
  52557. var index = this._scene._activeAnimatables.indexOf(this);
  52558. if (index > -1) {
  52559. this._scene._activeAnimatables.splice(index, 1);
  52560. this._scene._activeAnimatables.push(this);
  52561. }
  52562. }
  52563. return this;
  52564. };
  52565. Animatable.prototype.getAnimations = function () {
  52566. return this._runtimeAnimations;
  52567. };
  52568. Animatable.prototype.appendAnimations = function (target, animations) {
  52569. for (var index = 0; index < animations.length; index++) {
  52570. var animation = animations[index];
  52571. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52572. }
  52573. };
  52574. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52575. var runtimeAnimations = this._runtimeAnimations;
  52576. for (var index = 0; index < runtimeAnimations.length; index++) {
  52577. if (runtimeAnimations[index].animation.targetProperty === property) {
  52578. return runtimeAnimations[index].animation;
  52579. }
  52580. }
  52581. return null;
  52582. };
  52583. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52584. var runtimeAnimations = this._runtimeAnimations;
  52585. for (var index = 0; index < runtimeAnimations.length; index++) {
  52586. if (runtimeAnimations[index].animation.targetProperty === property) {
  52587. return runtimeAnimations[index];
  52588. }
  52589. }
  52590. return null;
  52591. };
  52592. Animatable.prototype.reset = function () {
  52593. var runtimeAnimations = this._runtimeAnimations;
  52594. for (var index = 0; index < runtimeAnimations.length; index++) {
  52595. runtimeAnimations[index].reset(true);
  52596. }
  52597. this._localDelayOffset = null;
  52598. this._pausedDelay = null;
  52599. };
  52600. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52601. var runtimeAnimations = this._runtimeAnimations;
  52602. for (var index = 0; index < runtimeAnimations.length; index++) {
  52603. runtimeAnimations[index].animation.enableBlending = true;
  52604. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52605. }
  52606. };
  52607. Animatable.prototype.disableBlending = function () {
  52608. var runtimeAnimations = this._runtimeAnimations;
  52609. for (var index = 0; index < runtimeAnimations.length; index++) {
  52610. runtimeAnimations[index].animation.enableBlending = false;
  52611. }
  52612. };
  52613. Animatable.prototype.goToFrame = function (frame) {
  52614. var runtimeAnimations = this._runtimeAnimations;
  52615. if (runtimeAnimations[0]) {
  52616. var fps = runtimeAnimations[0].animation.framePerSecond;
  52617. var currentFrame = runtimeAnimations[0].currentFrame;
  52618. var adjustTime = frame - currentFrame;
  52619. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52620. if (this._localDelayOffset === null) {
  52621. this._localDelayOffset = 0;
  52622. }
  52623. this._localDelayOffset -= delay;
  52624. }
  52625. for (var index = 0; index < runtimeAnimations.length; index++) {
  52626. runtimeAnimations[index].goToFrame(frame);
  52627. }
  52628. };
  52629. Animatable.prototype.pause = function () {
  52630. if (this._paused) {
  52631. return;
  52632. }
  52633. this._paused = true;
  52634. };
  52635. Animatable.prototype.restart = function () {
  52636. this._paused = false;
  52637. };
  52638. Animatable.prototype._raiseOnAnimationEnd = function () {
  52639. if (this.onAnimationEnd) {
  52640. this.onAnimationEnd();
  52641. }
  52642. this.onAnimationEndObservable.notifyObservers(this);
  52643. };
  52644. Animatable.prototype.stop = function (animationName) {
  52645. if (animationName) {
  52646. var idx = this._scene._activeAnimatables.indexOf(this);
  52647. if (idx > -1) {
  52648. var runtimeAnimations = this._runtimeAnimations;
  52649. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52650. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52651. continue;
  52652. }
  52653. runtimeAnimations[index].dispose();
  52654. runtimeAnimations.splice(index, 1);
  52655. }
  52656. if (runtimeAnimations.length == 0) {
  52657. this._scene._activeAnimatables.splice(idx, 1);
  52658. this._raiseOnAnimationEnd();
  52659. }
  52660. }
  52661. }
  52662. else {
  52663. var index = this._scene._activeAnimatables.indexOf(this);
  52664. if (index > -1) {
  52665. this._scene._activeAnimatables.splice(index, 1);
  52666. var runtimeAnimations = this._runtimeAnimations;
  52667. for (var index = 0; index < runtimeAnimations.length; index++) {
  52668. runtimeAnimations[index].dispose();
  52669. }
  52670. this._raiseOnAnimationEnd();
  52671. }
  52672. }
  52673. };
  52674. /**
  52675. * Wait asynchronously for the animation to end
  52676. * @returns a promise which will be fullfilled when the animation ends
  52677. */
  52678. Animatable.prototype.waitAsync = function () {
  52679. var _this = this;
  52680. return new Promise(function (resolve, reject) {
  52681. _this.onAnimationEndObservable.add(function () {
  52682. resolve(_this);
  52683. }, undefined, undefined, _this, true);
  52684. });
  52685. };
  52686. /** @hidden */
  52687. Animatable.prototype._animate = function (delay) {
  52688. if (this._paused) {
  52689. this.animationStarted = false;
  52690. if (this._pausedDelay === null) {
  52691. this._pausedDelay = delay;
  52692. }
  52693. return true;
  52694. }
  52695. if (this._localDelayOffset === null) {
  52696. this._localDelayOffset = delay;
  52697. this._pausedDelay = null;
  52698. }
  52699. else if (this._pausedDelay !== null) {
  52700. this._localDelayOffset += delay - this._pausedDelay;
  52701. this._pausedDelay = null;
  52702. }
  52703. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52704. return true;
  52705. }
  52706. // Animating
  52707. var running = false;
  52708. var runtimeAnimations = this._runtimeAnimations;
  52709. var index;
  52710. for (index = 0; index < runtimeAnimations.length; index++) {
  52711. var animation = runtimeAnimations[index];
  52712. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52713. running = running || isRunning;
  52714. }
  52715. this.animationStarted = running;
  52716. if (!running) {
  52717. // Remove from active animatables
  52718. index = this._scene._activeAnimatables.indexOf(this);
  52719. this._scene._activeAnimatables.splice(index, 1);
  52720. // Dispose all runtime animations
  52721. for (index = 0; index < runtimeAnimations.length; index++) {
  52722. runtimeAnimations[index].dispose();
  52723. }
  52724. this._raiseOnAnimationEnd();
  52725. this.onAnimationEnd = null;
  52726. this.onAnimationEndObservable.clear();
  52727. }
  52728. return running;
  52729. };
  52730. return Animatable;
  52731. }());
  52732. BABYLON.Animatable = Animatable;
  52733. })(BABYLON || (BABYLON = {}));
  52734. //# sourceMappingURL=babylon.animatable.js.map
  52735. var BABYLON;
  52736. (function (BABYLON) {
  52737. var EasingFunction = /** @class */ (function () {
  52738. function EasingFunction() {
  52739. // Properties
  52740. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52741. }
  52742. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52743. get: function () {
  52744. return EasingFunction._EASINGMODE_EASEIN;
  52745. },
  52746. enumerable: true,
  52747. configurable: true
  52748. });
  52749. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52750. get: function () {
  52751. return EasingFunction._EASINGMODE_EASEOUT;
  52752. },
  52753. enumerable: true,
  52754. configurable: true
  52755. });
  52756. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52757. get: function () {
  52758. return EasingFunction._EASINGMODE_EASEINOUT;
  52759. },
  52760. enumerable: true,
  52761. configurable: true
  52762. });
  52763. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52764. var n = Math.min(Math.max(easingMode, 0), 2);
  52765. this._easingMode = n;
  52766. };
  52767. EasingFunction.prototype.getEasingMode = function () {
  52768. return this._easingMode;
  52769. };
  52770. EasingFunction.prototype.easeInCore = function (gradient) {
  52771. throw new Error('You must implement this method');
  52772. };
  52773. EasingFunction.prototype.ease = function (gradient) {
  52774. switch (this._easingMode) {
  52775. case EasingFunction.EASINGMODE_EASEIN:
  52776. return this.easeInCore(gradient);
  52777. case EasingFunction.EASINGMODE_EASEOUT:
  52778. return (1 - this.easeInCore(1 - gradient));
  52779. }
  52780. if (gradient >= 0.5) {
  52781. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52782. }
  52783. return (this.easeInCore(gradient * 2) * 0.5);
  52784. };
  52785. //Statics
  52786. EasingFunction._EASINGMODE_EASEIN = 0;
  52787. EasingFunction._EASINGMODE_EASEOUT = 1;
  52788. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52789. return EasingFunction;
  52790. }());
  52791. BABYLON.EasingFunction = EasingFunction;
  52792. var CircleEase = /** @class */ (function (_super) {
  52793. __extends(CircleEase, _super);
  52794. function CircleEase() {
  52795. return _super !== null && _super.apply(this, arguments) || this;
  52796. }
  52797. CircleEase.prototype.easeInCore = function (gradient) {
  52798. gradient = Math.max(0, Math.min(1, gradient));
  52799. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52800. };
  52801. return CircleEase;
  52802. }(EasingFunction));
  52803. BABYLON.CircleEase = CircleEase;
  52804. var BackEase = /** @class */ (function (_super) {
  52805. __extends(BackEase, _super);
  52806. function BackEase(amplitude) {
  52807. if (amplitude === void 0) { amplitude = 1; }
  52808. var _this = _super.call(this) || this;
  52809. _this.amplitude = amplitude;
  52810. return _this;
  52811. }
  52812. BackEase.prototype.easeInCore = function (gradient) {
  52813. var num = Math.max(0, this.amplitude);
  52814. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52815. };
  52816. return BackEase;
  52817. }(EasingFunction));
  52818. BABYLON.BackEase = BackEase;
  52819. var BounceEase = /** @class */ (function (_super) {
  52820. __extends(BounceEase, _super);
  52821. function BounceEase(bounces, bounciness) {
  52822. if (bounces === void 0) { bounces = 3; }
  52823. if (bounciness === void 0) { bounciness = 2; }
  52824. var _this = _super.call(this) || this;
  52825. _this.bounces = bounces;
  52826. _this.bounciness = bounciness;
  52827. return _this;
  52828. }
  52829. BounceEase.prototype.easeInCore = function (gradient) {
  52830. var y = Math.max(0.0, this.bounces);
  52831. var bounciness = this.bounciness;
  52832. if (bounciness <= 1.0) {
  52833. bounciness = 1.001;
  52834. }
  52835. var num9 = Math.pow(bounciness, y);
  52836. var num5 = 1.0 - bounciness;
  52837. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52838. var num15 = gradient * num4;
  52839. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52840. var num3 = Math.floor(num65);
  52841. var num13 = num3 + 1.0;
  52842. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52843. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52844. var num7 = (num8 + num12) * 0.5;
  52845. var num6 = gradient - num7;
  52846. var num2 = num7 - num8;
  52847. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52848. };
  52849. return BounceEase;
  52850. }(EasingFunction));
  52851. BABYLON.BounceEase = BounceEase;
  52852. var CubicEase = /** @class */ (function (_super) {
  52853. __extends(CubicEase, _super);
  52854. function CubicEase() {
  52855. return _super !== null && _super.apply(this, arguments) || this;
  52856. }
  52857. CubicEase.prototype.easeInCore = function (gradient) {
  52858. return (gradient * gradient * gradient);
  52859. };
  52860. return CubicEase;
  52861. }(EasingFunction));
  52862. BABYLON.CubicEase = CubicEase;
  52863. var ElasticEase = /** @class */ (function (_super) {
  52864. __extends(ElasticEase, _super);
  52865. function ElasticEase(oscillations, springiness) {
  52866. if (oscillations === void 0) { oscillations = 3; }
  52867. if (springiness === void 0) { springiness = 3; }
  52868. var _this = _super.call(this) || this;
  52869. _this.oscillations = oscillations;
  52870. _this.springiness = springiness;
  52871. return _this;
  52872. }
  52873. ElasticEase.prototype.easeInCore = function (gradient) {
  52874. var num2;
  52875. var num3 = Math.max(0.0, this.oscillations);
  52876. var num = Math.max(0.0, this.springiness);
  52877. if (num == 0) {
  52878. num2 = gradient;
  52879. }
  52880. else {
  52881. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52882. }
  52883. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52884. };
  52885. return ElasticEase;
  52886. }(EasingFunction));
  52887. BABYLON.ElasticEase = ElasticEase;
  52888. var ExponentialEase = /** @class */ (function (_super) {
  52889. __extends(ExponentialEase, _super);
  52890. function ExponentialEase(exponent) {
  52891. if (exponent === void 0) { exponent = 2; }
  52892. var _this = _super.call(this) || this;
  52893. _this.exponent = exponent;
  52894. return _this;
  52895. }
  52896. ExponentialEase.prototype.easeInCore = function (gradient) {
  52897. if (this.exponent <= 0) {
  52898. return gradient;
  52899. }
  52900. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52901. };
  52902. return ExponentialEase;
  52903. }(EasingFunction));
  52904. BABYLON.ExponentialEase = ExponentialEase;
  52905. var PowerEase = /** @class */ (function (_super) {
  52906. __extends(PowerEase, _super);
  52907. function PowerEase(power) {
  52908. if (power === void 0) { power = 2; }
  52909. var _this = _super.call(this) || this;
  52910. _this.power = power;
  52911. return _this;
  52912. }
  52913. PowerEase.prototype.easeInCore = function (gradient) {
  52914. var y = Math.max(0.0, this.power);
  52915. return Math.pow(gradient, y);
  52916. };
  52917. return PowerEase;
  52918. }(EasingFunction));
  52919. BABYLON.PowerEase = PowerEase;
  52920. var QuadraticEase = /** @class */ (function (_super) {
  52921. __extends(QuadraticEase, _super);
  52922. function QuadraticEase() {
  52923. return _super !== null && _super.apply(this, arguments) || this;
  52924. }
  52925. QuadraticEase.prototype.easeInCore = function (gradient) {
  52926. return (gradient * gradient);
  52927. };
  52928. return QuadraticEase;
  52929. }(EasingFunction));
  52930. BABYLON.QuadraticEase = QuadraticEase;
  52931. var QuarticEase = /** @class */ (function (_super) {
  52932. __extends(QuarticEase, _super);
  52933. function QuarticEase() {
  52934. return _super !== null && _super.apply(this, arguments) || this;
  52935. }
  52936. QuarticEase.prototype.easeInCore = function (gradient) {
  52937. return (gradient * gradient * gradient * gradient);
  52938. };
  52939. return QuarticEase;
  52940. }(EasingFunction));
  52941. BABYLON.QuarticEase = QuarticEase;
  52942. var QuinticEase = /** @class */ (function (_super) {
  52943. __extends(QuinticEase, _super);
  52944. function QuinticEase() {
  52945. return _super !== null && _super.apply(this, arguments) || this;
  52946. }
  52947. QuinticEase.prototype.easeInCore = function (gradient) {
  52948. return (gradient * gradient * gradient * gradient * gradient);
  52949. };
  52950. return QuinticEase;
  52951. }(EasingFunction));
  52952. BABYLON.QuinticEase = QuinticEase;
  52953. var SineEase = /** @class */ (function (_super) {
  52954. __extends(SineEase, _super);
  52955. function SineEase() {
  52956. return _super !== null && _super.apply(this, arguments) || this;
  52957. }
  52958. SineEase.prototype.easeInCore = function (gradient) {
  52959. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52960. };
  52961. return SineEase;
  52962. }(EasingFunction));
  52963. BABYLON.SineEase = SineEase;
  52964. var BezierCurveEase = /** @class */ (function (_super) {
  52965. __extends(BezierCurveEase, _super);
  52966. function BezierCurveEase(x1, y1, x2, y2) {
  52967. if (x1 === void 0) { x1 = 0; }
  52968. if (y1 === void 0) { y1 = 0; }
  52969. if (x2 === void 0) { x2 = 1; }
  52970. if (y2 === void 0) { y2 = 1; }
  52971. var _this = _super.call(this) || this;
  52972. _this.x1 = x1;
  52973. _this.y1 = y1;
  52974. _this.x2 = x2;
  52975. _this.y2 = y2;
  52976. return _this;
  52977. }
  52978. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52979. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52980. };
  52981. return BezierCurveEase;
  52982. }(EasingFunction));
  52983. BABYLON.BezierCurveEase = BezierCurveEase;
  52984. })(BABYLON || (BABYLON = {}));
  52985. //# sourceMappingURL=babylon.easing.js.map
  52986. var BABYLON;
  52987. (function (BABYLON) {
  52988. /**
  52989. * A Condition applied to an Action
  52990. */
  52991. var Condition = /** @class */ (function () {
  52992. /**
  52993. * Creates a new Condition
  52994. * @param actionManager the manager of the action the condition is applied to
  52995. */
  52996. function Condition(actionManager) {
  52997. this._actionManager = actionManager;
  52998. }
  52999. /**
  53000. * Check if the current condition is valid
  53001. * @returns a boolean
  53002. */
  53003. Condition.prototype.isValid = function () {
  53004. return true;
  53005. };
  53006. /**
  53007. * Internal only
  53008. * @hidden
  53009. */
  53010. Condition.prototype._getProperty = function (propertyPath) {
  53011. return this._actionManager._getProperty(propertyPath);
  53012. };
  53013. /**
  53014. * Internal only
  53015. * @hidden
  53016. */
  53017. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  53018. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53019. };
  53020. /**
  53021. * Serialize placeholder for child classes
  53022. * @returns the serialized object
  53023. */
  53024. Condition.prototype.serialize = function () {
  53025. };
  53026. /**
  53027. * Internal only
  53028. * @hidden
  53029. */
  53030. Condition.prototype._serialize = function (serializedCondition) {
  53031. return {
  53032. type: 2,
  53033. children: [],
  53034. name: serializedCondition.name,
  53035. properties: serializedCondition.properties
  53036. };
  53037. };
  53038. return Condition;
  53039. }());
  53040. BABYLON.Condition = Condition;
  53041. /**
  53042. * Defines specific conditional operators as extensions of Condition
  53043. */
  53044. var ValueCondition = /** @class */ (function (_super) {
  53045. __extends(ValueCondition, _super);
  53046. /**
  53047. * Creates a new ValueCondition
  53048. * @param actionManager manager for the action the condition applies to
  53049. * @param target for the action
  53050. * @param propertyPath path to specify the property of the target the conditional operator uses
  53051. * @param value the value compared by the conditional operator against the current value of the property
  53052. * @param operator the conditional operator, default ValueCondition.IsEqual
  53053. */
  53054. function ValueCondition(actionManager, target,
  53055. /** path to specify the property of the target the conditional operator uses */
  53056. propertyPath,
  53057. /** the value compared by the conditional operator against the current value of the property */
  53058. value,
  53059. /** the conditional operator, default ValueCondition.IsEqual */
  53060. operator) {
  53061. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  53062. var _this = _super.call(this, actionManager) || this;
  53063. _this.propertyPath = propertyPath;
  53064. _this.value = value;
  53065. _this.operator = operator;
  53066. _this._target = target;
  53067. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  53068. _this._property = _this._getProperty(_this.propertyPath);
  53069. return _this;
  53070. }
  53071. Object.defineProperty(ValueCondition, "IsEqual", {
  53072. /**
  53073. * returns the number for IsEqual
  53074. */
  53075. get: function () {
  53076. return ValueCondition._IsEqual;
  53077. },
  53078. enumerable: true,
  53079. configurable: true
  53080. });
  53081. Object.defineProperty(ValueCondition, "IsDifferent", {
  53082. /**
  53083. * Returns the number for IsDifferent
  53084. */
  53085. get: function () {
  53086. return ValueCondition._IsDifferent;
  53087. },
  53088. enumerable: true,
  53089. configurable: true
  53090. });
  53091. Object.defineProperty(ValueCondition, "IsGreater", {
  53092. /**
  53093. * Returns the number for IsGreater
  53094. */
  53095. get: function () {
  53096. return ValueCondition._IsGreater;
  53097. },
  53098. enumerable: true,
  53099. configurable: true
  53100. });
  53101. Object.defineProperty(ValueCondition, "IsLesser", {
  53102. /**
  53103. * Returns the number for IsLesser
  53104. */
  53105. get: function () {
  53106. return ValueCondition._IsLesser;
  53107. },
  53108. enumerable: true,
  53109. configurable: true
  53110. });
  53111. /**
  53112. * Compares the given value with the property value for the specified conditional operator
  53113. * @returns the result of the comparison
  53114. */
  53115. ValueCondition.prototype.isValid = function () {
  53116. switch (this.operator) {
  53117. case ValueCondition.IsGreater:
  53118. return this._effectiveTarget[this._property] > this.value;
  53119. case ValueCondition.IsLesser:
  53120. return this._effectiveTarget[this._property] < this.value;
  53121. case ValueCondition.IsEqual:
  53122. case ValueCondition.IsDifferent:
  53123. var check;
  53124. if (this.value.equals) {
  53125. check = this.value.equals(this._effectiveTarget[this._property]);
  53126. }
  53127. else {
  53128. check = this.value === this._effectiveTarget[this._property];
  53129. }
  53130. return this.operator === ValueCondition.IsEqual ? check : !check;
  53131. }
  53132. return false;
  53133. };
  53134. /**
  53135. * Serialize the ValueCondition into a JSON compatible object
  53136. * @returns serialization object
  53137. */
  53138. ValueCondition.prototype.serialize = function () {
  53139. return this._serialize({
  53140. name: "ValueCondition",
  53141. properties: [
  53142. BABYLON.Action._GetTargetProperty(this._target),
  53143. { name: "propertyPath", value: this.propertyPath },
  53144. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53145. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  53146. ]
  53147. });
  53148. };
  53149. /**
  53150. * Gets the name of the conditional operator for the ValueCondition
  53151. * @param operator the conditional operator
  53152. * @returns the name
  53153. */
  53154. ValueCondition.GetOperatorName = function (operator) {
  53155. switch (operator) {
  53156. case ValueCondition._IsEqual: return "IsEqual";
  53157. case ValueCondition._IsDifferent: return "IsDifferent";
  53158. case ValueCondition._IsGreater: return "IsGreater";
  53159. case ValueCondition._IsLesser: return "IsLesser";
  53160. default: return "";
  53161. }
  53162. };
  53163. /**
  53164. * Internal only
  53165. * @hidden
  53166. */
  53167. ValueCondition._IsEqual = 0;
  53168. /**
  53169. * Internal only
  53170. * @hidden
  53171. */
  53172. ValueCondition._IsDifferent = 1;
  53173. /**
  53174. * Internal only
  53175. * @hidden
  53176. */
  53177. ValueCondition._IsGreater = 2;
  53178. /**
  53179. * Internal only
  53180. * @hidden
  53181. */
  53182. ValueCondition._IsLesser = 3;
  53183. return ValueCondition;
  53184. }(Condition));
  53185. BABYLON.ValueCondition = ValueCondition;
  53186. /**
  53187. * Defines a predicate condition as an extension of Condition
  53188. */
  53189. var PredicateCondition = /** @class */ (function (_super) {
  53190. __extends(PredicateCondition, _super);
  53191. /**
  53192. * Creates a new PredicateCondition
  53193. * @param actionManager manager for the action the condition applies to
  53194. * @param predicate defines the predicate function used to validate the condition
  53195. */
  53196. function PredicateCondition(actionManager,
  53197. /** defines the predicate function used to validate the condition */
  53198. predicate) {
  53199. var _this = _super.call(this, actionManager) || this;
  53200. _this.predicate = predicate;
  53201. return _this;
  53202. }
  53203. /**
  53204. * @returns the validity of the predicate condition
  53205. */
  53206. PredicateCondition.prototype.isValid = function () {
  53207. return this.predicate();
  53208. };
  53209. return PredicateCondition;
  53210. }(Condition));
  53211. BABYLON.PredicateCondition = PredicateCondition;
  53212. /**
  53213. * Defines a state condition as an extension of Condition
  53214. */
  53215. var StateCondition = /** @class */ (function (_super) {
  53216. __extends(StateCondition, _super);
  53217. /**
  53218. * Creates a new StateCondition
  53219. * @param actionManager manager for the action the condition applies to
  53220. * @param target of the condition
  53221. * @param value to compare with target state
  53222. */
  53223. function StateCondition(actionManager, target, value) {
  53224. var _this = _super.call(this, actionManager) || this;
  53225. _this.value = value;
  53226. _this._target = target;
  53227. return _this;
  53228. }
  53229. /**
  53230. * @returns the validity of the state
  53231. */
  53232. StateCondition.prototype.isValid = function () {
  53233. return this._target.state === this.value;
  53234. };
  53235. /**
  53236. * Serialize the StateCondition into a JSON compatible object
  53237. * @returns serialization object
  53238. */
  53239. StateCondition.prototype.serialize = function () {
  53240. return this._serialize({
  53241. name: "StateCondition",
  53242. properties: [
  53243. BABYLON.Action._GetTargetProperty(this._target),
  53244. { name: "value", value: this.value }
  53245. ]
  53246. });
  53247. };
  53248. return StateCondition;
  53249. }(Condition));
  53250. BABYLON.StateCondition = StateCondition;
  53251. })(BABYLON || (BABYLON = {}));
  53252. //# sourceMappingURL=babylon.condition.js.map
  53253. var BABYLON;
  53254. (function (BABYLON) {
  53255. /**
  53256. * The action to be carried out following a trigger
  53257. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  53258. */
  53259. var Action = /** @class */ (function () {
  53260. /**
  53261. * Creates a new Action
  53262. * @param triggerOptions the trigger, with or without parameters, for the action
  53263. * @param condition an optional determinant of action
  53264. */
  53265. function Action(
  53266. /** the trigger, with or without parameters, for the action */
  53267. triggerOptions, condition) {
  53268. this.triggerOptions = triggerOptions;
  53269. /**
  53270. * An event triggered prior to action being executed.
  53271. */
  53272. this.onBeforeExecuteObservable = new BABYLON.Observable();
  53273. if (triggerOptions.parameter) {
  53274. this.trigger = triggerOptions.trigger;
  53275. this._triggerParameter = triggerOptions.parameter;
  53276. }
  53277. else {
  53278. this.trigger = triggerOptions;
  53279. }
  53280. this._nextActiveAction = this;
  53281. this._condition = condition;
  53282. }
  53283. /**
  53284. * Internal only
  53285. * @hidden
  53286. */
  53287. Action.prototype._prepare = function () {
  53288. };
  53289. /**
  53290. * Gets the trigger parameters
  53291. * @returns the trigger parameters
  53292. */
  53293. Action.prototype.getTriggerParameter = function () {
  53294. return this._triggerParameter;
  53295. };
  53296. /**
  53297. * Internal only - executes current action event
  53298. * @hidden
  53299. */
  53300. Action.prototype._executeCurrent = function (evt) {
  53301. if (this._nextActiveAction._condition) {
  53302. var condition = this._nextActiveAction._condition;
  53303. var currentRenderId = this._actionManager.getScene().getRenderId();
  53304. // We cache the current evaluation for the current frame
  53305. if (condition._evaluationId === currentRenderId) {
  53306. if (!condition._currentResult) {
  53307. return;
  53308. }
  53309. }
  53310. else {
  53311. condition._evaluationId = currentRenderId;
  53312. if (!condition.isValid()) {
  53313. condition._currentResult = false;
  53314. return;
  53315. }
  53316. condition._currentResult = true;
  53317. }
  53318. }
  53319. this.onBeforeExecuteObservable.notifyObservers(this);
  53320. this._nextActiveAction.execute(evt);
  53321. this.skipToNextActiveAction();
  53322. };
  53323. /**
  53324. * Execute placeholder for child classes
  53325. * @param evt optional action event
  53326. */
  53327. Action.prototype.execute = function (evt) {
  53328. };
  53329. /**
  53330. * Skips to next active action
  53331. */
  53332. Action.prototype.skipToNextActiveAction = function () {
  53333. if (this._nextActiveAction._child) {
  53334. if (!this._nextActiveAction._child._actionManager) {
  53335. this._nextActiveAction._child._actionManager = this._actionManager;
  53336. }
  53337. this._nextActiveAction = this._nextActiveAction._child;
  53338. }
  53339. else {
  53340. this._nextActiveAction = this;
  53341. }
  53342. };
  53343. /**
  53344. * Adds action to chain of actions, may be a DoNothingAction
  53345. * @param action defines the next action to execute
  53346. * @returns The action passed in
  53347. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53348. */
  53349. Action.prototype.then = function (action) {
  53350. this._child = action;
  53351. action._actionManager = this._actionManager;
  53352. action._prepare();
  53353. return action;
  53354. };
  53355. /**
  53356. * Internal only
  53357. * @hidden
  53358. */
  53359. Action.prototype._getProperty = function (propertyPath) {
  53360. return this._actionManager._getProperty(propertyPath);
  53361. };
  53362. /**
  53363. * Internal only
  53364. * @hidden
  53365. */
  53366. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53367. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53368. };
  53369. /**
  53370. * Serialize placeholder for child classes
  53371. * @param parent of child
  53372. * @returns the serialized object
  53373. */
  53374. Action.prototype.serialize = function (parent) {
  53375. };
  53376. /**
  53377. * Internal only called by serialize
  53378. * @hidden
  53379. */
  53380. Action.prototype._serialize = function (serializedAction, parent) {
  53381. var serializationObject = {
  53382. type: 1,
  53383. children: [],
  53384. name: serializedAction.name,
  53385. properties: serializedAction.properties || []
  53386. };
  53387. // Serialize child
  53388. if (this._child) {
  53389. this._child.serialize(serializationObject);
  53390. }
  53391. // Check if "this" has a condition
  53392. if (this._condition) {
  53393. var serializedCondition = this._condition.serialize();
  53394. serializedCondition.children.push(serializationObject);
  53395. if (parent) {
  53396. parent.children.push(serializedCondition);
  53397. }
  53398. return serializedCondition;
  53399. }
  53400. if (parent) {
  53401. parent.children.push(serializationObject);
  53402. }
  53403. return serializationObject;
  53404. };
  53405. /**
  53406. * Internal only
  53407. * @hidden
  53408. */
  53409. Action._SerializeValueAsString = function (value) {
  53410. if (typeof value === "number") {
  53411. return value.toString();
  53412. }
  53413. if (typeof value === "boolean") {
  53414. return value ? "true" : "false";
  53415. }
  53416. if (value instanceof BABYLON.Vector2) {
  53417. return value.x + ", " + value.y;
  53418. }
  53419. if (value instanceof BABYLON.Vector3) {
  53420. return value.x + ", " + value.y + ", " + value.z;
  53421. }
  53422. if (value instanceof BABYLON.Color3) {
  53423. return value.r + ", " + value.g + ", " + value.b;
  53424. }
  53425. if (value instanceof BABYLON.Color4) {
  53426. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53427. }
  53428. return value; // string
  53429. };
  53430. /**
  53431. * Internal only
  53432. * @hidden
  53433. */
  53434. Action._GetTargetProperty = function (target) {
  53435. return {
  53436. name: "target",
  53437. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53438. : target instanceof BABYLON.Light ? "LightProperties"
  53439. : target instanceof BABYLON.Camera ? "CameraProperties"
  53440. : "SceneProperties",
  53441. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53442. };
  53443. };
  53444. return Action;
  53445. }());
  53446. BABYLON.Action = Action;
  53447. })(BABYLON || (BABYLON = {}));
  53448. //# sourceMappingURL=babylon.action.js.map
  53449. var BABYLON;
  53450. (function (BABYLON) {
  53451. /**
  53452. * ActionEvent is the event being sent when an action is triggered.
  53453. */
  53454. var ActionEvent = /** @class */ (function () {
  53455. /**
  53456. * Creates a new ActionEvent
  53457. * @param source The mesh or sprite that triggered the action
  53458. * @param pointerX The X mouse cursor position at the time of the event
  53459. * @param pointerY The Y mouse cursor position at the time of the event
  53460. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53461. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53462. * @param additionalData additional data for the event
  53463. */
  53464. function ActionEvent(
  53465. /** The mesh or sprite that triggered the action */
  53466. source,
  53467. /** The X mouse cursor position at the time of the event */
  53468. pointerX,
  53469. /** The Y mouse cursor position at the time of the event */
  53470. pointerY,
  53471. /** The mesh that is currently pointed at (can be null) */
  53472. meshUnderPointer,
  53473. /** the original (browser) event that triggered the ActionEvent */
  53474. sourceEvent,
  53475. /** additional data for the event */
  53476. additionalData) {
  53477. this.source = source;
  53478. this.pointerX = pointerX;
  53479. this.pointerY = pointerY;
  53480. this.meshUnderPointer = meshUnderPointer;
  53481. this.sourceEvent = sourceEvent;
  53482. this.additionalData = additionalData;
  53483. }
  53484. /**
  53485. * Helper function to auto-create an ActionEvent from a source mesh.
  53486. * @param source The source mesh that triggered the event
  53487. * @param evt The original (browser) event
  53488. * @param additionalData additional data for the event
  53489. * @returns the new ActionEvent
  53490. */
  53491. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53492. var scene = source.getScene();
  53493. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53494. };
  53495. /**
  53496. * Helper function to auto-create an ActionEvent from a source sprite
  53497. * @param source The source sprite that triggered the event
  53498. * @param scene Scene associated with the sprite
  53499. * @param evt The original (browser) event
  53500. * @param additionalData additional data for the event
  53501. * @returns the new ActionEvent
  53502. */
  53503. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53504. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53505. };
  53506. /**
  53507. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53508. * @param scene the scene where the event occurred
  53509. * @param evt The original (browser) event
  53510. * @returns the new ActionEvent
  53511. */
  53512. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53513. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53514. };
  53515. /**
  53516. * Helper function to auto-create an ActionEvent from a primitive
  53517. * @param prim defines the target primitive
  53518. * @param pointerPos defines the pointer position
  53519. * @param evt The original (browser) event
  53520. * @param additionalData additional data for the event
  53521. * @returns the new ActionEvent
  53522. */
  53523. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53524. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53525. };
  53526. return ActionEvent;
  53527. }());
  53528. BABYLON.ActionEvent = ActionEvent;
  53529. /**
  53530. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53531. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53532. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53533. */
  53534. var ActionManager = /** @class */ (function () {
  53535. /**
  53536. * Creates a new action manager
  53537. * @param scene defines the hosting scene
  53538. */
  53539. function ActionManager(scene) {
  53540. // Members
  53541. /** Gets the list of actions */
  53542. this.actions = new Array();
  53543. /** Gets the cursor to use when hovering items */
  53544. this.hoverCursor = '';
  53545. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53546. scene._actionManagers.push(this);
  53547. }
  53548. Object.defineProperty(ActionManager, "NothingTrigger", {
  53549. /**
  53550. * Nothing
  53551. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53552. */
  53553. get: function () {
  53554. return ActionManager._NothingTrigger;
  53555. },
  53556. enumerable: true,
  53557. configurable: true
  53558. });
  53559. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53560. /**
  53561. * On pick
  53562. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53563. */
  53564. get: function () {
  53565. return ActionManager._OnPickTrigger;
  53566. },
  53567. enumerable: true,
  53568. configurable: true
  53569. });
  53570. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53571. /**
  53572. * On left pick
  53573. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53574. */
  53575. get: function () {
  53576. return ActionManager._OnLeftPickTrigger;
  53577. },
  53578. enumerable: true,
  53579. configurable: true
  53580. });
  53581. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53582. /**
  53583. * On right pick
  53584. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53585. */
  53586. get: function () {
  53587. return ActionManager._OnRightPickTrigger;
  53588. },
  53589. enumerable: true,
  53590. configurable: true
  53591. });
  53592. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53593. /**
  53594. * On center pick
  53595. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53596. */
  53597. get: function () {
  53598. return ActionManager._OnCenterPickTrigger;
  53599. },
  53600. enumerable: true,
  53601. configurable: true
  53602. });
  53603. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53604. /**
  53605. * On pick down
  53606. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53607. */
  53608. get: function () {
  53609. return ActionManager._OnPickDownTrigger;
  53610. },
  53611. enumerable: true,
  53612. configurable: true
  53613. });
  53614. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53615. /**
  53616. * On double pick
  53617. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53618. */
  53619. get: function () {
  53620. return ActionManager._OnDoublePickTrigger;
  53621. },
  53622. enumerable: true,
  53623. configurable: true
  53624. });
  53625. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53626. /**
  53627. * On pick up
  53628. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53629. */
  53630. get: function () {
  53631. return ActionManager._OnPickUpTrigger;
  53632. },
  53633. enumerable: true,
  53634. configurable: true
  53635. });
  53636. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53637. /**
  53638. * On pick out.
  53639. * This trigger will only be raised if you also declared a OnPickDown
  53640. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53641. */
  53642. get: function () {
  53643. return ActionManager._OnPickOutTrigger;
  53644. },
  53645. enumerable: true,
  53646. configurable: true
  53647. });
  53648. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53649. /**
  53650. * On long press
  53651. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53652. */
  53653. get: function () {
  53654. return ActionManager._OnLongPressTrigger;
  53655. },
  53656. enumerable: true,
  53657. configurable: true
  53658. });
  53659. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53660. /**
  53661. * On pointer over
  53662. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53663. */
  53664. get: function () {
  53665. return ActionManager._OnPointerOverTrigger;
  53666. },
  53667. enumerable: true,
  53668. configurable: true
  53669. });
  53670. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53671. /**
  53672. * On pointer out
  53673. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53674. */
  53675. get: function () {
  53676. return ActionManager._OnPointerOutTrigger;
  53677. },
  53678. enumerable: true,
  53679. configurable: true
  53680. });
  53681. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53682. /**
  53683. * On every frame
  53684. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53685. */
  53686. get: function () {
  53687. return ActionManager._OnEveryFrameTrigger;
  53688. },
  53689. enumerable: true,
  53690. configurable: true
  53691. });
  53692. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53693. /**
  53694. * On intersection enter
  53695. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53696. */
  53697. get: function () {
  53698. return ActionManager._OnIntersectionEnterTrigger;
  53699. },
  53700. enumerable: true,
  53701. configurable: true
  53702. });
  53703. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53704. /**
  53705. * On intersection exit
  53706. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53707. */
  53708. get: function () {
  53709. return ActionManager._OnIntersectionExitTrigger;
  53710. },
  53711. enumerable: true,
  53712. configurable: true
  53713. });
  53714. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53715. /**
  53716. * On key down
  53717. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53718. */
  53719. get: function () {
  53720. return ActionManager._OnKeyDownTrigger;
  53721. },
  53722. enumerable: true,
  53723. configurable: true
  53724. });
  53725. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53726. /**
  53727. * On key up
  53728. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53729. */
  53730. get: function () {
  53731. return ActionManager._OnKeyUpTrigger;
  53732. },
  53733. enumerable: true,
  53734. configurable: true
  53735. });
  53736. // Methods
  53737. /**
  53738. * Releases all associated resources
  53739. */
  53740. ActionManager.prototype.dispose = function () {
  53741. var index = this._scene._actionManagers.indexOf(this);
  53742. for (var i = 0; i < this.actions.length; i++) {
  53743. var action = this.actions[i];
  53744. ActionManager.Triggers[action.trigger]--;
  53745. if (ActionManager.Triggers[action.trigger] === 0) {
  53746. delete ActionManager.Triggers[action.trigger];
  53747. }
  53748. }
  53749. if (index > -1) {
  53750. this._scene._actionManagers.splice(index, 1);
  53751. }
  53752. };
  53753. /**
  53754. * Gets hosting scene
  53755. * @returns the hosting scene
  53756. */
  53757. ActionManager.prototype.getScene = function () {
  53758. return this._scene;
  53759. };
  53760. /**
  53761. * Does this action manager handles actions of any of the given triggers
  53762. * @param triggers defines the triggers to be tested
  53763. * @return a boolean indicating whether one (or more) of the triggers is handled
  53764. */
  53765. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53766. for (var index = 0; index < this.actions.length; index++) {
  53767. var action = this.actions[index];
  53768. if (triggers.indexOf(action.trigger) > -1) {
  53769. return true;
  53770. }
  53771. }
  53772. return false;
  53773. };
  53774. /**
  53775. * Does this action manager handles actions of a given trigger
  53776. * @param trigger defines the trigger to be tested
  53777. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53778. * @return whether the trigger is handled
  53779. */
  53780. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53781. for (var index = 0; index < this.actions.length; index++) {
  53782. var action = this.actions[index];
  53783. if (action.trigger === trigger) {
  53784. if (parameterPredicate) {
  53785. if (parameterPredicate(action.getTriggerParameter())) {
  53786. return true;
  53787. }
  53788. }
  53789. else {
  53790. return true;
  53791. }
  53792. }
  53793. }
  53794. return false;
  53795. };
  53796. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53797. /**
  53798. * Does this action manager has pointer triggers
  53799. */
  53800. get: function () {
  53801. for (var index = 0; index < this.actions.length; index++) {
  53802. var action = this.actions[index];
  53803. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53804. return true;
  53805. }
  53806. }
  53807. return false;
  53808. },
  53809. enumerable: true,
  53810. configurable: true
  53811. });
  53812. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53813. /**
  53814. * Does this action manager has pick triggers
  53815. */
  53816. get: function () {
  53817. for (var index = 0; index < this.actions.length; index++) {
  53818. var action = this.actions[index];
  53819. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53820. return true;
  53821. }
  53822. }
  53823. return false;
  53824. },
  53825. enumerable: true,
  53826. configurable: true
  53827. });
  53828. Object.defineProperty(ActionManager, "HasTriggers", {
  53829. /**
  53830. * Does exist one action manager with at least one trigger
  53831. **/
  53832. get: function () {
  53833. for (var t in ActionManager.Triggers) {
  53834. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53835. return true;
  53836. }
  53837. }
  53838. return false;
  53839. },
  53840. enumerable: true,
  53841. configurable: true
  53842. });
  53843. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53844. /**
  53845. * Does exist one action manager with at least one pick trigger
  53846. **/
  53847. get: function () {
  53848. for (var t in ActionManager.Triggers) {
  53849. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53850. var t_int = parseInt(t);
  53851. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53852. return true;
  53853. }
  53854. }
  53855. }
  53856. return false;
  53857. },
  53858. enumerable: true,
  53859. configurable: true
  53860. });
  53861. /**
  53862. * Does exist one action manager that handles actions of a given trigger
  53863. * @param trigger defines the trigger to be tested
  53864. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53865. **/
  53866. ActionManager.HasSpecificTrigger = function (trigger) {
  53867. for (var t in ActionManager.Triggers) {
  53868. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53869. var t_int = parseInt(t);
  53870. if (t_int === trigger) {
  53871. return true;
  53872. }
  53873. }
  53874. }
  53875. return false;
  53876. };
  53877. /**
  53878. * Registers an action to this action manager
  53879. * @param action defines the action to be registered
  53880. * @return the action amended (prepared) after registration
  53881. */
  53882. ActionManager.prototype.registerAction = function (action) {
  53883. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53884. if (this.getScene().actionManager !== this) {
  53885. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53886. return null;
  53887. }
  53888. }
  53889. this.actions.push(action);
  53890. if (ActionManager.Triggers[action.trigger]) {
  53891. ActionManager.Triggers[action.trigger]++;
  53892. }
  53893. else {
  53894. ActionManager.Triggers[action.trigger] = 1;
  53895. }
  53896. action._actionManager = this;
  53897. action._prepare();
  53898. return action;
  53899. };
  53900. /**
  53901. * Unregisters an action to this action manager
  53902. * @param action defines the action to be unregistered
  53903. * @return a boolean indicating whether the action has been unregistered
  53904. */
  53905. ActionManager.prototype.unregisterAction = function (action) {
  53906. var index = this.actions.indexOf(action);
  53907. if (index !== -1) {
  53908. this.actions.splice(index, 1);
  53909. ActionManager.Triggers[action.trigger] -= 1;
  53910. if (ActionManager.Triggers[action.trigger] === 0) {
  53911. delete ActionManager.Triggers[action.trigger];
  53912. }
  53913. delete action._actionManager;
  53914. return true;
  53915. }
  53916. return false;
  53917. };
  53918. /**
  53919. * Process a specific trigger
  53920. * @param trigger defines the trigger to process
  53921. * @param evt defines the event details to be processed
  53922. */
  53923. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53924. for (var index = 0; index < this.actions.length; index++) {
  53925. var action = this.actions[index];
  53926. if (action.trigger === trigger) {
  53927. if (evt) {
  53928. if (trigger === ActionManager.OnKeyUpTrigger
  53929. || trigger === ActionManager.OnKeyDownTrigger) {
  53930. var parameter = action.getTriggerParameter();
  53931. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53932. if (!parameter.toLowerCase) {
  53933. continue;
  53934. }
  53935. var lowerCase = parameter.toLowerCase();
  53936. if (lowerCase !== evt.sourceEvent.key) {
  53937. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53938. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53939. if (actualkey !== lowerCase) {
  53940. continue;
  53941. }
  53942. }
  53943. }
  53944. }
  53945. }
  53946. action._executeCurrent(evt);
  53947. }
  53948. }
  53949. };
  53950. /** @hidden */
  53951. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53952. var properties = propertyPath.split(".");
  53953. for (var index = 0; index < properties.length - 1; index++) {
  53954. target = target[properties[index]];
  53955. }
  53956. return target;
  53957. };
  53958. /** @hidden */
  53959. ActionManager.prototype._getProperty = function (propertyPath) {
  53960. var properties = propertyPath.split(".");
  53961. return properties[properties.length - 1];
  53962. };
  53963. /**
  53964. * Serialize this manager to a JSON object
  53965. * @param name defines the property name to store this manager
  53966. * @returns a JSON representation of this manager
  53967. */
  53968. ActionManager.prototype.serialize = function (name) {
  53969. var root = {
  53970. children: new Array(),
  53971. name: name,
  53972. type: 3,
  53973. properties: new Array() // Empty for root but required
  53974. };
  53975. for (var i = 0; i < this.actions.length; i++) {
  53976. var triggerObject = {
  53977. type: 0,
  53978. children: new Array(),
  53979. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53980. properties: new Array()
  53981. };
  53982. var triggerOptions = this.actions[i].triggerOptions;
  53983. if (triggerOptions && typeof triggerOptions !== "number") {
  53984. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53985. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53986. }
  53987. else {
  53988. var parameter = {};
  53989. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53990. if (triggerOptions.parameter.mesh) {
  53991. parameter._meshId = triggerOptions.parameter.mesh.id;
  53992. }
  53993. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53994. }
  53995. }
  53996. // Serialize child action, recursively
  53997. this.actions[i].serialize(triggerObject);
  53998. // Add serialized trigger
  53999. root.children.push(triggerObject);
  54000. }
  54001. return root;
  54002. };
  54003. /**
  54004. * Creates a new ActionManager from a JSON data
  54005. * @param parsedActions defines the JSON data to read from
  54006. * @param object defines the hosting mesh
  54007. * @param scene defines the hosting scene
  54008. */
  54009. ActionManager.Parse = function (parsedActions, object, scene) {
  54010. var actionManager = new ActionManager(scene);
  54011. if (object === null)
  54012. scene.actionManager = actionManager;
  54013. else
  54014. object.actionManager = actionManager;
  54015. // instanciate a new object
  54016. var instanciate = function (name, params) {
  54017. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  54018. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  54019. newInstance.constructor.apply(newInstance, params);
  54020. return newInstance;
  54021. };
  54022. var parseParameter = function (name, value, target, propertyPath) {
  54023. if (propertyPath === null) {
  54024. // String, boolean or float
  54025. var floatValue = parseFloat(value);
  54026. if (value === "true" || value === "false")
  54027. return value === "true";
  54028. else
  54029. return isNaN(floatValue) ? value : floatValue;
  54030. }
  54031. var effectiveTarget = propertyPath.split(".");
  54032. var values = value.split(",");
  54033. // Get effective Target
  54034. for (var i = 0; i < effectiveTarget.length; i++) {
  54035. target = target[effectiveTarget[i]];
  54036. }
  54037. // Return appropriate value with its type
  54038. if (typeof (target) === "boolean")
  54039. return values[0] === "true";
  54040. if (typeof (target) === "string")
  54041. return values[0];
  54042. // Parameters with multiple values such as Vector3 etc.
  54043. var split = new Array();
  54044. for (var i = 0; i < values.length; i++)
  54045. split.push(parseFloat(values[i]));
  54046. if (target instanceof BABYLON.Vector3)
  54047. return BABYLON.Vector3.FromArray(split);
  54048. if (target instanceof BABYLON.Vector4)
  54049. return BABYLON.Vector4.FromArray(split);
  54050. if (target instanceof BABYLON.Color3)
  54051. return BABYLON.Color3.FromArray(split);
  54052. if (target instanceof BABYLON.Color4)
  54053. return BABYLON.Color4.FromArray(split);
  54054. return parseFloat(values[0]);
  54055. };
  54056. // traverse graph per trigger
  54057. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  54058. if (combineArray === void 0) { combineArray = null; }
  54059. if (parsedAction.detached)
  54060. return;
  54061. var parameters = new Array();
  54062. var target = null;
  54063. var propertyPath = null;
  54064. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  54065. // Parameters
  54066. if (parsedAction.type === 2)
  54067. parameters.push(actionManager);
  54068. else
  54069. parameters.push(trigger);
  54070. if (combine) {
  54071. var actions = new Array();
  54072. for (var j = 0; j < parsedAction.combine.length; j++) {
  54073. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  54074. }
  54075. parameters.push(actions);
  54076. }
  54077. else {
  54078. for (var i = 0; i < parsedAction.properties.length; i++) {
  54079. var value = parsedAction.properties[i].value;
  54080. var name = parsedAction.properties[i].name;
  54081. var targetType = parsedAction.properties[i].targetType;
  54082. if (name === "target")
  54083. if (targetType !== null && targetType === "SceneProperties")
  54084. value = target = scene;
  54085. else
  54086. value = target = scene.getNodeByName(value);
  54087. else if (name === "parent")
  54088. value = scene.getNodeByName(value);
  54089. else if (name === "sound")
  54090. value = scene.getSoundByName(value);
  54091. else if (name !== "propertyPath") {
  54092. if (parsedAction.type === 2 && name === "operator")
  54093. value = BABYLON.ValueCondition[value];
  54094. else
  54095. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  54096. }
  54097. else {
  54098. propertyPath = value;
  54099. }
  54100. parameters.push(value);
  54101. }
  54102. }
  54103. if (combineArray === null) {
  54104. parameters.push(condition);
  54105. }
  54106. else {
  54107. parameters.push(null);
  54108. }
  54109. // If interpolate value action
  54110. if (parsedAction.name === "InterpolateValueAction") {
  54111. var param = parameters[parameters.length - 2];
  54112. parameters[parameters.length - 1] = param;
  54113. parameters[parameters.length - 2] = condition;
  54114. }
  54115. // Action or condition(s) and not CombineAction
  54116. var newAction = instanciate(parsedAction.name, parameters);
  54117. if (newAction instanceof BABYLON.Condition && condition !== null) {
  54118. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  54119. if (action)
  54120. action.then(nothing);
  54121. else
  54122. actionManager.registerAction(nothing);
  54123. action = nothing;
  54124. }
  54125. if (combineArray === null) {
  54126. if (newAction instanceof BABYLON.Condition) {
  54127. condition = newAction;
  54128. newAction = action;
  54129. }
  54130. else {
  54131. condition = null;
  54132. if (action)
  54133. action.then(newAction);
  54134. else
  54135. actionManager.registerAction(newAction);
  54136. }
  54137. }
  54138. else {
  54139. combineArray.push(newAction);
  54140. }
  54141. for (var i = 0; i < parsedAction.children.length; i++)
  54142. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  54143. };
  54144. // triggers
  54145. for (var i = 0; i < parsedActions.children.length; i++) {
  54146. var triggerParams;
  54147. var trigger = parsedActions.children[i];
  54148. if (trigger.properties.length > 0) {
  54149. var param = trigger.properties[0].value;
  54150. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  54151. if (value._meshId) {
  54152. value.mesh = scene.getMeshByID(value._meshId);
  54153. }
  54154. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  54155. }
  54156. else
  54157. triggerParams = ActionManager[trigger.name];
  54158. for (var j = 0; j < trigger.children.length; j++) {
  54159. if (!trigger.detached)
  54160. traverse(trigger.children[j], triggerParams, null, null);
  54161. }
  54162. }
  54163. };
  54164. /**
  54165. * Get a trigger name by index
  54166. * @param trigger defines the trigger index
  54167. * @returns a trigger name
  54168. */
  54169. ActionManager.GetTriggerName = function (trigger) {
  54170. switch (trigger) {
  54171. case 0: return "NothingTrigger";
  54172. case 1: return "OnPickTrigger";
  54173. case 2: return "OnLeftPickTrigger";
  54174. case 3: return "OnRightPickTrigger";
  54175. case 4: return "OnCenterPickTrigger";
  54176. case 5: return "OnPickDownTrigger";
  54177. case 6: return "OnPickUpTrigger";
  54178. case 7: return "OnLongPressTrigger";
  54179. case 8: return "OnPointerOverTrigger";
  54180. case 9: return "OnPointerOutTrigger";
  54181. case 10: return "OnEveryFrameTrigger";
  54182. case 11: return "OnIntersectionEnterTrigger";
  54183. case 12: return "OnIntersectionExitTrigger";
  54184. case 13: return "OnKeyDownTrigger";
  54185. case 14: return "OnKeyUpTrigger";
  54186. case 15: return "OnPickOutTrigger";
  54187. default: return "";
  54188. }
  54189. };
  54190. // Statics
  54191. ActionManager._NothingTrigger = 0;
  54192. ActionManager._OnPickTrigger = 1;
  54193. ActionManager._OnLeftPickTrigger = 2;
  54194. ActionManager._OnRightPickTrigger = 3;
  54195. ActionManager._OnCenterPickTrigger = 4;
  54196. ActionManager._OnPickDownTrigger = 5;
  54197. ActionManager._OnDoublePickTrigger = 6;
  54198. ActionManager._OnPickUpTrigger = 7;
  54199. ActionManager._OnLongPressTrigger = 8;
  54200. ActionManager._OnPointerOverTrigger = 9;
  54201. ActionManager._OnPointerOutTrigger = 10;
  54202. ActionManager._OnEveryFrameTrigger = 11;
  54203. ActionManager._OnIntersectionEnterTrigger = 12;
  54204. ActionManager._OnIntersectionExitTrigger = 13;
  54205. ActionManager._OnKeyDownTrigger = 14;
  54206. ActionManager._OnKeyUpTrigger = 15;
  54207. ActionManager._OnPickOutTrigger = 16;
  54208. /** Gets the list of active triggers */
  54209. ActionManager.Triggers = {};
  54210. return ActionManager;
  54211. }());
  54212. BABYLON.ActionManager = ActionManager;
  54213. })(BABYLON || (BABYLON = {}));
  54214. //# sourceMappingURL=babylon.actionManager.js.map
  54215. var BABYLON;
  54216. (function (BABYLON) {
  54217. var InterpolateValueAction = /** @class */ (function (_super) {
  54218. __extends(InterpolateValueAction, _super);
  54219. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  54220. if (duration === void 0) { duration = 1000; }
  54221. var _this = _super.call(this, triggerOptions, condition) || this;
  54222. _this.propertyPath = propertyPath;
  54223. _this.value = value;
  54224. _this.duration = duration;
  54225. _this.stopOtherAnimations = stopOtherAnimations;
  54226. _this.onInterpolationDone = onInterpolationDone;
  54227. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  54228. _this._target = _this._effectiveTarget = target;
  54229. return _this;
  54230. }
  54231. InterpolateValueAction.prototype._prepare = function () {
  54232. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54233. this._property = this._getProperty(this.propertyPath);
  54234. };
  54235. InterpolateValueAction.prototype.execute = function () {
  54236. var _this = this;
  54237. var scene = this._actionManager.getScene();
  54238. var keys = [
  54239. {
  54240. frame: 0,
  54241. value: this._effectiveTarget[this._property]
  54242. }, {
  54243. frame: 100,
  54244. value: this.value
  54245. }
  54246. ];
  54247. var dataType;
  54248. if (typeof this.value === "number") {
  54249. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  54250. }
  54251. else if (this.value instanceof BABYLON.Color3) {
  54252. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  54253. }
  54254. else if (this.value instanceof BABYLON.Vector3) {
  54255. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  54256. }
  54257. else if (this.value instanceof BABYLON.Matrix) {
  54258. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  54259. }
  54260. else if (this.value instanceof BABYLON.Quaternion) {
  54261. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  54262. }
  54263. else {
  54264. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  54265. return;
  54266. }
  54267. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  54268. animation.setKeys(keys);
  54269. if (this.stopOtherAnimations) {
  54270. scene.stopAnimation(this._effectiveTarget);
  54271. }
  54272. var wrapper = function () {
  54273. _this.onInterpolationDoneObservable.notifyObservers(_this);
  54274. if (_this.onInterpolationDone) {
  54275. _this.onInterpolationDone();
  54276. }
  54277. };
  54278. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  54279. };
  54280. InterpolateValueAction.prototype.serialize = function (parent) {
  54281. return _super.prototype._serialize.call(this, {
  54282. name: "InterpolateValueAction",
  54283. properties: [
  54284. BABYLON.Action._GetTargetProperty(this._target),
  54285. { name: "propertyPath", value: this.propertyPath },
  54286. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54287. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  54288. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  54289. ]
  54290. }, parent);
  54291. };
  54292. return InterpolateValueAction;
  54293. }(BABYLON.Action));
  54294. BABYLON.InterpolateValueAction = InterpolateValueAction;
  54295. })(BABYLON || (BABYLON = {}));
  54296. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  54297. var BABYLON;
  54298. (function (BABYLON) {
  54299. var SwitchBooleanAction = /** @class */ (function (_super) {
  54300. __extends(SwitchBooleanAction, _super);
  54301. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  54302. var _this = _super.call(this, triggerOptions, condition) || this;
  54303. _this.propertyPath = propertyPath;
  54304. _this._target = _this._effectiveTarget = target;
  54305. return _this;
  54306. }
  54307. SwitchBooleanAction.prototype._prepare = function () {
  54308. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54309. this._property = this._getProperty(this.propertyPath);
  54310. };
  54311. SwitchBooleanAction.prototype.execute = function () {
  54312. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  54313. };
  54314. SwitchBooleanAction.prototype.serialize = function (parent) {
  54315. return _super.prototype._serialize.call(this, {
  54316. name: "SwitchBooleanAction",
  54317. properties: [
  54318. BABYLON.Action._GetTargetProperty(this._target),
  54319. { name: "propertyPath", value: this.propertyPath }
  54320. ]
  54321. }, parent);
  54322. };
  54323. return SwitchBooleanAction;
  54324. }(BABYLON.Action));
  54325. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  54326. var SetStateAction = /** @class */ (function (_super) {
  54327. __extends(SetStateAction, _super);
  54328. function SetStateAction(triggerOptions, target, value, condition) {
  54329. var _this = _super.call(this, triggerOptions, condition) || this;
  54330. _this.value = value;
  54331. _this._target = target;
  54332. return _this;
  54333. }
  54334. SetStateAction.prototype.execute = function () {
  54335. this._target.state = this.value;
  54336. };
  54337. SetStateAction.prototype.serialize = function (parent) {
  54338. return _super.prototype._serialize.call(this, {
  54339. name: "SetStateAction",
  54340. properties: [
  54341. BABYLON.Action._GetTargetProperty(this._target),
  54342. { name: "value", value: this.value }
  54343. ]
  54344. }, parent);
  54345. };
  54346. return SetStateAction;
  54347. }(BABYLON.Action));
  54348. BABYLON.SetStateAction = SetStateAction;
  54349. var SetValueAction = /** @class */ (function (_super) {
  54350. __extends(SetValueAction, _super);
  54351. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54352. var _this = _super.call(this, triggerOptions, condition) || this;
  54353. _this.propertyPath = propertyPath;
  54354. _this.value = value;
  54355. _this._target = _this._effectiveTarget = target;
  54356. return _this;
  54357. }
  54358. SetValueAction.prototype._prepare = function () {
  54359. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54360. this._property = this._getProperty(this.propertyPath);
  54361. };
  54362. SetValueAction.prototype.execute = function () {
  54363. this._effectiveTarget[this._property] = this.value;
  54364. if (this._target.markAsDirty) {
  54365. this._target.markAsDirty(this._property);
  54366. }
  54367. };
  54368. SetValueAction.prototype.serialize = function (parent) {
  54369. return _super.prototype._serialize.call(this, {
  54370. name: "SetValueAction",
  54371. properties: [
  54372. BABYLON.Action._GetTargetProperty(this._target),
  54373. { name: "propertyPath", value: this.propertyPath },
  54374. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54375. ]
  54376. }, parent);
  54377. };
  54378. return SetValueAction;
  54379. }(BABYLON.Action));
  54380. BABYLON.SetValueAction = SetValueAction;
  54381. var IncrementValueAction = /** @class */ (function (_super) {
  54382. __extends(IncrementValueAction, _super);
  54383. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54384. var _this = _super.call(this, triggerOptions, condition) || this;
  54385. _this.propertyPath = propertyPath;
  54386. _this.value = value;
  54387. _this._target = _this._effectiveTarget = target;
  54388. return _this;
  54389. }
  54390. IncrementValueAction.prototype._prepare = function () {
  54391. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54392. this._property = this._getProperty(this.propertyPath);
  54393. if (typeof this._effectiveTarget[this._property] !== "number") {
  54394. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54395. }
  54396. };
  54397. IncrementValueAction.prototype.execute = function () {
  54398. this._effectiveTarget[this._property] += this.value;
  54399. if (this._target.markAsDirty) {
  54400. this._target.markAsDirty(this._property);
  54401. }
  54402. };
  54403. IncrementValueAction.prototype.serialize = function (parent) {
  54404. return _super.prototype._serialize.call(this, {
  54405. name: "IncrementValueAction",
  54406. properties: [
  54407. BABYLON.Action._GetTargetProperty(this._target),
  54408. { name: "propertyPath", value: this.propertyPath },
  54409. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54410. ]
  54411. }, parent);
  54412. };
  54413. return IncrementValueAction;
  54414. }(BABYLON.Action));
  54415. BABYLON.IncrementValueAction = IncrementValueAction;
  54416. var PlayAnimationAction = /** @class */ (function (_super) {
  54417. __extends(PlayAnimationAction, _super);
  54418. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54419. var _this = _super.call(this, triggerOptions, condition) || this;
  54420. _this.from = from;
  54421. _this.to = to;
  54422. _this.loop = loop;
  54423. _this._target = target;
  54424. return _this;
  54425. }
  54426. PlayAnimationAction.prototype._prepare = function () {
  54427. };
  54428. PlayAnimationAction.prototype.execute = function () {
  54429. var scene = this._actionManager.getScene();
  54430. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54431. };
  54432. PlayAnimationAction.prototype.serialize = function (parent) {
  54433. return _super.prototype._serialize.call(this, {
  54434. name: "PlayAnimationAction",
  54435. properties: [
  54436. BABYLON.Action._GetTargetProperty(this._target),
  54437. { name: "from", value: String(this.from) },
  54438. { name: "to", value: String(this.to) },
  54439. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54440. ]
  54441. }, parent);
  54442. };
  54443. return PlayAnimationAction;
  54444. }(BABYLON.Action));
  54445. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54446. var StopAnimationAction = /** @class */ (function (_super) {
  54447. __extends(StopAnimationAction, _super);
  54448. function StopAnimationAction(triggerOptions, target, condition) {
  54449. var _this = _super.call(this, triggerOptions, condition) || this;
  54450. _this._target = target;
  54451. return _this;
  54452. }
  54453. StopAnimationAction.prototype._prepare = function () {
  54454. };
  54455. StopAnimationAction.prototype.execute = function () {
  54456. var scene = this._actionManager.getScene();
  54457. scene.stopAnimation(this._target);
  54458. };
  54459. StopAnimationAction.prototype.serialize = function (parent) {
  54460. return _super.prototype._serialize.call(this, {
  54461. name: "StopAnimationAction",
  54462. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54463. }, parent);
  54464. };
  54465. return StopAnimationAction;
  54466. }(BABYLON.Action));
  54467. BABYLON.StopAnimationAction = StopAnimationAction;
  54468. var DoNothingAction = /** @class */ (function (_super) {
  54469. __extends(DoNothingAction, _super);
  54470. function DoNothingAction(triggerOptions, condition) {
  54471. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54472. return _super.call(this, triggerOptions, condition) || this;
  54473. }
  54474. DoNothingAction.prototype.execute = function () {
  54475. };
  54476. DoNothingAction.prototype.serialize = function (parent) {
  54477. return _super.prototype._serialize.call(this, {
  54478. name: "DoNothingAction",
  54479. properties: []
  54480. }, parent);
  54481. };
  54482. return DoNothingAction;
  54483. }(BABYLON.Action));
  54484. BABYLON.DoNothingAction = DoNothingAction;
  54485. var CombineAction = /** @class */ (function (_super) {
  54486. __extends(CombineAction, _super);
  54487. function CombineAction(triggerOptions, children, condition) {
  54488. var _this = _super.call(this, triggerOptions, condition) || this;
  54489. _this.children = children;
  54490. return _this;
  54491. }
  54492. CombineAction.prototype._prepare = function () {
  54493. for (var index = 0; index < this.children.length; index++) {
  54494. this.children[index]._actionManager = this._actionManager;
  54495. this.children[index]._prepare();
  54496. }
  54497. };
  54498. CombineAction.prototype.execute = function (evt) {
  54499. for (var index = 0; index < this.children.length; index++) {
  54500. this.children[index].execute(evt);
  54501. }
  54502. };
  54503. CombineAction.prototype.serialize = function (parent) {
  54504. var serializationObject = _super.prototype._serialize.call(this, {
  54505. name: "CombineAction",
  54506. properties: [],
  54507. combine: []
  54508. }, parent);
  54509. for (var i = 0; i < this.children.length; i++) {
  54510. serializationObject.combine.push(this.children[i].serialize(null));
  54511. }
  54512. return serializationObject;
  54513. };
  54514. return CombineAction;
  54515. }(BABYLON.Action));
  54516. BABYLON.CombineAction = CombineAction;
  54517. var ExecuteCodeAction = /** @class */ (function (_super) {
  54518. __extends(ExecuteCodeAction, _super);
  54519. function ExecuteCodeAction(triggerOptions, func, condition) {
  54520. var _this = _super.call(this, triggerOptions, condition) || this;
  54521. _this.func = func;
  54522. return _this;
  54523. }
  54524. ExecuteCodeAction.prototype.execute = function (evt) {
  54525. this.func(evt);
  54526. };
  54527. return ExecuteCodeAction;
  54528. }(BABYLON.Action));
  54529. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54530. var SetParentAction = /** @class */ (function (_super) {
  54531. __extends(SetParentAction, _super);
  54532. function SetParentAction(triggerOptions, target, parent, condition) {
  54533. var _this = _super.call(this, triggerOptions, condition) || this;
  54534. _this._target = target;
  54535. _this._parent = parent;
  54536. return _this;
  54537. }
  54538. SetParentAction.prototype._prepare = function () {
  54539. };
  54540. SetParentAction.prototype.execute = function () {
  54541. if (this._target.parent === this._parent) {
  54542. return;
  54543. }
  54544. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54545. invertParentWorldMatrix.invert();
  54546. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54547. this._target.parent = this._parent;
  54548. };
  54549. SetParentAction.prototype.serialize = function (parent) {
  54550. return _super.prototype._serialize.call(this, {
  54551. name: "SetParentAction",
  54552. properties: [
  54553. BABYLON.Action._GetTargetProperty(this._target),
  54554. BABYLON.Action._GetTargetProperty(this._parent),
  54555. ]
  54556. }, parent);
  54557. };
  54558. return SetParentAction;
  54559. }(BABYLON.Action));
  54560. BABYLON.SetParentAction = SetParentAction;
  54561. var PlaySoundAction = /** @class */ (function (_super) {
  54562. __extends(PlaySoundAction, _super);
  54563. function PlaySoundAction(triggerOptions, sound, condition) {
  54564. var _this = _super.call(this, triggerOptions, condition) || this;
  54565. _this._sound = sound;
  54566. return _this;
  54567. }
  54568. PlaySoundAction.prototype._prepare = function () {
  54569. };
  54570. PlaySoundAction.prototype.execute = function () {
  54571. if (this._sound !== undefined)
  54572. this._sound.play();
  54573. };
  54574. PlaySoundAction.prototype.serialize = function (parent) {
  54575. return _super.prototype._serialize.call(this, {
  54576. name: "PlaySoundAction",
  54577. properties: [{ name: "sound", value: this._sound.name }]
  54578. }, parent);
  54579. };
  54580. return PlaySoundAction;
  54581. }(BABYLON.Action));
  54582. BABYLON.PlaySoundAction = PlaySoundAction;
  54583. var StopSoundAction = /** @class */ (function (_super) {
  54584. __extends(StopSoundAction, _super);
  54585. function StopSoundAction(triggerOptions, sound, condition) {
  54586. var _this = _super.call(this, triggerOptions, condition) || this;
  54587. _this._sound = sound;
  54588. return _this;
  54589. }
  54590. StopSoundAction.prototype._prepare = function () {
  54591. };
  54592. StopSoundAction.prototype.execute = function () {
  54593. if (this._sound !== undefined)
  54594. this._sound.stop();
  54595. };
  54596. StopSoundAction.prototype.serialize = function (parent) {
  54597. return _super.prototype._serialize.call(this, {
  54598. name: "StopSoundAction",
  54599. properties: [{ name: "sound", value: this._sound.name }]
  54600. }, parent);
  54601. };
  54602. return StopSoundAction;
  54603. }(BABYLON.Action));
  54604. BABYLON.StopSoundAction = StopSoundAction;
  54605. })(BABYLON || (BABYLON = {}));
  54606. //# sourceMappingURL=babylon.directActions.js.map
  54607. var BABYLON;
  54608. (function (BABYLON) {
  54609. var SpriteManager = /** @class */ (function () {
  54610. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54611. if (epsilon === void 0) { epsilon = 0.01; }
  54612. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54613. this.name = name;
  54614. this.sprites = new Array();
  54615. this.renderingGroupId = 0;
  54616. this.layerMask = 0x0FFFFFFF;
  54617. this.fogEnabled = true;
  54618. this.isPickable = false;
  54619. /**
  54620. * An event triggered when the manager is disposed.
  54621. */
  54622. this.onDisposeObservable = new BABYLON.Observable();
  54623. this._vertexBuffers = {};
  54624. this._capacity = capacity;
  54625. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54626. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54627. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54628. if (cellSize.width && cellSize.height) {
  54629. this.cellWidth = cellSize.width;
  54630. this.cellHeight = cellSize.height;
  54631. }
  54632. else if (cellSize !== undefined) {
  54633. this.cellWidth = cellSize;
  54634. this.cellHeight = cellSize;
  54635. }
  54636. else {
  54637. return;
  54638. }
  54639. this._epsilon = epsilon;
  54640. this._scene = scene;
  54641. this._scene.spriteManagers.push(this);
  54642. var indices = [];
  54643. var index = 0;
  54644. for (var count = 0; count < capacity; count++) {
  54645. indices.push(index);
  54646. indices.push(index + 1);
  54647. indices.push(index + 2);
  54648. indices.push(index);
  54649. indices.push(index + 2);
  54650. indices.push(index + 3);
  54651. index += 4;
  54652. }
  54653. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54654. // VBO
  54655. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54656. this._vertexData = new Float32Array(capacity * 16 * 4);
  54657. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54658. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54659. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54660. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54661. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54662. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54663. this._vertexBuffers["options"] = options;
  54664. this._vertexBuffers["cellInfo"] = cellInfo;
  54665. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54666. // Effects
  54667. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54668. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54669. }
  54670. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54671. set: function (callback) {
  54672. if (this._onDisposeObserver) {
  54673. this.onDisposeObservable.remove(this._onDisposeObserver);
  54674. }
  54675. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54676. },
  54677. enumerable: true,
  54678. configurable: true
  54679. });
  54680. Object.defineProperty(SpriteManager.prototype, "texture", {
  54681. get: function () {
  54682. return this._spriteTexture;
  54683. },
  54684. set: function (value) {
  54685. this._spriteTexture = value;
  54686. },
  54687. enumerable: true,
  54688. configurable: true
  54689. });
  54690. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54691. var arrayOffset = index * 16;
  54692. if (offsetX === 0)
  54693. offsetX = this._epsilon;
  54694. else if (offsetX === 1)
  54695. offsetX = 1 - this._epsilon;
  54696. if (offsetY === 0)
  54697. offsetY = this._epsilon;
  54698. else if (offsetY === 1)
  54699. offsetY = 1 - this._epsilon;
  54700. this._vertexData[arrayOffset] = sprite.position.x;
  54701. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54702. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54703. this._vertexData[arrayOffset + 3] = sprite.angle;
  54704. this._vertexData[arrayOffset + 4] = sprite.width;
  54705. this._vertexData[arrayOffset + 5] = sprite.height;
  54706. this._vertexData[arrayOffset + 6] = offsetX;
  54707. this._vertexData[arrayOffset + 7] = offsetY;
  54708. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54709. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54710. var offset = (sprite.cellIndex / rowSize) >> 0;
  54711. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54712. this._vertexData[arrayOffset + 11] = offset;
  54713. // Color
  54714. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54715. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54716. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54717. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54718. };
  54719. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54720. var count = Math.min(this._capacity, this.sprites.length);
  54721. var min = BABYLON.Vector3.Zero();
  54722. var max = BABYLON.Vector3.Zero();
  54723. var distance = Number.MAX_VALUE;
  54724. var currentSprite = null;
  54725. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54726. var cameraView = camera.getViewMatrix();
  54727. for (var index = 0; index < count; index++) {
  54728. var sprite = this.sprites[index];
  54729. if (!sprite) {
  54730. continue;
  54731. }
  54732. if (predicate) {
  54733. if (!predicate(sprite)) {
  54734. continue;
  54735. }
  54736. }
  54737. else if (!sprite.isPickable) {
  54738. continue;
  54739. }
  54740. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54741. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54742. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54743. if (ray.intersectsBoxMinMax(min, max)) {
  54744. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54745. if (distance > currentDistance) {
  54746. distance = currentDistance;
  54747. currentSprite = sprite;
  54748. if (fastCheck) {
  54749. break;
  54750. }
  54751. }
  54752. }
  54753. }
  54754. if (currentSprite) {
  54755. var result = new BABYLON.PickingInfo();
  54756. result.hit = true;
  54757. result.pickedSprite = currentSprite;
  54758. result.distance = distance;
  54759. return result;
  54760. }
  54761. return null;
  54762. };
  54763. SpriteManager.prototype.render = function () {
  54764. // Check
  54765. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54766. return;
  54767. var engine = this._scene.getEngine();
  54768. var baseSize = this._spriteTexture.getBaseSize();
  54769. // Sprites
  54770. var deltaTime = engine.getDeltaTime();
  54771. var max = Math.min(this._capacity, this.sprites.length);
  54772. var rowSize = baseSize.width / this.cellWidth;
  54773. var offset = 0;
  54774. for (var index = 0; index < max; index++) {
  54775. var sprite = this.sprites[index];
  54776. if (!sprite) {
  54777. continue;
  54778. }
  54779. sprite._animate(deltaTime);
  54780. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54781. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54782. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54783. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54784. }
  54785. this._buffer.update(this._vertexData);
  54786. // Render
  54787. var effect = this._effectBase;
  54788. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54789. effect = this._effectFog;
  54790. }
  54791. engine.enableEffect(effect);
  54792. var viewMatrix = this._scene.getViewMatrix();
  54793. effect.setTexture("diffuseSampler", this._spriteTexture);
  54794. effect.setMatrix("view", viewMatrix);
  54795. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54796. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54797. // Fog
  54798. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54799. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54800. effect.setColor3("vFogColor", this._scene.fogColor);
  54801. }
  54802. // VBOs
  54803. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54804. // Draw order
  54805. engine.setDepthFunctionToLessOrEqual();
  54806. effect.setBool("alphaTest", true);
  54807. engine.setColorWrite(false);
  54808. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54809. engine.setColorWrite(true);
  54810. effect.setBool("alphaTest", false);
  54811. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54812. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54813. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54814. };
  54815. SpriteManager.prototype.dispose = function () {
  54816. if (this._buffer) {
  54817. this._buffer.dispose();
  54818. this._buffer = null;
  54819. }
  54820. if (this._indexBuffer) {
  54821. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54822. this._indexBuffer = null;
  54823. }
  54824. if (this._spriteTexture) {
  54825. this._spriteTexture.dispose();
  54826. this._spriteTexture = null;
  54827. }
  54828. // Remove from scene
  54829. var index = this._scene.spriteManagers.indexOf(this);
  54830. this._scene.spriteManagers.splice(index, 1);
  54831. // Callback
  54832. this.onDisposeObservable.notifyObservers(this);
  54833. this.onDisposeObservable.clear();
  54834. };
  54835. return SpriteManager;
  54836. }());
  54837. BABYLON.SpriteManager = SpriteManager;
  54838. })(BABYLON || (BABYLON = {}));
  54839. //# sourceMappingURL=babylon.spriteManager.js.map
  54840. var BABYLON;
  54841. (function (BABYLON) {
  54842. var Sprite = /** @class */ (function () {
  54843. function Sprite(name, manager) {
  54844. this.name = name;
  54845. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54846. this.width = 1.0;
  54847. this.height = 1.0;
  54848. this.angle = 0;
  54849. this.cellIndex = 0;
  54850. this.invertU = 0;
  54851. this.invertV = 0;
  54852. this.animations = new Array();
  54853. this.isPickable = false;
  54854. this._animationStarted = false;
  54855. this._loopAnimation = false;
  54856. this._fromIndex = 0;
  54857. this._toIndex = 0;
  54858. this._delay = 0;
  54859. this._direction = 1;
  54860. this._time = 0;
  54861. this._manager = manager;
  54862. this._manager.sprites.push(this);
  54863. this.position = BABYLON.Vector3.Zero();
  54864. }
  54865. Object.defineProperty(Sprite.prototype, "size", {
  54866. get: function () {
  54867. return this.width;
  54868. },
  54869. set: function (value) {
  54870. this.width = value;
  54871. this.height = value;
  54872. },
  54873. enumerable: true,
  54874. configurable: true
  54875. });
  54876. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54877. this._fromIndex = from;
  54878. this._toIndex = to;
  54879. this._loopAnimation = loop;
  54880. this._delay = delay;
  54881. this._animationStarted = true;
  54882. this._direction = from < to ? 1 : -1;
  54883. this.cellIndex = from;
  54884. this._time = 0;
  54885. this._onAnimationEnd = onAnimationEnd;
  54886. };
  54887. Sprite.prototype.stopAnimation = function () {
  54888. this._animationStarted = false;
  54889. };
  54890. Sprite.prototype._animate = function (deltaTime) {
  54891. if (!this._animationStarted)
  54892. return;
  54893. this._time += deltaTime;
  54894. if (this._time > this._delay) {
  54895. this._time = this._time % this._delay;
  54896. this.cellIndex += this._direction;
  54897. if (this.cellIndex > this._toIndex) {
  54898. if (this._loopAnimation) {
  54899. this.cellIndex = this._fromIndex;
  54900. }
  54901. else {
  54902. this.cellIndex = this._toIndex;
  54903. this._animationStarted = false;
  54904. if (this._onAnimationEnd) {
  54905. this._onAnimationEnd();
  54906. }
  54907. if (this.disposeWhenFinishedAnimating) {
  54908. this.dispose();
  54909. }
  54910. }
  54911. }
  54912. }
  54913. };
  54914. Sprite.prototype.dispose = function () {
  54915. for (var i = 0; i < this._manager.sprites.length; i++) {
  54916. if (this._manager.sprites[i] == this) {
  54917. this._manager.sprites.splice(i, 1);
  54918. }
  54919. }
  54920. };
  54921. return Sprite;
  54922. }());
  54923. BABYLON.Sprite = Sprite;
  54924. })(BABYLON || (BABYLON = {}));
  54925. //# sourceMappingURL=babylon.sprite.js.map
  54926. var BABYLON;
  54927. (function (BABYLON) {
  54928. var IntersectionInfo = /** @class */ (function () {
  54929. function IntersectionInfo(bu, bv, distance) {
  54930. this.bu = bu;
  54931. this.bv = bv;
  54932. this.distance = distance;
  54933. this.faceId = 0;
  54934. this.subMeshId = 0;
  54935. }
  54936. return IntersectionInfo;
  54937. }());
  54938. BABYLON.IntersectionInfo = IntersectionInfo;
  54939. /**
  54940. * Information about the result of picking within a scene
  54941. * See https://doc.babylonjs.com/babylon101/picking_collisions
  54942. */
  54943. var PickingInfo = /** @class */ (function () {
  54944. function PickingInfo() {
  54945. /**
  54946. * If the pick collided with an object
  54947. */
  54948. this.hit = false;
  54949. /**
  54950. * Distance away where the pick collided
  54951. */
  54952. this.distance = 0;
  54953. /**
  54954. * The location of pick collision
  54955. */
  54956. this.pickedPoint = null;
  54957. /**
  54958. * The mesh corrisponding the the pick collision
  54959. */
  54960. this.pickedMesh = null;
  54961. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  54962. this.bu = 0;
  54963. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  54964. this.bv = 0;
  54965. /** The id of the face on the mesh that was picked */
  54966. this.faceId = -1;
  54967. /** Id of the the submesh that was picked */
  54968. this.subMeshId = 0;
  54969. /** If a sprite was picked, this will be the sprite the pick collided with */
  54970. this.pickedSprite = null;
  54971. /**
  54972. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  54973. */
  54974. this.originMesh = null;
  54975. /**
  54976. * The ray that was used to perform the picking.
  54977. */
  54978. this.ray = null;
  54979. }
  54980. /**
  54981. * Gets the normal corrispodning to the face the pick collided with
  54982. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  54983. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  54984. * @returns The normal corrispodning to the face the pick collided with
  54985. */
  54986. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54987. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54988. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54989. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54990. return null;
  54991. }
  54992. var indices = this.pickedMesh.getIndices();
  54993. if (!indices) {
  54994. return null;
  54995. }
  54996. var result;
  54997. if (useVerticesNormals) {
  54998. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54999. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  55000. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  55001. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  55002. normal0 = normal0.scale(this.bu);
  55003. normal1 = normal1.scale(this.bv);
  55004. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  55005. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  55006. }
  55007. else {
  55008. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55009. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  55010. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  55011. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  55012. var p1p2 = vertex1.subtract(vertex2);
  55013. var p3p2 = vertex3.subtract(vertex2);
  55014. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  55015. }
  55016. if (useWorldCoordinates) {
  55017. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  55018. }
  55019. return BABYLON.Vector3.Normalize(result);
  55020. };
  55021. /**
  55022. * Gets the texture coordinates of where the pick occured
  55023. * @returns the vector containing the coordnates of the texture
  55024. */
  55025. PickingInfo.prototype.getTextureCoordinates = function () {
  55026. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55027. return null;
  55028. }
  55029. var indices = this.pickedMesh.getIndices();
  55030. if (!indices) {
  55031. return null;
  55032. }
  55033. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55034. if (!uvs) {
  55035. return null;
  55036. }
  55037. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  55038. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  55039. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  55040. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  55041. uv1 = uv1.scale(this.bu);
  55042. uv2 = uv2.scale(this.bv);
  55043. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  55044. };
  55045. return PickingInfo;
  55046. }());
  55047. BABYLON.PickingInfo = PickingInfo;
  55048. })(BABYLON || (BABYLON = {}));
  55049. //# sourceMappingURL=babylon.pickingInfo.js.map
  55050. var BABYLON;
  55051. (function (BABYLON) {
  55052. var Ray = /** @class */ (function () {
  55053. function Ray(origin, direction, length) {
  55054. if (length === void 0) { length = Number.MAX_VALUE; }
  55055. this.origin = origin;
  55056. this.direction = direction;
  55057. this.length = length;
  55058. }
  55059. // Methods
  55060. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  55061. var d = 0.0;
  55062. var maxValue = Number.MAX_VALUE;
  55063. var inv;
  55064. var min;
  55065. var max;
  55066. var temp;
  55067. if (Math.abs(this.direction.x) < 0.0000001) {
  55068. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  55069. return false;
  55070. }
  55071. }
  55072. else {
  55073. inv = 1.0 / this.direction.x;
  55074. min = (minimum.x - this.origin.x) * inv;
  55075. max = (maximum.x - this.origin.x) * inv;
  55076. if (max === -Infinity) {
  55077. max = Infinity;
  55078. }
  55079. if (min > max) {
  55080. temp = min;
  55081. min = max;
  55082. max = temp;
  55083. }
  55084. d = Math.max(min, d);
  55085. maxValue = Math.min(max, maxValue);
  55086. if (d > maxValue) {
  55087. return false;
  55088. }
  55089. }
  55090. if (Math.abs(this.direction.y) < 0.0000001) {
  55091. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  55092. return false;
  55093. }
  55094. }
  55095. else {
  55096. inv = 1.0 / this.direction.y;
  55097. min = (minimum.y - this.origin.y) * inv;
  55098. max = (maximum.y - this.origin.y) * inv;
  55099. if (max === -Infinity) {
  55100. max = Infinity;
  55101. }
  55102. if (min > max) {
  55103. temp = min;
  55104. min = max;
  55105. max = temp;
  55106. }
  55107. d = Math.max(min, d);
  55108. maxValue = Math.min(max, maxValue);
  55109. if (d > maxValue) {
  55110. return false;
  55111. }
  55112. }
  55113. if (Math.abs(this.direction.z) < 0.0000001) {
  55114. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  55115. return false;
  55116. }
  55117. }
  55118. else {
  55119. inv = 1.0 / this.direction.z;
  55120. min = (minimum.z - this.origin.z) * inv;
  55121. max = (maximum.z - this.origin.z) * inv;
  55122. if (max === -Infinity) {
  55123. max = Infinity;
  55124. }
  55125. if (min > max) {
  55126. temp = min;
  55127. min = max;
  55128. max = temp;
  55129. }
  55130. d = Math.max(min, d);
  55131. maxValue = Math.min(max, maxValue);
  55132. if (d > maxValue) {
  55133. return false;
  55134. }
  55135. }
  55136. return true;
  55137. };
  55138. Ray.prototype.intersectsBox = function (box) {
  55139. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  55140. };
  55141. Ray.prototype.intersectsSphere = function (sphere) {
  55142. var x = sphere.center.x - this.origin.x;
  55143. var y = sphere.center.y - this.origin.y;
  55144. var z = sphere.center.z - this.origin.z;
  55145. var pyth = (x * x) + (y * y) + (z * z);
  55146. var rr = sphere.radius * sphere.radius;
  55147. if (pyth <= rr) {
  55148. return true;
  55149. }
  55150. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  55151. if (dot < 0.0) {
  55152. return false;
  55153. }
  55154. var temp = pyth - (dot * dot);
  55155. return temp <= rr;
  55156. };
  55157. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  55158. if (!this._edge1) {
  55159. this._edge1 = BABYLON.Vector3.Zero();
  55160. this._edge2 = BABYLON.Vector3.Zero();
  55161. this._pvec = BABYLON.Vector3.Zero();
  55162. this._tvec = BABYLON.Vector3.Zero();
  55163. this._qvec = BABYLON.Vector3.Zero();
  55164. }
  55165. vertex1.subtractToRef(vertex0, this._edge1);
  55166. vertex2.subtractToRef(vertex0, this._edge2);
  55167. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  55168. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  55169. if (det === 0) {
  55170. return null;
  55171. }
  55172. var invdet = 1 / det;
  55173. this.origin.subtractToRef(vertex0, this._tvec);
  55174. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  55175. if (bu < 0 || bu > 1.0) {
  55176. return null;
  55177. }
  55178. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  55179. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  55180. if (bv < 0 || bu + bv > 1.0) {
  55181. return null;
  55182. }
  55183. //check if the distance is longer than the predefined length.
  55184. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  55185. if (distance > this.length) {
  55186. return null;
  55187. }
  55188. return new BABYLON.IntersectionInfo(bu, bv, distance);
  55189. };
  55190. Ray.prototype.intersectsPlane = function (plane) {
  55191. var distance;
  55192. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  55193. if (Math.abs(result1) < 9.99999997475243E-07) {
  55194. return null;
  55195. }
  55196. else {
  55197. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  55198. distance = (-plane.d - result2) / result1;
  55199. if (distance < 0.0) {
  55200. if (distance < -9.99999997475243E-07) {
  55201. return null;
  55202. }
  55203. else {
  55204. return 0;
  55205. }
  55206. }
  55207. return distance;
  55208. }
  55209. };
  55210. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  55211. var tm = BABYLON.Tmp.Matrix[0];
  55212. mesh.getWorldMatrix().invertToRef(tm);
  55213. if (this._tmpRay) {
  55214. Ray.TransformToRef(this, tm, this._tmpRay);
  55215. }
  55216. else {
  55217. this._tmpRay = Ray.Transform(this, tm);
  55218. }
  55219. return mesh.intersects(this._tmpRay, fastCheck);
  55220. };
  55221. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  55222. if (results) {
  55223. results.length = 0;
  55224. }
  55225. else {
  55226. results = [];
  55227. }
  55228. for (var i = 0; i < meshes.length; i++) {
  55229. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  55230. if (pickInfo.hit) {
  55231. results.push(pickInfo);
  55232. }
  55233. }
  55234. results.sort(this._comparePickingInfo);
  55235. return results;
  55236. };
  55237. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  55238. if (pickingInfoA.distance < pickingInfoB.distance) {
  55239. return -1;
  55240. }
  55241. else if (pickingInfoA.distance > pickingInfoB.distance) {
  55242. return 1;
  55243. }
  55244. else {
  55245. return 0;
  55246. }
  55247. };
  55248. /**
  55249. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  55250. * @param sega the first point of the segment to test the intersection against
  55251. * @param segb the second point of the segment to test the intersection against
  55252. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  55253. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  55254. */
  55255. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  55256. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  55257. var u = segb.subtract(sega);
  55258. var v = rsegb.subtract(this.origin);
  55259. var w = sega.subtract(this.origin);
  55260. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  55261. var b = BABYLON.Vector3.Dot(u, v);
  55262. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  55263. var d = BABYLON.Vector3.Dot(u, w);
  55264. var e = BABYLON.Vector3.Dot(v, w);
  55265. var D = a * c - b * b; // always >= 0
  55266. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  55267. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  55268. // compute the line parameters of the two closest points
  55269. if (D < Ray.smallnum) { // the lines are almost parallel
  55270. sN = 0.0; // force using point P0 on segment S1
  55271. sD = 1.0; // to prevent possible division by 0.0 later
  55272. tN = e;
  55273. tD = c;
  55274. }
  55275. else { // get the closest points on the infinite lines
  55276. sN = (b * e - c * d);
  55277. tN = (a * e - b * d);
  55278. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  55279. sN = 0.0;
  55280. tN = e;
  55281. tD = c;
  55282. }
  55283. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  55284. sN = sD;
  55285. tN = e + b;
  55286. tD = c;
  55287. }
  55288. }
  55289. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  55290. tN = 0.0;
  55291. // recompute sc for this edge
  55292. if (-d < 0.0) {
  55293. sN = 0.0;
  55294. }
  55295. else if (-d > a)
  55296. sN = sD;
  55297. else {
  55298. sN = -d;
  55299. sD = a;
  55300. }
  55301. }
  55302. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  55303. tN = tD;
  55304. // recompute sc for this edge
  55305. if ((-d + b) < 0.0) {
  55306. sN = 0;
  55307. }
  55308. else if ((-d + b) > a) {
  55309. sN = sD;
  55310. }
  55311. else {
  55312. sN = (-d + b);
  55313. sD = a;
  55314. }
  55315. }
  55316. // finally do the division to get sc and tc
  55317. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  55318. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  55319. // get the difference of the two closest points
  55320. var qtc = v.multiplyByFloats(tc, tc, tc);
  55321. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  55322. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  55323. if (isIntersected) {
  55324. return qtc.length();
  55325. }
  55326. return -1;
  55327. };
  55328. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55329. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  55330. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  55331. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  55332. this.direction.normalize();
  55333. return this;
  55334. };
  55335. // Statics
  55336. Ray.Zero = function () {
  55337. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  55338. };
  55339. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55340. var result = Ray.Zero();
  55341. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  55342. };
  55343. /**
  55344. * 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
  55345. * transformed to the given world matrix.
  55346. * @param origin The origin point
  55347. * @param end The end point
  55348. * @param world a matrix to transform the ray to. Default is the identity matrix.
  55349. */
  55350. Ray.CreateNewFromTo = function (origin, end, world) {
  55351. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  55352. var direction = end.subtract(origin);
  55353. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  55354. direction.normalize();
  55355. return Ray.Transform(new Ray(origin, direction, length), world);
  55356. };
  55357. Ray.Transform = function (ray, matrix) {
  55358. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  55359. Ray.TransformToRef(ray, matrix, result);
  55360. return result;
  55361. };
  55362. Ray.TransformToRef = function (ray, matrix, result) {
  55363. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  55364. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  55365. result.length = ray.length;
  55366. var dir = result.direction;
  55367. var len = dir.length();
  55368. if (!(len === 0 || len === 1)) {
  55369. var num = 1.0 / len;
  55370. dir.x *= num;
  55371. dir.y *= num;
  55372. dir.z *= num;
  55373. result.length *= len;
  55374. }
  55375. };
  55376. Ray.smallnum = 0.00000001;
  55377. Ray.rayl = 10e8;
  55378. return Ray;
  55379. }());
  55380. BABYLON.Ray = Ray;
  55381. })(BABYLON || (BABYLON = {}));
  55382. //# sourceMappingURL=babylon.ray.js.map
  55383. var BABYLON;
  55384. (function (BABYLON) {
  55385. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  55386. if (boxMin.x > sphereCenter.x + sphereRadius)
  55387. return false;
  55388. if (sphereCenter.x - sphereRadius > boxMax.x)
  55389. return false;
  55390. if (boxMin.y > sphereCenter.y + sphereRadius)
  55391. return false;
  55392. if (sphereCenter.y - sphereRadius > boxMax.y)
  55393. return false;
  55394. if (boxMin.z > sphereCenter.z + sphereRadius)
  55395. return false;
  55396. if (sphereCenter.z - sphereRadius > boxMax.z)
  55397. return false;
  55398. return true;
  55399. };
  55400. var getLowestRoot = (function () {
  55401. var result = { root: 0, found: false };
  55402. return function (a, b, c, maxR) {
  55403. result.root = 0;
  55404. result.found = false;
  55405. var determinant = b * b - 4.0 * a * c;
  55406. if (determinant < 0)
  55407. return result;
  55408. var sqrtD = Math.sqrt(determinant);
  55409. var r1 = (-b - sqrtD) / (2.0 * a);
  55410. var r2 = (-b + sqrtD) / (2.0 * a);
  55411. if (r1 > r2) {
  55412. var temp = r2;
  55413. r2 = r1;
  55414. r1 = temp;
  55415. }
  55416. if (r1 > 0 && r1 < maxR) {
  55417. result.root = r1;
  55418. result.found = true;
  55419. return result;
  55420. }
  55421. if (r2 > 0 && r2 < maxR) {
  55422. result.root = r2;
  55423. result.found = true;
  55424. return result;
  55425. }
  55426. return result;
  55427. };
  55428. })();
  55429. var Collider = /** @class */ (function () {
  55430. function Collider() {
  55431. this._collisionPoint = BABYLON.Vector3.Zero();
  55432. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  55433. this._tempVector = BABYLON.Vector3.Zero();
  55434. this._tempVector2 = BABYLON.Vector3.Zero();
  55435. this._tempVector3 = BABYLON.Vector3.Zero();
  55436. this._tempVector4 = BABYLON.Vector3.Zero();
  55437. this._edge = BABYLON.Vector3.Zero();
  55438. this._baseToVertex = BABYLON.Vector3.Zero();
  55439. this._destinationPoint = BABYLON.Vector3.Zero();
  55440. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55441. this._displacementVector = BABYLON.Vector3.Zero();
  55442. this._radius = BABYLON.Vector3.One();
  55443. this._retry = 0;
  55444. this._basePointWorld = BABYLON.Vector3.Zero();
  55445. this._velocityWorld = BABYLON.Vector3.Zero();
  55446. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55447. this._collisionMask = -1;
  55448. }
  55449. Object.defineProperty(Collider.prototype, "collisionMask", {
  55450. get: function () {
  55451. return this._collisionMask;
  55452. },
  55453. set: function (mask) {
  55454. this._collisionMask = !isNaN(mask) ? mask : -1;
  55455. },
  55456. enumerable: true,
  55457. configurable: true
  55458. });
  55459. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55460. /**
  55461. * Gets the plane normal used to compute the sliding response (in local space)
  55462. */
  55463. get: function () {
  55464. return this._slidePlaneNormal;
  55465. },
  55466. enumerable: true,
  55467. configurable: true
  55468. });
  55469. // Methods
  55470. Collider.prototype._initialize = function (source, dir, e) {
  55471. this._velocity = dir;
  55472. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55473. this._basePoint = source;
  55474. source.multiplyToRef(this._radius, this._basePointWorld);
  55475. dir.multiplyToRef(this._radius, this._velocityWorld);
  55476. this._velocityWorldLength = this._velocityWorld.length();
  55477. this._epsilon = e;
  55478. this.collisionFound = false;
  55479. };
  55480. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55481. pa.subtractToRef(point, this._tempVector);
  55482. pb.subtractToRef(point, this._tempVector2);
  55483. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55484. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55485. if (d < 0)
  55486. return false;
  55487. pc.subtractToRef(point, this._tempVector3);
  55488. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55489. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55490. if (d < 0)
  55491. return false;
  55492. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55493. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55494. return d >= 0;
  55495. };
  55496. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55497. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55498. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55499. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55500. return false;
  55501. }
  55502. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55503. return false;
  55504. return true;
  55505. };
  55506. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55507. var t0;
  55508. var embeddedInPlane = false;
  55509. //defensive programming, actually not needed.
  55510. if (!trianglePlaneArray) {
  55511. trianglePlaneArray = [];
  55512. }
  55513. if (!trianglePlaneArray[faceIndex]) {
  55514. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55515. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55516. }
  55517. var trianglePlane = trianglePlaneArray[faceIndex];
  55518. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55519. return;
  55520. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55521. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55522. if (normalDotVelocity == 0) {
  55523. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55524. return;
  55525. embeddedInPlane = true;
  55526. t0 = 0;
  55527. }
  55528. else {
  55529. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55530. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55531. if (t0 > t1) {
  55532. var temp = t1;
  55533. t1 = t0;
  55534. t0 = temp;
  55535. }
  55536. if (t0 > 1.0 || t1 < 0.0)
  55537. return;
  55538. if (t0 < 0)
  55539. t0 = 0;
  55540. if (t0 > 1.0)
  55541. t0 = 1.0;
  55542. }
  55543. this._collisionPoint.copyFromFloats(0, 0, 0);
  55544. var found = false;
  55545. var t = 1.0;
  55546. if (!embeddedInPlane) {
  55547. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55548. this._velocity.scaleToRef(t0, this._tempVector);
  55549. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55550. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55551. found = true;
  55552. t = t0;
  55553. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55554. }
  55555. }
  55556. if (!found) {
  55557. var velocitySquaredLength = this._velocity.lengthSquared();
  55558. var a = velocitySquaredLength;
  55559. this._basePoint.subtractToRef(p1, this._tempVector);
  55560. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55561. var c = this._tempVector.lengthSquared() - 1.0;
  55562. var lowestRoot = getLowestRoot(a, b, c, t);
  55563. if (lowestRoot.found) {
  55564. t = lowestRoot.root;
  55565. found = true;
  55566. this._collisionPoint.copyFrom(p1);
  55567. }
  55568. this._basePoint.subtractToRef(p2, this._tempVector);
  55569. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55570. c = this._tempVector.lengthSquared() - 1.0;
  55571. lowestRoot = getLowestRoot(a, b, c, t);
  55572. if (lowestRoot.found) {
  55573. t = lowestRoot.root;
  55574. found = true;
  55575. this._collisionPoint.copyFrom(p2);
  55576. }
  55577. this._basePoint.subtractToRef(p3, this._tempVector);
  55578. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55579. c = this._tempVector.lengthSquared() - 1.0;
  55580. lowestRoot = getLowestRoot(a, b, c, t);
  55581. if (lowestRoot.found) {
  55582. t = lowestRoot.root;
  55583. found = true;
  55584. this._collisionPoint.copyFrom(p3);
  55585. }
  55586. p2.subtractToRef(p1, this._edge);
  55587. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55588. var edgeSquaredLength = this._edge.lengthSquared();
  55589. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55590. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55591. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55592. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55593. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55594. lowestRoot = getLowestRoot(a, b, c, t);
  55595. if (lowestRoot.found) {
  55596. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55597. if (f >= 0.0 && f <= 1.0) {
  55598. t = lowestRoot.root;
  55599. found = true;
  55600. this._edge.scaleInPlace(f);
  55601. p1.addToRef(this._edge, this._collisionPoint);
  55602. }
  55603. }
  55604. p3.subtractToRef(p2, this._edge);
  55605. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55606. edgeSquaredLength = this._edge.lengthSquared();
  55607. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55608. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55609. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55610. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55611. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55612. lowestRoot = getLowestRoot(a, b, c, t);
  55613. if (lowestRoot.found) {
  55614. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55615. if (f >= 0.0 && f <= 1.0) {
  55616. t = lowestRoot.root;
  55617. found = true;
  55618. this._edge.scaleInPlace(f);
  55619. p2.addToRef(this._edge, this._collisionPoint);
  55620. }
  55621. }
  55622. p1.subtractToRef(p3, this._edge);
  55623. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55624. edgeSquaredLength = this._edge.lengthSquared();
  55625. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55626. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55627. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55628. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55629. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55630. lowestRoot = getLowestRoot(a, b, c, t);
  55631. if (lowestRoot.found) {
  55632. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55633. if (f >= 0.0 && f <= 1.0) {
  55634. t = lowestRoot.root;
  55635. found = true;
  55636. this._edge.scaleInPlace(f);
  55637. p3.addToRef(this._edge, this._collisionPoint);
  55638. }
  55639. }
  55640. }
  55641. if (found) {
  55642. var distToCollision = t * this._velocity.length();
  55643. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55644. if (!this.intersectionPoint) {
  55645. this.intersectionPoint = this._collisionPoint.clone();
  55646. }
  55647. else {
  55648. this.intersectionPoint.copyFrom(this._collisionPoint);
  55649. }
  55650. this._nearestDistance = distToCollision;
  55651. this.collisionFound = true;
  55652. }
  55653. }
  55654. };
  55655. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55656. for (var i = indexStart; i < indexEnd; i += 3) {
  55657. var p1 = pts[indices[i] - decal];
  55658. var p2 = pts[indices[i + 1] - decal];
  55659. var p3 = pts[indices[i + 2] - decal];
  55660. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55661. }
  55662. };
  55663. Collider.prototype._getResponse = function (pos, vel) {
  55664. pos.addToRef(vel, this._destinationPoint);
  55665. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55666. this._basePoint.addToRef(vel, pos);
  55667. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55668. this._slidePlaneNormal.normalize();
  55669. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55670. pos.addInPlace(this._displacementVector);
  55671. this.intersectionPoint.addInPlace(this._displacementVector);
  55672. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55673. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55674. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55675. };
  55676. return Collider;
  55677. }());
  55678. BABYLON.Collider = Collider;
  55679. })(BABYLON || (BABYLON = {}));
  55680. //# sourceMappingURL=babylon.collider.js.map
  55681. var BABYLON;
  55682. (function (BABYLON) {
  55683. //WebWorker code will be inserted to this variable.
  55684. BABYLON.CollisionWorker = "";
  55685. /** Defines supported task for worker process */
  55686. var WorkerTaskType;
  55687. (function (WorkerTaskType) {
  55688. /** Initialization */
  55689. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55690. /** Update of geometry */
  55691. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55692. /** Evaluate collision */
  55693. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55694. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55695. /** Defines kind of replies returned by worker */
  55696. var WorkerReplyType;
  55697. (function (WorkerReplyType) {
  55698. /** Success */
  55699. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55700. /** Unkown error */
  55701. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55702. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55703. var CollisionCoordinatorWorker = /** @class */ (function () {
  55704. function CollisionCoordinatorWorker() {
  55705. var _this = this;
  55706. this._scaledPosition = BABYLON.Vector3.Zero();
  55707. this._scaledVelocity = BABYLON.Vector3.Zero();
  55708. this.onMeshUpdated = function (transformNode) {
  55709. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55710. };
  55711. this.onGeometryUpdated = function (geometry) {
  55712. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55713. };
  55714. this._afterRender = function () {
  55715. if (!_this._init)
  55716. return;
  55717. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55718. return;
  55719. }
  55720. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55721. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55722. if (_this._runningUpdated > 4) {
  55723. return;
  55724. }
  55725. ++_this._runningUpdated;
  55726. var payload = {
  55727. updatedMeshes: _this._addUpdateMeshesList,
  55728. updatedGeometries: _this._addUpdateGeometriesList,
  55729. removedGeometries: _this._toRemoveGeometryArray,
  55730. removedMeshes: _this._toRemoveMeshesArray
  55731. };
  55732. var message = {
  55733. payload: payload,
  55734. taskType: WorkerTaskType.UPDATE
  55735. };
  55736. var serializable = [];
  55737. for (var id in payload.updatedGeometries) {
  55738. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55739. //prepare transferables
  55740. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55741. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55742. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55743. }
  55744. }
  55745. _this._worker.postMessage(message, serializable);
  55746. _this._addUpdateMeshesList = {};
  55747. _this._addUpdateGeometriesList = {};
  55748. _this._toRemoveGeometryArray = [];
  55749. _this._toRemoveMeshesArray = [];
  55750. };
  55751. this._onMessageFromWorker = function (e) {
  55752. var returnData = e.data;
  55753. if (returnData.error != WorkerReplyType.SUCCESS) {
  55754. //TODO what errors can be returned from the worker?
  55755. BABYLON.Tools.Warn("error returned from worker!");
  55756. return;
  55757. }
  55758. switch (returnData.taskType) {
  55759. case WorkerTaskType.INIT:
  55760. _this._init = true;
  55761. //Update the worked with ALL of the scene's current state
  55762. _this._scene.meshes.forEach(function (mesh) {
  55763. _this.onMeshAdded(mesh);
  55764. });
  55765. _this._scene.getGeometries().forEach(function (geometry) {
  55766. _this.onGeometryAdded(geometry);
  55767. });
  55768. break;
  55769. case WorkerTaskType.UPDATE:
  55770. _this._runningUpdated--;
  55771. break;
  55772. case WorkerTaskType.COLLIDE:
  55773. var returnPayload = returnData.payload;
  55774. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55775. return;
  55776. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55777. if (callback) {
  55778. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55779. if (mesh) {
  55780. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55781. }
  55782. }
  55783. //cleanup
  55784. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55785. break;
  55786. }
  55787. };
  55788. this._collisionsCallbackArray = [];
  55789. this._init = false;
  55790. this._runningUpdated = 0;
  55791. this._addUpdateMeshesList = {};
  55792. this._addUpdateGeometriesList = {};
  55793. this._toRemoveGeometryArray = [];
  55794. this._toRemoveMeshesArray = [];
  55795. }
  55796. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55797. if (!this._init)
  55798. return;
  55799. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55800. return;
  55801. position.divideToRef(collider._radius, this._scaledPosition);
  55802. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55803. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55804. var payload = {
  55805. collider: {
  55806. position: this._scaledPosition.asArray(),
  55807. velocity: this._scaledVelocity.asArray(),
  55808. radius: collider._radius.asArray()
  55809. },
  55810. collisionId: collisionIndex,
  55811. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55812. maximumRetry: maximumRetry
  55813. };
  55814. var message = {
  55815. payload: payload,
  55816. taskType: WorkerTaskType.COLLIDE
  55817. };
  55818. this._worker.postMessage(message);
  55819. };
  55820. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55821. this._scene = scene;
  55822. this._scene.registerAfterRender(this._afterRender);
  55823. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55824. this._worker = new Worker(workerUrl);
  55825. this._worker.onmessage = this._onMessageFromWorker;
  55826. var message = {
  55827. payload: {},
  55828. taskType: WorkerTaskType.INIT
  55829. };
  55830. this._worker.postMessage(message);
  55831. };
  55832. CollisionCoordinatorWorker.prototype.destroy = function () {
  55833. this._scene.unregisterAfterRender(this._afterRender);
  55834. this._worker.terminate();
  55835. };
  55836. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55837. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55838. this.onMeshUpdated(mesh);
  55839. };
  55840. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55841. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55842. };
  55843. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55844. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55845. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55846. this.onGeometryUpdated(geometry);
  55847. };
  55848. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55849. this._toRemoveGeometryArray.push(geometry.id);
  55850. };
  55851. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55852. var submeshes = [];
  55853. if (mesh.subMeshes) {
  55854. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55855. var boundingInfo = sm.getBoundingInfo();
  55856. return {
  55857. position: idx,
  55858. verticesStart: sm.verticesStart,
  55859. verticesCount: sm.verticesCount,
  55860. indexStart: sm.indexStart,
  55861. indexCount: sm.indexCount,
  55862. hasMaterial: !!sm.getMaterial(),
  55863. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55864. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55865. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55866. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55867. };
  55868. });
  55869. }
  55870. var geometryId = null;
  55871. if (mesh instanceof BABYLON.Mesh) {
  55872. var geometry = mesh.geometry;
  55873. geometryId = geometry ? geometry.id : null;
  55874. }
  55875. else if (mesh instanceof BABYLON.InstancedMesh) {
  55876. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55877. geometryId = geometry ? geometry.id : null;
  55878. }
  55879. var boundingInfo = mesh.getBoundingInfo();
  55880. return {
  55881. uniqueId: mesh.uniqueId,
  55882. id: mesh.id,
  55883. name: mesh.name,
  55884. geometryId: geometryId,
  55885. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55886. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55887. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55888. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55889. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55890. subMeshes: submeshes,
  55891. checkCollisions: mesh.checkCollisions
  55892. };
  55893. };
  55894. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55895. return {
  55896. id: geometry.id,
  55897. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55898. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55899. indices: new Uint32Array(geometry.getIndices() || []),
  55900. };
  55901. };
  55902. return CollisionCoordinatorWorker;
  55903. }());
  55904. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55905. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55906. function CollisionCoordinatorLegacy() {
  55907. this._scaledPosition = BABYLON.Vector3.Zero();
  55908. this._scaledVelocity = BABYLON.Vector3.Zero();
  55909. this._finalPosition = BABYLON.Vector3.Zero();
  55910. }
  55911. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55912. position.divideToRef(collider._radius, this._scaledPosition);
  55913. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55914. collider.collidedMesh = null;
  55915. collider._retry = 0;
  55916. collider._initialVelocity = this._scaledVelocity;
  55917. collider._initialPosition = this._scaledPosition;
  55918. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55919. this._finalPosition.multiplyInPlace(collider._radius);
  55920. //run the callback
  55921. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55922. };
  55923. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55924. this._scene = scene;
  55925. };
  55926. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55927. //Legacy need no destruction method.
  55928. };
  55929. //No update in legacy mode
  55930. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55931. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55932. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55933. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55934. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55935. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55936. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55937. if (excludedMesh === void 0) { excludedMesh = null; }
  55938. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55939. if (collider._retry >= maximumRetry) {
  55940. finalPosition.copyFrom(position);
  55941. return;
  55942. }
  55943. // Check if this is a mesh else camera or -1
  55944. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55945. collider._initialize(position, velocity, closeDistance);
  55946. // Check all meshes
  55947. for (var index = 0; index < this._scene.meshes.length; index++) {
  55948. var mesh = this._scene.meshes[index];
  55949. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55950. mesh._checkCollision(collider);
  55951. }
  55952. }
  55953. if (!collider.collisionFound) {
  55954. position.addToRef(velocity, finalPosition);
  55955. return;
  55956. }
  55957. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55958. collider._getResponse(position, velocity);
  55959. }
  55960. if (velocity.length() <= closeDistance) {
  55961. finalPosition.copyFrom(position);
  55962. return;
  55963. }
  55964. collider._retry++;
  55965. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55966. };
  55967. return CollisionCoordinatorLegacy;
  55968. }());
  55969. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55970. })(BABYLON || (BABYLON = {}));
  55971. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55972. var BABYLON;
  55973. (function (BABYLON) {
  55974. /**
  55975. * A particle represents one of the element emitted by a particle system.
  55976. * This is mainly define by its coordinates, direction, velocity and age.
  55977. */
  55978. var Particle = /** @class */ (function () {
  55979. /**
  55980. * Creates a new instance Particle
  55981. * @param particleSystem the particle system the particle belongs to
  55982. */
  55983. function Particle(
  55984. /**
  55985. * particleSystem the particle system the particle belongs to.
  55986. */
  55987. particleSystem) {
  55988. this.particleSystem = particleSystem;
  55989. /**
  55990. * The world position of the particle in the scene.
  55991. */
  55992. this.position = BABYLON.Vector3.Zero();
  55993. /**
  55994. * The world direction of the particle in the scene.
  55995. */
  55996. this.direction = BABYLON.Vector3.Zero();
  55997. /**
  55998. * The color of the particle.
  55999. */
  56000. this.color = new BABYLON.Color4(0, 0, 0, 0);
  56001. /**
  56002. * The color change of the particle per step.
  56003. */
  56004. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  56005. /**
  56006. * Defines how long will the life of the particle be.
  56007. */
  56008. this.lifeTime = 1.0;
  56009. /**
  56010. * The current age of the particle.
  56011. */
  56012. this.age = 0;
  56013. /**
  56014. * The current size of the particle.
  56015. */
  56016. this.size = 0;
  56017. /**
  56018. * The current angle of the particle.
  56019. */
  56020. this.angle = 0;
  56021. /**
  56022. * Defines how fast is the angle changing.
  56023. */
  56024. this.angularSpeed = 0;
  56025. /**
  56026. * Defines the cell index used by the particle to be rendered from a sprite.
  56027. */
  56028. this.cellIndex = 0;
  56029. this._currentFrameCounter = 0;
  56030. if (!this.particleSystem.isAnimationSheetEnabled) {
  56031. return;
  56032. }
  56033. this.updateCellInfoFromSystem();
  56034. }
  56035. Particle.prototype.updateCellInfoFromSystem = function () {
  56036. this.cellIndex = this.particleSystem.startSpriteCellID;
  56037. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  56038. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  56039. }
  56040. else {
  56041. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  56042. }
  56043. };
  56044. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  56045. // (ageOffset / scaledUpdateSpeed) / available cells
  56046. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  56047. this._currentFrameCounter += scaledUpdateSpeed;
  56048. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  56049. this._currentFrameCounter = 0;
  56050. this.cellIndex++;
  56051. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  56052. this.cellIndex = this.particleSystem.endSpriteCellID;
  56053. }
  56054. }
  56055. };
  56056. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  56057. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  56058. this.cellIndex++;
  56059. this._currentFrameCounter = 0;
  56060. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  56061. if (this.particleSystem.spriteCellLoop) {
  56062. this.cellIndex = this.particleSystem.startSpriteCellID;
  56063. }
  56064. else {
  56065. this.cellIndex = this.particleSystem.endSpriteCellID;
  56066. }
  56067. }
  56068. }
  56069. else {
  56070. this._currentFrameCounter++;
  56071. }
  56072. };
  56073. /**
  56074. * Copy the properties of particle to another one.
  56075. * @param other the particle to copy the information to.
  56076. */
  56077. Particle.prototype.copyTo = function (other) {
  56078. other.position.copyFrom(this.position);
  56079. other.direction.copyFrom(this.direction);
  56080. other.color.copyFrom(this.color);
  56081. other.colorStep.copyFrom(this.colorStep);
  56082. other.lifeTime = this.lifeTime;
  56083. other.age = this.age;
  56084. other.size = this.size;
  56085. other.angle = this.angle;
  56086. other.angularSpeed = this.angularSpeed;
  56087. other.particleSystem = this.particleSystem;
  56088. other.cellIndex = this.cellIndex;
  56089. };
  56090. return Particle;
  56091. }());
  56092. BABYLON.Particle = Particle;
  56093. })(BABYLON || (BABYLON = {}));
  56094. //# sourceMappingURL=babylon.particle.js.map
  56095. var BABYLON;
  56096. (function (BABYLON) {
  56097. /**
  56098. * This represents a particle system in Babylon.
  56099. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  56100. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56101. * @example https://doc.babylonjs.com/babylon101/particles
  56102. */
  56103. var ParticleSystem = /** @class */ (function () {
  56104. /**
  56105. * Instantiates a particle system.
  56106. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  56107. * @param name The name of the particle system
  56108. * @param capacity The max number of particles alive at the same time
  56109. * @param scene The scene the particle system belongs to
  56110. * @param customEffect a custom effect used to change the way particles are rendered by default
  56111. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56112. * @param epsilon Offset used to render the particles
  56113. */
  56114. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  56115. if (customEffect === void 0) { customEffect = null; }
  56116. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56117. if (epsilon === void 0) { epsilon = 0.01; }
  56118. var _this = this;
  56119. /**
  56120. * List of animations used by the particle system.
  56121. */
  56122. this.animations = [];
  56123. /**
  56124. * The rendering group used by the Particle system to chose when to render.
  56125. */
  56126. this.renderingGroupId = 0;
  56127. /**
  56128. * The emitter represents the Mesh or position we are attaching the particle system to.
  56129. */
  56130. this.emitter = null;
  56131. /**
  56132. * The maximum number of particles to emit per frame
  56133. */
  56134. this.emitRate = 10;
  56135. /**
  56136. * If you want to launch only a few particles at once, that can be done, as well.
  56137. */
  56138. this.manualEmitCount = -1;
  56139. /**
  56140. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56141. */
  56142. this.updateSpeed = 0.01;
  56143. /**
  56144. * The amount of time the particle system is running (depends of the overall update speed).
  56145. */
  56146. this.targetStopDuration = 0;
  56147. /**
  56148. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  56149. */
  56150. this.disposeOnStop = false;
  56151. /**
  56152. * Minimum power of emitting particles.
  56153. */
  56154. this.minEmitPower = 1;
  56155. /**
  56156. * Maximum power of emitting particles.
  56157. */
  56158. this.maxEmitPower = 1;
  56159. /**
  56160. * Minimum life time of emitting particles.
  56161. */
  56162. this.minLifeTime = 1;
  56163. /**
  56164. * Maximum life time of emitting particles.
  56165. */
  56166. this.maxLifeTime = 1;
  56167. /**
  56168. * Minimum Size of emitting particles.
  56169. */
  56170. this.minSize = 1;
  56171. /**
  56172. * Maximum Size of emitting particles.
  56173. */
  56174. this.maxSize = 1;
  56175. /**
  56176. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56177. */
  56178. this.minAngularSpeed = 0;
  56179. /**
  56180. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56181. */
  56182. this.maxAngularSpeed = 0;
  56183. /**
  56184. * The layer mask we are rendering the particles through.
  56185. */
  56186. this.layerMask = 0x0FFFFFFF;
  56187. /**
  56188. * This can help using your own shader to render the particle system.
  56189. * The according effect will be created
  56190. */
  56191. this.customShader = null;
  56192. /**
  56193. * By default particle system starts as soon as they are created. This prevents the
  56194. * automatic start to happen and let you decide when to start emitting particles.
  56195. */
  56196. this.preventAutoStart = false;
  56197. /**
  56198. * Callback triggered when the particle animation is ending.
  56199. */
  56200. this.onAnimationEnd = null;
  56201. /**
  56202. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56203. */
  56204. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  56205. /**
  56206. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56207. * to override the particles.
  56208. */
  56209. this.forceDepthWrite = false;
  56210. /**
  56211. * You can use gravity if you want to give an orientation to your particles.
  56212. */
  56213. this.gravity = BABYLON.Vector3.Zero();
  56214. /**
  56215. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56216. */
  56217. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56218. /**
  56219. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56220. */
  56221. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56222. /**
  56223. * Color the particle will have at the end of its lifetime.
  56224. */
  56225. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  56226. /**
  56227. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  56228. */
  56229. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56230. /**
  56231. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  56232. */
  56233. this.spriteCellLoop = true;
  56234. /**
  56235. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  56236. */
  56237. this.spriteCellChangeSpeed = 0;
  56238. /**
  56239. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  56240. */
  56241. this.startSpriteCellID = 0;
  56242. /**
  56243. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  56244. */
  56245. this.endSpriteCellID = 0;
  56246. /**
  56247. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  56248. */
  56249. this.spriteCellWidth = 0;
  56250. /**
  56251. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  56252. */
  56253. this.spriteCellHeight = 0;
  56254. /**
  56255. * An event triggered when the system is disposed.
  56256. */
  56257. this.onDisposeObservable = new BABYLON.Observable();
  56258. this._particles = new Array();
  56259. this._stockParticles = new Array();
  56260. this._newPartsExcess = 0;
  56261. this._vertexBuffers = {};
  56262. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56263. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56264. this._scaledDirection = BABYLON.Vector3.Zero();
  56265. this._scaledGravity = BABYLON.Vector3.Zero();
  56266. this._currentRenderId = -1;
  56267. this._started = false;
  56268. this._stopped = false;
  56269. this._actualFrame = 0;
  56270. this._vertexBufferSize = 11;
  56271. // start of sub system methods
  56272. /**
  56273. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56274. * Its lifetime will start back at 0.
  56275. */
  56276. this.recycleParticle = function (particle) {
  56277. var lastParticle = _this._particles.pop();
  56278. if (lastParticle !== particle) {
  56279. lastParticle.copyTo(particle);
  56280. }
  56281. _this._stockParticles.push(lastParticle);
  56282. };
  56283. this._createParticle = function () {
  56284. var particle;
  56285. if (_this._stockParticles.length !== 0) {
  56286. particle = _this._stockParticles.pop();
  56287. particle.age = 0;
  56288. particle.cellIndex = _this.startSpriteCellID;
  56289. }
  56290. else {
  56291. particle = new BABYLON.Particle(_this);
  56292. }
  56293. return particle;
  56294. };
  56295. this._emitFromParticle = function (particle) {
  56296. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  56297. return;
  56298. }
  56299. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  56300. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  56301. subSystem._rootParticleSystem = _this;
  56302. _this.activeSubSystems.push(subSystem);
  56303. subSystem.start();
  56304. };
  56305. this._appendParticleVertexes = null;
  56306. this.id = name;
  56307. this.name = name;
  56308. this._capacity = capacity;
  56309. this._epsilon = epsilon;
  56310. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56311. if (isAnimationSheetEnabled) {
  56312. this._vertexBufferSize = 12;
  56313. }
  56314. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56315. this._customEffect = customEffect;
  56316. scene.particleSystems.push(this);
  56317. this._createIndexBuffer();
  56318. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  56319. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  56320. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  56321. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  56322. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  56323. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  56324. if (this._isAnimationSheetEnabled) {
  56325. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  56326. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56327. }
  56328. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56329. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56330. this._vertexBuffers["options"] = options;
  56331. // Default emitter type
  56332. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56333. this.updateFunction = function (particles) {
  56334. for (var index = 0; index < particles.length; index++) {
  56335. var particle = particles[index];
  56336. particle.age += _this._scaledUpdateSpeed;
  56337. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56338. _this._emitFromParticle(particle);
  56339. _this.recycleParticle(particle);
  56340. index--;
  56341. continue;
  56342. }
  56343. else {
  56344. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56345. particle.color.addInPlace(_this._scaledColorStep);
  56346. if (particle.color.a < 0)
  56347. particle.color.a = 0;
  56348. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56349. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  56350. particle.position.addInPlace(_this._scaledDirection);
  56351. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56352. particle.direction.addInPlace(_this._scaledGravity);
  56353. if (_this._isAnimationSheetEnabled) {
  56354. particle.updateCellIndex(_this._scaledUpdateSpeed);
  56355. }
  56356. }
  56357. }
  56358. };
  56359. }
  56360. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  56361. /**
  56362. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56363. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56364. */
  56365. get: function () {
  56366. if (this.particleEmitterType.direction1) {
  56367. return this.particleEmitterType.direction1;
  56368. }
  56369. return BABYLON.Vector3.Zero();
  56370. },
  56371. set: function (value) {
  56372. if (this.particleEmitterType.direction1) {
  56373. this.particleEmitterType.direction1 = value;
  56374. }
  56375. },
  56376. enumerable: true,
  56377. configurable: true
  56378. });
  56379. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  56380. /**
  56381. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56382. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56383. */
  56384. get: function () {
  56385. if (this.particleEmitterType.direction2) {
  56386. return this.particleEmitterType.direction2;
  56387. }
  56388. return BABYLON.Vector3.Zero();
  56389. },
  56390. set: function (value) {
  56391. if (this.particleEmitterType.direction2) {
  56392. this.particleEmitterType.direction2 = value;
  56393. }
  56394. },
  56395. enumerable: true,
  56396. configurable: true
  56397. });
  56398. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  56399. /**
  56400. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  56401. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56402. */
  56403. get: function () {
  56404. if (this.particleEmitterType.minEmitBox) {
  56405. return this.particleEmitterType.minEmitBox;
  56406. }
  56407. return BABYLON.Vector3.Zero();
  56408. },
  56409. set: function (value) {
  56410. if (this.particleEmitterType.minEmitBox) {
  56411. this.particleEmitterType.minEmitBox = value;
  56412. }
  56413. },
  56414. enumerable: true,
  56415. configurable: true
  56416. });
  56417. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  56418. /**
  56419. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  56420. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56421. */
  56422. get: function () {
  56423. if (this.particleEmitterType.maxEmitBox) {
  56424. return this.particleEmitterType.maxEmitBox;
  56425. }
  56426. return BABYLON.Vector3.Zero();
  56427. },
  56428. set: function (value) {
  56429. if (this.particleEmitterType.maxEmitBox) {
  56430. this.particleEmitterType.maxEmitBox = value;
  56431. }
  56432. },
  56433. enumerable: true,
  56434. configurable: true
  56435. });
  56436. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56437. /**
  56438. * Sets a callback that will be triggered when the system is disposed.
  56439. */
  56440. set: function (callback) {
  56441. if (this._onDisposeObserver) {
  56442. this.onDisposeObservable.remove(this._onDisposeObserver);
  56443. }
  56444. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56445. },
  56446. enumerable: true,
  56447. configurable: true
  56448. });
  56449. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  56450. /**
  56451. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  56452. */
  56453. get: function () {
  56454. return this._isAnimationSheetEnabled;
  56455. },
  56456. enumerable: true,
  56457. configurable: true
  56458. });
  56459. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56460. //end of Sub-emitter
  56461. /**
  56462. * Gets the current list of active particles
  56463. */
  56464. get: function () {
  56465. return this._particles;
  56466. },
  56467. enumerable: true,
  56468. configurable: true
  56469. });
  56470. /**
  56471. * Returns the string "ParticleSystem"
  56472. * @returns a string containing the class name
  56473. */
  56474. ParticleSystem.prototype.getClassName = function () {
  56475. return "ParticleSystem";
  56476. };
  56477. ParticleSystem.prototype._createIndexBuffer = function () {
  56478. var indices = [];
  56479. var index = 0;
  56480. for (var count = 0; count < this._capacity; count++) {
  56481. indices.push(index);
  56482. indices.push(index + 1);
  56483. indices.push(index + 2);
  56484. indices.push(index);
  56485. indices.push(index + 2);
  56486. indices.push(index + 3);
  56487. index += 4;
  56488. }
  56489. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56490. };
  56491. /**
  56492. * Gets the maximum number of particles active at the same time.
  56493. * @returns The max number of active particles.
  56494. */
  56495. ParticleSystem.prototype.getCapacity = function () {
  56496. return this._capacity;
  56497. };
  56498. /**
  56499. * Gets Wether there are still active particles in the system.
  56500. * @returns True if it is alive, otherwise false.
  56501. */
  56502. ParticleSystem.prototype.isAlive = function () {
  56503. return this._alive;
  56504. };
  56505. /**
  56506. * Gets Wether the system has been started.
  56507. * @returns True if it has been started, otherwise false.
  56508. */
  56509. ParticleSystem.prototype.isStarted = function () {
  56510. return this._started;
  56511. };
  56512. /**
  56513. * Starts the particle system and begins to emit.
  56514. */
  56515. ParticleSystem.prototype.start = function () {
  56516. this._started = true;
  56517. this._stopped = false;
  56518. this._actualFrame = 0;
  56519. if (this.subEmitters && this.subEmitters.length != 0) {
  56520. this.activeSubSystems = new Array();
  56521. }
  56522. };
  56523. /**
  56524. * Stops the particle system.
  56525. * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true.
  56526. */
  56527. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56528. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56529. this._stopped = true;
  56530. if (stopSubEmitters) {
  56531. this._stopSubEmitters();
  56532. }
  56533. };
  56534. // animation sheet
  56535. /**
  56536. * Remove all active particles
  56537. */
  56538. ParticleSystem.prototype.reset = function () {
  56539. this._stockParticles = [];
  56540. this._particles = [];
  56541. };
  56542. /**
  56543. * @hidden (for internal use only)
  56544. */
  56545. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56546. var offset = index * this._vertexBufferSize;
  56547. this._vertexData[offset] = particle.position.x;
  56548. this._vertexData[offset + 1] = particle.position.y;
  56549. this._vertexData[offset + 2] = particle.position.z;
  56550. this._vertexData[offset + 3] = particle.color.r;
  56551. this._vertexData[offset + 4] = particle.color.g;
  56552. this._vertexData[offset + 5] = particle.color.b;
  56553. this._vertexData[offset + 6] = particle.color.a;
  56554. this._vertexData[offset + 7] = particle.angle;
  56555. this._vertexData[offset + 8] = particle.size;
  56556. this._vertexData[offset + 9] = offsetX;
  56557. this._vertexData[offset + 10] = offsetY;
  56558. };
  56559. /**
  56560. * @hidden (for internal use only)
  56561. */
  56562. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  56563. if (offsetX === 0)
  56564. offsetX = this._epsilon;
  56565. else if (offsetX === 1)
  56566. offsetX = 1 - this._epsilon;
  56567. if (offsetY === 0)
  56568. offsetY = this._epsilon;
  56569. else if (offsetY === 1)
  56570. offsetY = 1 - this._epsilon;
  56571. var offset = index * this._vertexBufferSize;
  56572. this._vertexData[offset] = particle.position.x;
  56573. this._vertexData[offset + 1] = particle.position.y;
  56574. this._vertexData[offset + 2] = particle.position.z;
  56575. this._vertexData[offset + 3] = particle.color.r;
  56576. this._vertexData[offset + 4] = particle.color.g;
  56577. this._vertexData[offset + 5] = particle.color.b;
  56578. this._vertexData[offset + 6] = particle.color.a;
  56579. this._vertexData[offset + 7] = particle.angle;
  56580. this._vertexData[offset + 8] = particle.size;
  56581. this._vertexData[offset + 9] = offsetX;
  56582. this._vertexData[offset + 10] = offsetY;
  56583. this._vertexData[offset + 11] = particle.cellIndex;
  56584. };
  56585. ParticleSystem.prototype._stopSubEmitters = function () {
  56586. if (!this.activeSubSystems) {
  56587. return;
  56588. }
  56589. this.activeSubSystems.forEach(function (subSystem) {
  56590. subSystem.stop(true);
  56591. });
  56592. this.activeSubSystems = new Array();
  56593. };
  56594. ParticleSystem.prototype._removeFromRoot = function () {
  56595. if (!this._rootParticleSystem) {
  56596. return;
  56597. }
  56598. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56599. if (index !== -1) {
  56600. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56601. }
  56602. };
  56603. // end of sub system methods
  56604. ParticleSystem.prototype._update = function (newParticles) {
  56605. // Update current
  56606. this._alive = this._particles.length > 0;
  56607. this.updateFunction(this._particles);
  56608. // Add new ones
  56609. var worldMatrix;
  56610. if (this.emitter.position) {
  56611. var emitterMesh = this.emitter;
  56612. worldMatrix = emitterMesh.getWorldMatrix();
  56613. }
  56614. else {
  56615. var emitterPosition = this.emitter;
  56616. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56617. }
  56618. var particle;
  56619. for (var index = 0; index < newParticles; index++) {
  56620. if (this._particles.length === this._capacity) {
  56621. break;
  56622. }
  56623. particle = this._createParticle();
  56624. this._particles.push(particle);
  56625. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56626. if (this.startPositionFunction) {
  56627. this.startPositionFunction(worldMatrix, particle.position, particle);
  56628. }
  56629. else {
  56630. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56631. }
  56632. if (this.startDirectionFunction) {
  56633. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56634. }
  56635. else {
  56636. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56637. }
  56638. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56639. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56640. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56641. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56642. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56643. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56644. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56645. }
  56646. };
  56647. ParticleSystem.prototype._getEffect = function () {
  56648. if (this._customEffect) {
  56649. return this._customEffect;
  56650. }
  56651. ;
  56652. var defines = [];
  56653. if (this._scene.clipPlane) {
  56654. defines.push("#define CLIPPLANE");
  56655. }
  56656. if (this._isAnimationSheetEnabled) {
  56657. defines.push("#define ANIMATESHEET");
  56658. }
  56659. // Effect
  56660. var join = defines.join("\n");
  56661. if (this._cachedDefines !== join) {
  56662. this._cachedDefines = join;
  56663. var attributesNamesOrOptions;
  56664. var effectCreationOption;
  56665. if (this._isAnimationSheetEnabled) {
  56666. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56667. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56668. }
  56669. else {
  56670. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56671. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56672. }
  56673. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56674. }
  56675. return this._effect;
  56676. };
  56677. /**
  56678. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56679. */
  56680. ParticleSystem.prototype.animate = function () {
  56681. if (!this._started)
  56682. return;
  56683. var effect = this._getEffect();
  56684. // Check
  56685. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56686. return;
  56687. if (this._currentRenderId === this._scene.getRenderId()) {
  56688. return;
  56689. }
  56690. this._currentRenderId = this._scene.getRenderId();
  56691. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56692. // determine the number of particles we need to create
  56693. var newParticles;
  56694. if (this.manualEmitCount > -1) {
  56695. newParticles = this.manualEmitCount;
  56696. this._newPartsExcess = 0;
  56697. this.manualEmitCount = 0;
  56698. }
  56699. else {
  56700. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56701. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56702. }
  56703. if (this._newPartsExcess > 1.0) {
  56704. newParticles += this._newPartsExcess >> 0;
  56705. this._newPartsExcess -= this._newPartsExcess >> 0;
  56706. }
  56707. this._alive = false;
  56708. if (!this._stopped) {
  56709. this._actualFrame += this._scaledUpdateSpeed;
  56710. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56711. this.stop();
  56712. }
  56713. else {
  56714. newParticles = 0;
  56715. }
  56716. this._update(newParticles);
  56717. // Stopped?
  56718. if (this._stopped) {
  56719. if (!this._alive) {
  56720. this._started = false;
  56721. if (this.onAnimationEnd) {
  56722. this.onAnimationEnd();
  56723. }
  56724. if (this.disposeOnStop) {
  56725. this._scene._toBeDisposed.push(this);
  56726. }
  56727. }
  56728. }
  56729. // Animation sheet
  56730. if (this._isAnimationSheetEnabled) {
  56731. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56732. }
  56733. else {
  56734. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56735. }
  56736. // Update VBO
  56737. var offset = 0;
  56738. for (var index = 0; index < this._particles.length; index++) {
  56739. var particle = this._particles[index];
  56740. this._appendParticleVertexes(offset, particle);
  56741. offset += 4;
  56742. }
  56743. if (this._vertexBuffer) {
  56744. this._vertexBuffer.update(this._vertexData);
  56745. }
  56746. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56747. this.stop();
  56748. }
  56749. };
  56750. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56751. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56752. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56753. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56754. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56755. };
  56756. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56757. this._appendParticleVertex(offset++, particle, 0, 0);
  56758. this._appendParticleVertex(offset++, particle, 1, 0);
  56759. this._appendParticleVertex(offset++, particle, 1, 1);
  56760. this._appendParticleVertex(offset++, particle, 0, 1);
  56761. };
  56762. /**
  56763. * Rebuilds the particle system.
  56764. */
  56765. ParticleSystem.prototype.rebuild = function () {
  56766. this._createIndexBuffer();
  56767. if (this._vertexBuffer) {
  56768. this._vertexBuffer._rebuild();
  56769. }
  56770. };
  56771. /**
  56772. * Is this system ready to be used/rendered
  56773. * @return true if the system is ready
  56774. */
  56775. ParticleSystem.prototype.isReady = function () {
  56776. var effect = this._getEffect();
  56777. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56778. return false;
  56779. }
  56780. return true;
  56781. };
  56782. /**
  56783. * Renders the particle system in its current state.
  56784. * @returns the current number of particles
  56785. */
  56786. ParticleSystem.prototype.render = function () {
  56787. var effect = this._getEffect();
  56788. // Check
  56789. if (!this.isReady() || !this._particles.length) {
  56790. return 0;
  56791. }
  56792. var engine = this._scene.getEngine();
  56793. // Render
  56794. engine.enableEffect(effect);
  56795. engine.setState(false);
  56796. var viewMatrix = this._scene.getViewMatrix();
  56797. effect.setTexture("diffuseSampler", this.particleTexture);
  56798. effect.setMatrix("view", viewMatrix);
  56799. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56800. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56801. var baseSize = this.particleTexture.getBaseSize();
  56802. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56803. }
  56804. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56805. if (this._scene.clipPlane) {
  56806. var clipPlane = this._scene.clipPlane;
  56807. var invView = viewMatrix.clone();
  56808. invView.invert();
  56809. effect.setMatrix("invView", invView);
  56810. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56811. }
  56812. // VBOs
  56813. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56814. // Draw order
  56815. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56816. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56817. }
  56818. else {
  56819. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56820. }
  56821. if (this.forceDepthWrite) {
  56822. engine.setDepthWrite(true);
  56823. }
  56824. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56825. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56826. return this._particles.length;
  56827. };
  56828. /**
  56829. * Disposes the particle system and free the associated resources
  56830. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56831. */
  56832. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56833. if (disposeTexture === void 0) { disposeTexture = true; }
  56834. if (this._vertexBuffer) {
  56835. this._vertexBuffer.dispose();
  56836. this._vertexBuffer = null;
  56837. }
  56838. if (this._indexBuffer) {
  56839. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56840. this._indexBuffer = null;
  56841. }
  56842. if (disposeTexture && this.particleTexture) {
  56843. this.particleTexture.dispose();
  56844. this.particleTexture = null;
  56845. }
  56846. this._removeFromRoot();
  56847. // Remove from scene
  56848. var index = this._scene.particleSystems.indexOf(this);
  56849. if (index > -1) {
  56850. this._scene.particleSystems.splice(index, 1);
  56851. }
  56852. // Callback
  56853. this.onDisposeObservable.notifyObservers(this);
  56854. this.onDisposeObservable.clear();
  56855. };
  56856. /**
  56857. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56858. * @param radius The radius of the sphere to emit from
  56859. * @returns the emitter
  56860. */
  56861. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56862. if (radius === void 0) { radius = 1; }
  56863. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56864. this.particleEmitterType = particleEmitter;
  56865. return particleEmitter;
  56866. };
  56867. /**
  56868. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56869. * @param radius The radius of the sphere to emit from
  56870. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56871. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56872. * @returns the emitter
  56873. */
  56874. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56875. if (radius === void 0) { radius = 1; }
  56876. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56877. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56878. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56879. this.particleEmitterType = particleEmitter;
  56880. return particleEmitter;
  56881. };
  56882. /**
  56883. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56884. * @param radius The radius of the cone to emit from
  56885. * @param angle The base angle of the cone
  56886. * @returns the emitter
  56887. */
  56888. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56889. if (radius === void 0) { radius = 1; }
  56890. if (angle === void 0) { angle = Math.PI / 4; }
  56891. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56892. this.particleEmitterType = particleEmitter;
  56893. return particleEmitter;
  56894. };
  56895. // this method needs to be changed when breaking changes will be allowed to match the sphere and cone methods and properties direction1,2 and minEmitBox,maxEmitBox to be removed from the system.
  56896. /**
  56897. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56898. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56899. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56900. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56901. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56902. * @returns the emitter
  56903. */
  56904. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56905. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56906. this.particleEmitterType = particleEmitter;
  56907. this.direction1 = direction1;
  56908. this.direction2 = direction2;
  56909. this.minEmitBox = minEmitBox;
  56910. this.maxEmitBox = maxEmitBox;
  56911. return particleEmitter;
  56912. };
  56913. // Clone
  56914. /**
  56915. * Clones the particle system.
  56916. * @param name The name of the cloned object
  56917. * @param newEmitter The new emitter to use
  56918. * @returns the cloned particle system
  56919. */
  56920. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56921. var custom = null;
  56922. var program = null;
  56923. if (this.customShader != null) {
  56924. program = this.customShader;
  56925. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56926. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56927. }
  56928. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56929. result.customShader = program;
  56930. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56931. if (newEmitter === undefined) {
  56932. newEmitter = this.emitter;
  56933. }
  56934. result.emitter = newEmitter;
  56935. if (this.particleTexture) {
  56936. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56937. }
  56938. if (!this.preventAutoStart) {
  56939. result.start();
  56940. }
  56941. return result;
  56942. };
  56943. /**
  56944. * Serializes the particle system to a JSON object.
  56945. * @returns the JSON object
  56946. */
  56947. ParticleSystem.prototype.serialize = function () {
  56948. var serializationObject = {};
  56949. serializationObject.name = this.name;
  56950. serializationObject.id = this.id;
  56951. // Emitter
  56952. if (this.emitter.position) {
  56953. var emitterMesh = this.emitter;
  56954. serializationObject.emitterId = emitterMesh.id;
  56955. }
  56956. else {
  56957. var emitterPosition = this.emitter;
  56958. serializationObject.emitter = emitterPosition.asArray();
  56959. }
  56960. serializationObject.capacity = this.getCapacity();
  56961. if (this.particleTexture) {
  56962. serializationObject.textureName = this.particleTexture.name;
  56963. }
  56964. // Animations
  56965. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56966. // Particle system
  56967. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56968. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56969. serializationObject.minSize = this.minSize;
  56970. serializationObject.maxSize = this.maxSize;
  56971. serializationObject.minEmitPower = this.minEmitPower;
  56972. serializationObject.maxEmitPower = this.maxEmitPower;
  56973. serializationObject.minLifeTime = this.minLifeTime;
  56974. serializationObject.maxLifeTime = this.maxLifeTime;
  56975. serializationObject.emitRate = this.emitRate;
  56976. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56977. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56978. serializationObject.gravity = this.gravity.asArray();
  56979. serializationObject.direction1 = this.direction1.asArray();
  56980. serializationObject.direction2 = this.direction2.asArray();
  56981. serializationObject.color1 = this.color1.asArray();
  56982. serializationObject.color2 = this.color2.asArray();
  56983. serializationObject.colorDead = this.colorDead.asArray();
  56984. serializationObject.updateSpeed = this.updateSpeed;
  56985. serializationObject.targetStopDuration = this.targetStopDuration;
  56986. serializationObject.textureMask = this.textureMask.asArray();
  56987. serializationObject.blendMode = this.blendMode;
  56988. serializationObject.customShader = this.customShader;
  56989. serializationObject.preventAutoStart = this.preventAutoStart;
  56990. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56991. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56992. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56993. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56994. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56995. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56996. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56997. // Emitter
  56998. if (this.particleEmitterType) {
  56999. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57000. }
  57001. return serializationObject;
  57002. };
  57003. /**
  57004. * Parses a JSON object to create a particle system.
  57005. * @param parsedParticleSystem The JSON object to parse
  57006. * @param scene The scene to create the particle system in
  57007. * @param rootUrl The root url to use to load external dependencies like texture
  57008. * @returns the Parsed particle system
  57009. */
  57010. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57011. var name = parsedParticleSystem.name;
  57012. var custom = null;
  57013. var program = null;
  57014. if (parsedParticleSystem.customShader) {
  57015. program = parsedParticleSystem.customShader;
  57016. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57017. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57018. }
  57019. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  57020. particleSystem.customShader = program;
  57021. if (parsedParticleSystem.id) {
  57022. particleSystem.id = parsedParticleSystem.id;
  57023. }
  57024. // Auto start
  57025. if (parsedParticleSystem.preventAutoStart) {
  57026. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  57027. }
  57028. // Texture
  57029. if (parsedParticleSystem.textureName) {
  57030. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57031. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57032. }
  57033. // Emitter
  57034. if (parsedParticleSystem.emitterId) {
  57035. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57036. }
  57037. else {
  57038. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57039. }
  57040. // Animations
  57041. if (parsedParticleSystem.animations) {
  57042. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57043. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57044. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57045. }
  57046. }
  57047. if (parsedParticleSystem.autoAnimate) {
  57048. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  57049. }
  57050. // Particle system
  57051. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57052. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57053. particleSystem.minSize = parsedParticleSystem.minSize;
  57054. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57055. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57056. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57057. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57058. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57059. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57060. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  57061. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  57062. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57063. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  57064. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  57065. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57066. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57067. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57068. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57069. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57070. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  57071. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57072. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  57073. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  57074. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  57075. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  57076. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  57077. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  57078. if (!particleSystem.preventAutoStart) {
  57079. particleSystem.start();
  57080. }
  57081. return particleSystem;
  57082. };
  57083. /**
  57084. * Source color is added to the destination color without alpha affecting the result.
  57085. */
  57086. ParticleSystem.BLENDMODE_ONEONE = 0;
  57087. /**
  57088. * Blend current color and particle color using particle’s alpha.
  57089. */
  57090. ParticleSystem.BLENDMODE_STANDARD = 1;
  57091. return ParticleSystem;
  57092. }());
  57093. BABYLON.ParticleSystem = ParticleSystem;
  57094. })(BABYLON || (BABYLON = {}));
  57095. //# sourceMappingURL=babylon.particleSystem.js.map
  57096. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  57097. var BABYLON;
  57098. (function (BABYLON) {
  57099. /**
  57100. * Particle emitter emitting particles from the inside of a box.
  57101. * It emits the particles randomly between 2 given directions.
  57102. */
  57103. var BoxParticleEmitter = /** @class */ (function () {
  57104. /**
  57105. * Creates a new instance BoxParticleEmitter
  57106. */
  57107. function BoxParticleEmitter() {
  57108. /**
  57109. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57110. */
  57111. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  57112. /**
  57113. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57114. */
  57115. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  57116. /**
  57117. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  57118. */
  57119. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  57120. /**
  57121. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  57122. */
  57123. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  57124. }
  57125. /**
  57126. * Called by the particle System when the direction is computed for the created particle.
  57127. * @param emitPower is the power of the particle (speed)
  57128. * @param worldMatrix is the world matrix of the particle system
  57129. * @param directionToUpdate is the direction vector to update with the result
  57130. * @param particle is the particle we are computed the direction for
  57131. */
  57132. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57133. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57134. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57135. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57136. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57137. };
  57138. /**
  57139. * Called by the particle System when the position is computed for the created particle.
  57140. * @param worldMatrix is the world matrix of the particle system
  57141. * @param positionToUpdate is the position vector to update with the result
  57142. * @param particle is the particle we are computed the position for
  57143. */
  57144. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57145. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  57146. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  57147. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  57148. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57149. };
  57150. /**
  57151. * Clones the current emitter and returns a copy of it
  57152. * @returns the new emitter
  57153. */
  57154. BoxParticleEmitter.prototype.clone = function () {
  57155. var newOne = new BoxParticleEmitter();
  57156. BABYLON.Tools.DeepCopy(this, newOne);
  57157. return newOne;
  57158. };
  57159. /**
  57160. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57161. * @param effect defines the update shader
  57162. */
  57163. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  57164. effect.setVector3("direction1", this.direction1);
  57165. effect.setVector3("direction2", this.direction2);
  57166. effect.setVector3("minEmitBox", this.minEmitBox);
  57167. effect.setVector3("maxEmitBox", this.maxEmitBox);
  57168. };
  57169. /**
  57170. * Returns a string to use to update the GPU particles update shader
  57171. * @returns a string containng the defines string
  57172. */
  57173. BoxParticleEmitter.prototype.getEffectDefines = function () {
  57174. return "#define BOXEMITTER";
  57175. };
  57176. /**
  57177. * Returns the string "BoxEmitter"
  57178. * @returns a string containing the class name
  57179. */
  57180. BoxParticleEmitter.prototype.getClassName = function () {
  57181. return "BoxEmitter";
  57182. };
  57183. /**
  57184. * Serializes the particle system to a JSON object.
  57185. * @returns the JSON object
  57186. */
  57187. BoxParticleEmitter.prototype.serialize = function () {
  57188. var serializationObject = {};
  57189. serializationObject.type = this.getClassName();
  57190. serializationObject.direction1 = this.direction1.asArray();
  57191. serializationObject.direction2 = this.direction2.asArray();
  57192. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57193. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57194. return serializationObject;
  57195. };
  57196. /**
  57197. * Parse properties from a JSON object
  57198. * @param serializationObject defines the JSON object
  57199. */
  57200. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  57201. this.direction1.copyFrom(serializationObject.direction1);
  57202. this.direction2.copyFrom(serializationObject.direction2);
  57203. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  57204. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  57205. };
  57206. return BoxParticleEmitter;
  57207. }());
  57208. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  57209. })(BABYLON || (BABYLON = {}));
  57210. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  57211. var BABYLON;
  57212. (function (BABYLON) {
  57213. /**
  57214. * Particle emitter emitting particles from the inside of a cone.
  57215. * It emits the particles alongside the cone volume from the base to the particle.
  57216. * The emission direction might be randomized.
  57217. */
  57218. var ConeParticleEmitter = /** @class */ (function () {
  57219. /**
  57220. * Creates a new instance ConeParticleEmitter
  57221. * @param radius the radius of the emission cone (1 by default)
  57222. * @param angles the cone base angle (PI by default)
  57223. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57224. */
  57225. function ConeParticleEmitter(radius,
  57226. /**
  57227. * The radius of the emission cone.
  57228. */
  57229. angle,
  57230. /**
  57231. * The cone base angle.
  57232. */
  57233. directionRandomizer) {
  57234. if (radius === void 0) { radius = 1; }
  57235. if (angle === void 0) { angle = Math.PI; }
  57236. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57237. this.angle = angle;
  57238. this.directionRandomizer = directionRandomizer;
  57239. this.radius = radius;
  57240. }
  57241. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  57242. /**
  57243. * Gets the radius of the emission cone.
  57244. */
  57245. get: function () {
  57246. return this._radius;
  57247. },
  57248. /**
  57249. * Sets the radius of the emission cone.
  57250. */
  57251. set: function (value) {
  57252. this._radius = value;
  57253. if (this.angle !== 0) {
  57254. this._height = value / Math.tan(this.angle / 2);
  57255. }
  57256. else {
  57257. this._height = 1;
  57258. }
  57259. },
  57260. enumerable: true,
  57261. configurable: true
  57262. });
  57263. /**
  57264. * Called by the particle System when the direction is computed for the created particle.
  57265. * @param emitPower is the power of the particle (speed)
  57266. * @param worldMatrix is the world matrix of the particle system
  57267. * @param directionToUpdate is the direction vector to update with the result
  57268. * @param particle is the particle we are computed the direction for
  57269. */
  57270. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57271. if (this.angle === 0) {
  57272. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  57273. }
  57274. else {
  57275. // measure the direction Vector from the emitter to the particle.
  57276. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57277. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57278. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57279. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57280. direction.x += randX;
  57281. direction.y += randY;
  57282. direction.z += randZ;
  57283. direction.normalize();
  57284. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57285. }
  57286. };
  57287. /**
  57288. * Called by the particle System when the position is computed for the created particle.
  57289. * @param worldMatrix is the world matrix of the particle system
  57290. * @param positionToUpdate is the position vector to update with the result
  57291. * @param particle is the particle we are computed the position for
  57292. */
  57293. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57294. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  57295. var h = BABYLON.Scalar.RandomRange(0, 1);
  57296. // Better distribution in a cone at normal angles.
  57297. h = 1 - h * h;
  57298. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  57299. radius = radius * h;
  57300. var randX = radius * Math.sin(s);
  57301. var randZ = radius * Math.cos(s);
  57302. var randY = h * this._height;
  57303. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57304. };
  57305. /**
  57306. * Clones the current emitter and returns a copy of it
  57307. * @returns the new emitter
  57308. */
  57309. ConeParticleEmitter.prototype.clone = function () {
  57310. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  57311. BABYLON.Tools.DeepCopy(this, newOne);
  57312. return newOne;
  57313. };
  57314. /**
  57315. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57316. * @param effect defines the update shader
  57317. */
  57318. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  57319. effect.setFloat("radius", this.radius);
  57320. effect.setFloat("coneAngle", this.angle);
  57321. effect.setFloat("height", this._height);
  57322. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57323. };
  57324. /**
  57325. * Returns a string to use to update the GPU particles update shader
  57326. * @returns a string containng the defines string
  57327. */
  57328. ConeParticleEmitter.prototype.getEffectDefines = function () {
  57329. return "#define CONEEMITTER";
  57330. };
  57331. /**
  57332. * Returns the string "BoxEmitter"
  57333. * @returns a string containing the class name
  57334. */
  57335. ConeParticleEmitter.prototype.getClassName = function () {
  57336. return "ConeEmitter";
  57337. };
  57338. /**
  57339. * Serializes the particle system to a JSON object.
  57340. * @returns the JSON object
  57341. */
  57342. ConeParticleEmitter.prototype.serialize = function () {
  57343. var serializationObject = {};
  57344. serializationObject.type = this.getClassName();
  57345. serializationObject.radius = this.radius;
  57346. serializationObject.angle = this.angle;
  57347. serializationObject.directionRandomizer = this.directionRandomizer;
  57348. return serializationObject;
  57349. };
  57350. /**
  57351. * Parse properties from a JSON object
  57352. * @param serializationObject defines the JSON object
  57353. */
  57354. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  57355. this.radius = serializationObject.radius;
  57356. this.angle = serializationObject.angle;
  57357. this.directionRandomizer = serializationObject.directionRandomizer;
  57358. };
  57359. return ConeParticleEmitter;
  57360. }());
  57361. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  57362. })(BABYLON || (BABYLON = {}));
  57363. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  57364. var BABYLON;
  57365. (function (BABYLON) {
  57366. /**
  57367. * Particle emitter emitting particles from the inside of a sphere.
  57368. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  57369. */
  57370. var SphereParticleEmitter = /** @class */ (function () {
  57371. /**
  57372. * Creates a new instance SphereParticleEmitter
  57373. * @param radius the radius of the emission sphere (1 by default)
  57374. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57375. */
  57376. function SphereParticleEmitter(
  57377. /**
  57378. * The radius of the emission sphere.
  57379. */
  57380. radius,
  57381. /**
  57382. * How much to randomize the particle direction [0-1].
  57383. */
  57384. directionRandomizer) {
  57385. if (radius === void 0) { radius = 1; }
  57386. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57387. this.radius = radius;
  57388. this.directionRandomizer = directionRandomizer;
  57389. }
  57390. /**
  57391. * Called by the particle System when the direction is computed for the created particle.
  57392. * @param emitPower is the power of the particle (speed)
  57393. * @param worldMatrix is the world matrix of the particle system
  57394. * @param directionToUpdate is the direction vector to update with the result
  57395. * @param particle is the particle we are computed the direction for
  57396. */
  57397. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57398. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57399. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57400. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57401. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57402. direction.x += randX;
  57403. direction.y += randY;
  57404. direction.z += randZ;
  57405. direction.normalize();
  57406. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57407. };
  57408. /**
  57409. * Called by the particle System when the position is computed for the created particle.
  57410. * @param worldMatrix is the world matrix of the particle system
  57411. * @param positionToUpdate is the position vector to update with the result
  57412. * @param particle is the particle we are computed the position for
  57413. */
  57414. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57415. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57416. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  57417. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  57418. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57419. var randY = randRadius * Math.cos(theta);
  57420. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57421. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57422. };
  57423. /**
  57424. * Clones the current emitter and returns a copy of it
  57425. * @returns the new emitter
  57426. */
  57427. SphereParticleEmitter.prototype.clone = function () {
  57428. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  57429. BABYLON.Tools.DeepCopy(this, newOne);
  57430. return newOne;
  57431. };
  57432. /**
  57433. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57434. * @param effect defines the update shader
  57435. */
  57436. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57437. effect.setFloat("radius", this.radius);
  57438. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57439. };
  57440. /**
  57441. * Returns a string to use to update the GPU particles update shader
  57442. * @returns a string containng the defines string
  57443. */
  57444. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57445. return "#define SPHEREEMITTER";
  57446. };
  57447. /**
  57448. * Returns the string "SphereParticleEmitter"
  57449. * @returns a string containing the class name
  57450. */
  57451. SphereParticleEmitter.prototype.getClassName = function () {
  57452. return "SphereParticleEmitter";
  57453. };
  57454. /**
  57455. * Serializes the particle system to a JSON object.
  57456. * @returns the JSON object
  57457. */
  57458. SphereParticleEmitter.prototype.serialize = function () {
  57459. var serializationObject = {};
  57460. serializationObject.type = this.getClassName();
  57461. serializationObject.radius = this.radius;
  57462. serializationObject.directionRandomizer = this.directionRandomizer;
  57463. return serializationObject;
  57464. };
  57465. /**
  57466. * Parse properties from a JSON object
  57467. * @param serializationObject defines the JSON object
  57468. */
  57469. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57470. this.radius = serializationObject.radius;
  57471. this.directionRandomizer = serializationObject.directionRandomizer;
  57472. };
  57473. return SphereParticleEmitter;
  57474. }());
  57475. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57476. /**
  57477. * Particle emitter emitting particles from the inside of a sphere.
  57478. * It emits the particles randomly between two vectors.
  57479. */
  57480. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57481. __extends(SphereDirectedParticleEmitter, _super);
  57482. /**
  57483. * Creates a new instance SphereDirectedParticleEmitter
  57484. * @param radius the radius of the emission sphere (1 by default)
  57485. * @param direction1 the min limit of the emission direction (up vector by default)
  57486. * @param direction2 the max limit of the emission direction (up vector by default)
  57487. */
  57488. function SphereDirectedParticleEmitter(radius,
  57489. /**
  57490. * The min limit of the emission direction.
  57491. */
  57492. direction1,
  57493. /**
  57494. * The max limit of the emission direction.
  57495. */
  57496. direction2) {
  57497. if (radius === void 0) { radius = 1; }
  57498. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57499. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57500. var _this = _super.call(this, radius) || this;
  57501. _this.direction1 = direction1;
  57502. _this.direction2 = direction2;
  57503. return _this;
  57504. }
  57505. /**
  57506. * Called by the particle System when the direction is computed for the created particle.
  57507. * @param emitPower is the power of the particle (speed)
  57508. * @param worldMatrix is the world matrix of the particle system
  57509. * @param directionToUpdate is the direction vector to update with the result
  57510. * @param particle is the particle we are computed the direction for
  57511. */
  57512. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57513. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57514. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57515. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57516. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57517. };
  57518. /**
  57519. * Clones the current emitter and returns a copy of it
  57520. * @returns the new emitter
  57521. */
  57522. SphereDirectedParticleEmitter.prototype.clone = function () {
  57523. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57524. BABYLON.Tools.DeepCopy(this, newOne);
  57525. return newOne;
  57526. };
  57527. /**
  57528. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57529. * @param effect defines the update shader
  57530. */
  57531. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57532. effect.setFloat("radius", this.radius);
  57533. effect.setVector3("direction1", this.direction1);
  57534. effect.setVector3("direction2", this.direction2);
  57535. };
  57536. /**
  57537. * Returns a string to use to update the GPU particles update shader
  57538. * @returns a string containng the defines string
  57539. */
  57540. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57541. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57542. };
  57543. /**
  57544. * Returns the string "SphereDirectedParticleEmitter"
  57545. * @returns a string containing the class name
  57546. */
  57547. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57548. return "SphereDirectedParticleEmitter";
  57549. };
  57550. /**
  57551. * Serializes the particle system to a JSON object.
  57552. * @returns the JSON object
  57553. */
  57554. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57555. var serializationObject = _super.prototype.serialize.call(this);
  57556. serializationObject.direction1 = this.direction1.asArray();
  57557. serializationObject.direction2 = this.direction2.asArray();
  57558. return serializationObject;
  57559. };
  57560. /**
  57561. * Parse properties from a JSON object
  57562. * @param serializationObject defines the JSON object
  57563. */
  57564. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57565. _super.prototype.parse.call(this, serializationObject);
  57566. this.direction1.copyFrom(serializationObject.direction1);
  57567. this.direction2.copyFrom(serializationObject.direction2);
  57568. };
  57569. return SphereDirectedParticleEmitter;
  57570. }(SphereParticleEmitter));
  57571. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57572. })(BABYLON || (BABYLON = {}));
  57573. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57574. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57575. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57576. s = arguments[i];
  57577. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57578. t[p] = s[p];
  57579. }
  57580. return t;
  57581. };
  57582. var BABYLON;
  57583. (function (BABYLON) {
  57584. /**
  57585. * This represents a GPU particle system in Babylon
  57586. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57587. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57588. */
  57589. var GPUParticleSystem = /** @class */ (function () {
  57590. /**
  57591. * Instantiates a GPU particle system.
  57592. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  57593. * @param name The name of the particle system
  57594. * @param capacity The max number of particles alive at the same time
  57595. * @param scene The scene the particle system belongs to
  57596. */
  57597. function GPUParticleSystem(name, options, scene) {
  57598. /**
  57599. * The emitter represents the Mesh or position we are attaching the particle system to.
  57600. */
  57601. this.emitter = null;
  57602. /**
  57603. * The rendering group used by the Particle system to chose when to render.
  57604. */
  57605. this.renderingGroupId = 0;
  57606. /**
  57607. * The layer mask we are rendering the particles through.
  57608. */
  57609. this.layerMask = 0x0FFFFFFF;
  57610. this._targetIndex = 0;
  57611. this._currentRenderId = -1;
  57612. this._started = false;
  57613. this._stopped = false;
  57614. this._timeDelta = 0;
  57615. this._attributesStrideSize = 16;
  57616. this._actualFrame = 0;
  57617. /**
  57618. * List of animations used by the particle system.
  57619. */
  57620. this.animations = [];
  57621. /**
  57622. * An event triggered when the system is disposed.
  57623. */
  57624. this.onDisposeObservable = new BABYLON.Observable();
  57625. /**
  57626. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57627. */
  57628. this.updateSpeed = 0.01;
  57629. /**
  57630. * The amount of time the particle system is running (depends of the overall update speed).
  57631. */
  57632. this.targetStopDuration = 0;
  57633. /**
  57634. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57635. */
  57636. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57637. /**
  57638. * Minimum life time of emitting particles.
  57639. */
  57640. this.minLifeTime = 1;
  57641. /**
  57642. * Maximum life time of emitting particles.
  57643. */
  57644. this.maxLifeTime = 1;
  57645. /**
  57646. * Minimum Size of emitting particles.
  57647. */
  57648. this.minSize = 1;
  57649. /**
  57650. * Maximum Size of emitting particles.
  57651. */
  57652. this.maxSize = 1;
  57653. /**
  57654. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57655. */
  57656. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57657. /**
  57658. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57659. */
  57660. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57661. /**
  57662. * Color the particle will have at the end of its lifetime.
  57663. */
  57664. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57665. /**
  57666. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57667. */
  57668. this.emitRate = 100;
  57669. /**
  57670. * You can use gravity if you want to give an orientation to your particles.
  57671. */
  57672. this.gravity = BABYLON.Vector3.Zero();
  57673. /**
  57674. * Minimum power of emitting particles.
  57675. */
  57676. this.minEmitPower = 1;
  57677. /**
  57678. * Maximum power of emitting particles.
  57679. */
  57680. this.maxEmitPower = 1;
  57681. /**
  57682. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57683. */
  57684. this.minAngularSpeed = 0;
  57685. /**
  57686. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57687. */
  57688. this.maxAngularSpeed = 0;
  57689. /**
  57690. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57691. * to override the particles.
  57692. */
  57693. this.forceDepthWrite = false;
  57694. this.id = name;
  57695. this.name = name;
  57696. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57697. this._engine = this._scene.getEngine();
  57698. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57699. this._capacity = fullOptions.capacity;
  57700. this._activeCount = fullOptions.capacity;
  57701. this._currentActiveCount = 0;
  57702. this._scene.particleSystems.push(this);
  57703. this._updateEffectOptions = {
  57704. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "angle"],
  57705. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57706. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  57707. "angleRange"],
  57708. uniformBuffersNames: [],
  57709. samplers: ["randomSampler"],
  57710. defines: "",
  57711. fallbacks: null,
  57712. onCompiled: null,
  57713. onError: null,
  57714. indexParameters: null,
  57715. maxSimultaneousLights: 0,
  57716. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection", "outAngle"]
  57717. };
  57718. // Random data
  57719. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57720. var d = [];
  57721. for (var i = 0; i < maxTextureSize; ++i) {
  57722. d.push(Math.random());
  57723. d.push(Math.random());
  57724. d.push(Math.random());
  57725. d.push(Math.random());
  57726. }
  57727. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA32F, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57728. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57729. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57730. this._randomTextureSize = maxTextureSize;
  57731. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57732. }
  57733. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57734. /**
  57735. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57736. */
  57737. get: function () {
  57738. if (!BABYLON.Engine.LastCreatedEngine) {
  57739. return false;
  57740. }
  57741. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57742. },
  57743. enumerable: true,
  57744. configurable: true
  57745. });
  57746. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57747. /**
  57748. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57749. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57750. */
  57751. get: function () {
  57752. if (this.particleEmitterType.direction1) {
  57753. return this.particleEmitterType.direction1;
  57754. }
  57755. return BABYLON.Vector3.Zero();
  57756. },
  57757. set: function (value) {
  57758. if (this.particleEmitterType.direction1) {
  57759. this.particleEmitterType.direction1 = value;
  57760. }
  57761. },
  57762. enumerable: true,
  57763. configurable: true
  57764. });
  57765. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57766. /**
  57767. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57768. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57769. */
  57770. get: function () {
  57771. if (this.particleEmitterType.direction2) {
  57772. return this.particleEmitterType.direction2;
  57773. }
  57774. return BABYLON.Vector3.Zero();
  57775. },
  57776. set: function (value) {
  57777. if (this.particleEmitterType.direction2) {
  57778. this.particleEmitterType.direction2 = value;
  57779. }
  57780. },
  57781. enumerable: true,
  57782. configurable: true
  57783. });
  57784. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57785. /**
  57786. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  57787. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57788. */
  57789. get: function () {
  57790. if (this.particleEmitterType.minEmitBox) {
  57791. return this.particleEmitterType.minEmitBox;
  57792. }
  57793. return BABYLON.Vector3.Zero();
  57794. },
  57795. set: function (value) {
  57796. if (this.particleEmitterType.minEmitBox) {
  57797. this.particleEmitterType.minEmitBox = value;
  57798. }
  57799. },
  57800. enumerable: true,
  57801. configurable: true
  57802. });
  57803. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57804. /**
  57805. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  57806. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57807. */
  57808. get: function () {
  57809. if (this.particleEmitterType.maxEmitBox) {
  57810. return this.particleEmitterType.maxEmitBox;
  57811. }
  57812. return BABYLON.Vector3.Zero();
  57813. },
  57814. set: function (value) {
  57815. if (this.particleEmitterType.maxEmitBox) {
  57816. this.particleEmitterType.maxEmitBox = value;
  57817. }
  57818. },
  57819. enumerable: true,
  57820. configurable: true
  57821. });
  57822. /**
  57823. * Gets the maximum number of particles active at the same time.
  57824. * @returns The max number of active particles.
  57825. */
  57826. GPUParticleSystem.prototype.getCapacity = function () {
  57827. return this._capacity;
  57828. };
  57829. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57830. /**
  57831. * Gets or set the number of active particles
  57832. */
  57833. get: function () {
  57834. return this._activeCount;
  57835. },
  57836. set: function (value) {
  57837. this._activeCount = Math.min(value, this._capacity);
  57838. },
  57839. enumerable: true,
  57840. configurable: true
  57841. });
  57842. /**
  57843. * Is this system ready to be used/rendered
  57844. * @return true if the system is ready
  57845. */
  57846. GPUParticleSystem.prototype.isReady = function () {
  57847. if (!this._updateEffect) {
  57848. this._recreateUpdateEffect();
  57849. this._recreateRenderEffect();
  57850. return false;
  57851. }
  57852. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57853. return false;
  57854. }
  57855. return true;
  57856. };
  57857. /**
  57858. * Gets Wether the system has been started.
  57859. * @returns True if it has been started, otherwise false.
  57860. */
  57861. GPUParticleSystem.prototype.isStarted = function () {
  57862. return this._started;
  57863. };
  57864. /**
  57865. * Starts the particle system and begins to emit.
  57866. */
  57867. GPUParticleSystem.prototype.start = function () {
  57868. this._started = true;
  57869. this._stopped = false;
  57870. };
  57871. /**
  57872. * Stops the particle system.
  57873. */
  57874. GPUParticleSystem.prototype.stop = function () {
  57875. this._stopped = true;
  57876. };
  57877. /**
  57878. * Remove all active particles
  57879. */
  57880. GPUParticleSystem.prototype.reset = function () {
  57881. this._releaseBuffers();
  57882. this._releaseVAOs();
  57883. this._currentActiveCount = 0;
  57884. this._targetIndex = 0;
  57885. };
  57886. /**
  57887. * Returns the string "GPUParticleSystem"
  57888. * @returns a string containing the class name
  57889. */
  57890. GPUParticleSystem.prototype.getClassName = function () {
  57891. return "GPUParticleSystem";
  57892. };
  57893. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57894. var updateVertexBuffers = {};
  57895. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57896. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57897. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57898. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  57899. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  57900. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  57901. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  57902. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", 14, 2);
  57903. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57904. this._engine.bindArrayBuffer(null);
  57905. return vao;
  57906. };
  57907. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57908. var renderVertexBuffers = {};
  57909. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57910. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57911. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57912. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  57913. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  57914. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", 14, 2, this._attributesStrideSize, true);
  57915. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57916. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57917. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57918. this._engine.bindArrayBuffer(null);
  57919. return vao;
  57920. };
  57921. GPUParticleSystem.prototype._initialize = function (force) {
  57922. if (force === void 0) { force = false; }
  57923. if (this._buffer0 && !force) {
  57924. return;
  57925. }
  57926. var engine = this._scene.getEngine();
  57927. var data = new Array();
  57928. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57929. // position
  57930. data.push(0.0);
  57931. data.push(0.0);
  57932. data.push(0.0);
  57933. // Age and life
  57934. data.push(0.0); // create the particle as a dead one to create a new one at start
  57935. data.push(0.0);
  57936. // Seed
  57937. data.push(Math.random());
  57938. // Size
  57939. data.push(0.0);
  57940. // color
  57941. data.push(0.0);
  57942. data.push(0.0);
  57943. data.push(0.0);
  57944. data.push(0.0);
  57945. // direction
  57946. data.push(0.0);
  57947. data.push(0.0);
  57948. data.push(0.0);
  57949. // angle
  57950. data.push(0.0);
  57951. data.push(0.0);
  57952. }
  57953. // Sprite data
  57954. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57955. -0.5, 0.5, 0, 1,
  57956. -0.5, -0.5, 0, 0,
  57957. 0.5, -0.5, 1, 0]);
  57958. // Buffers
  57959. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57960. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57961. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57962. // Update VAO
  57963. this._updateVAO = [];
  57964. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57965. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57966. // Render VAO
  57967. this._renderVAO = [];
  57968. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57969. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57970. // Links
  57971. this._sourceBuffer = this._buffer0;
  57972. this._targetBuffer = this._buffer1;
  57973. };
  57974. /** @hidden */
  57975. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57976. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57977. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57978. return;
  57979. }
  57980. this._updateEffectOptions.defines = defines;
  57981. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57982. };
  57983. /** @hidden */
  57984. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57985. var defines = "";
  57986. if (this._scene.clipPlane) {
  57987. defines = "\n#define CLIPPLANE";
  57988. }
  57989. if (this._renderEffect && this._renderEffect.defines === defines) {
  57990. return;
  57991. }
  57992. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "angle"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57993. };
  57994. /**
  57995. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57996. */
  57997. GPUParticleSystem.prototype.animate = function () {
  57998. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57999. this._actualFrame += this._timeDelta;
  58000. if (!this._stopped) {
  58001. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  58002. this.stop();
  58003. }
  58004. }
  58005. };
  58006. /**
  58007. * Renders the particle system in its current state.
  58008. * @returns the current number of particles
  58009. */
  58010. GPUParticleSystem.prototype.render = function () {
  58011. if (!this._started) {
  58012. return 0;
  58013. }
  58014. this._recreateUpdateEffect();
  58015. this._recreateRenderEffect();
  58016. if (!this.isReady()) {
  58017. return 0;
  58018. }
  58019. if (this._currentRenderId === this._scene.getRenderId()) {
  58020. return 0;
  58021. }
  58022. this._currentRenderId = this._scene.getRenderId();
  58023. // Get everything ready to render
  58024. this._initialize();
  58025. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  58026. // Enable update effect
  58027. this._engine.enableEffect(this._updateEffect);
  58028. this._engine.setState(false);
  58029. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  58030. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  58031. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  58032. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  58033. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  58034. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  58035. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  58036. this._updateEffect.setDirectColor4("color1", this.color1);
  58037. this._updateEffect.setDirectColor4("color2", this.color2);
  58038. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  58039. this._updateEffect.setFloat2("angleRange", this.minAngularSpeed, this.maxAngularSpeed);
  58040. this._updateEffect.setVector3("gravity", this.gravity);
  58041. if (this.particleEmitterType) {
  58042. this.particleEmitterType.applyToShader(this._updateEffect);
  58043. }
  58044. var emitterWM;
  58045. if (this.emitter.position) {
  58046. var emitterMesh = this.emitter;
  58047. emitterWM = emitterMesh.getWorldMatrix();
  58048. }
  58049. else {
  58050. var emitterPosition = this.emitter;
  58051. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  58052. }
  58053. this._updateEffect.setMatrix("emitterWM", emitterWM);
  58054. // Bind source VAO
  58055. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  58056. // Update
  58057. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  58058. this._engine.setRasterizerState(false);
  58059. this._engine.beginTransformFeedback();
  58060. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  58061. this._engine.endTransformFeedback();
  58062. this._engine.setRasterizerState(true);
  58063. this._engine.bindTransformFeedbackBuffer(null);
  58064. // Enable render effect
  58065. this._engine.enableEffect(this._renderEffect);
  58066. var viewMatrix = this._scene.getViewMatrix();
  58067. this._renderEffect.setMatrix("view", viewMatrix);
  58068. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  58069. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  58070. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  58071. if (this._scene.clipPlane) {
  58072. var clipPlane = this._scene.clipPlane;
  58073. var invView = viewMatrix.clone();
  58074. invView.invert();
  58075. this._renderEffect.setMatrix("invView", invView);
  58076. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  58077. }
  58078. // Draw order
  58079. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  58080. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  58081. }
  58082. else {
  58083. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  58084. }
  58085. if (this.forceDepthWrite) {
  58086. this._engine.setDepthWrite(true);
  58087. }
  58088. // Bind source VAO
  58089. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  58090. // Render
  58091. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  58092. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58093. // Switch VAOs
  58094. this._targetIndex++;
  58095. if (this._targetIndex === 2) {
  58096. this._targetIndex = 0;
  58097. }
  58098. // Switch buffers
  58099. var tmpBuffer = this._sourceBuffer;
  58100. this._sourceBuffer = this._targetBuffer;
  58101. this._targetBuffer = tmpBuffer;
  58102. return this._currentActiveCount;
  58103. };
  58104. /**
  58105. * Rebuilds the particle system
  58106. */
  58107. GPUParticleSystem.prototype.rebuild = function () {
  58108. this._initialize(true);
  58109. };
  58110. GPUParticleSystem.prototype._releaseBuffers = function () {
  58111. if (this._buffer0) {
  58112. this._buffer0.dispose();
  58113. this._buffer0 = null;
  58114. }
  58115. if (this._buffer1) {
  58116. this._buffer1.dispose();
  58117. this._buffer1 = null;
  58118. }
  58119. if (this._spriteBuffer) {
  58120. this._spriteBuffer.dispose();
  58121. this._spriteBuffer = null;
  58122. }
  58123. };
  58124. GPUParticleSystem.prototype._releaseVAOs = function () {
  58125. if (!this._updateVAO) {
  58126. return;
  58127. }
  58128. for (var index = 0; index < this._updateVAO.length; index++) {
  58129. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  58130. }
  58131. this._updateVAO = [];
  58132. for (var index = 0; index < this._renderVAO.length; index++) {
  58133. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  58134. }
  58135. this._renderVAO = [];
  58136. };
  58137. /**
  58138. * Disposes the particle system and free the associated resources
  58139. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  58140. */
  58141. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  58142. if (disposeTexture === void 0) { disposeTexture = true; }
  58143. var index = this._scene.particleSystems.indexOf(this);
  58144. if (index > -1) {
  58145. this._scene.particleSystems.splice(index, 1);
  58146. }
  58147. this._releaseBuffers();
  58148. this._releaseVAOs();
  58149. if (this._randomTexture) {
  58150. this._randomTexture.dispose();
  58151. this._randomTexture = null;
  58152. }
  58153. if (disposeTexture && this.particleTexture) {
  58154. this.particleTexture.dispose();
  58155. this.particleTexture = null;
  58156. }
  58157. // Callback
  58158. this.onDisposeObservable.notifyObservers(this);
  58159. this.onDisposeObservable.clear();
  58160. };
  58161. /**
  58162. * Clones the particle system.
  58163. * @param name The name of the cloned object
  58164. * @param newEmitter The new emitter to use
  58165. * @returns the cloned particle system
  58166. */
  58167. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  58168. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  58169. BABYLON.Tools.DeepCopy(this, result);
  58170. if (newEmitter === undefined) {
  58171. newEmitter = this.emitter;
  58172. }
  58173. result.emitter = newEmitter;
  58174. if (this.particleTexture) {
  58175. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  58176. }
  58177. return result;
  58178. };
  58179. /**
  58180. * Serializes the particle system to a JSON object.
  58181. * @returns the JSON object
  58182. */
  58183. GPUParticleSystem.prototype.serialize = function () {
  58184. var serializationObject = {};
  58185. serializationObject.name = this.name;
  58186. serializationObject.id = this.id;
  58187. // Emitter
  58188. if (this.emitter.position) {
  58189. var emitterMesh = this.emitter;
  58190. serializationObject.emitterId = emitterMesh.id;
  58191. }
  58192. else {
  58193. var emitterPosition = this.emitter;
  58194. serializationObject.emitter = emitterPosition.asArray();
  58195. }
  58196. serializationObject.capacity = this.getCapacity();
  58197. if (this.particleTexture) {
  58198. serializationObject.textureName = this.particleTexture.name;
  58199. }
  58200. // Animations
  58201. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  58202. // Particle system
  58203. serializationObject.activeParticleCount = this.activeParticleCount;
  58204. serializationObject.randomTextureSize = this._randomTextureSize;
  58205. serializationObject.minSize = this.minSize;
  58206. serializationObject.maxSize = this.maxSize;
  58207. serializationObject.minEmitPower = this.minEmitPower;
  58208. serializationObject.maxEmitPower = this.maxEmitPower;
  58209. serializationObject.minLifeTime = this.minLifeTime;
  58210. serializationObject.maxLifeTime = this.maxLifeTime;
  58211. serializationObject.minAngularSpeed = this.minAngularSpeed;
  58212. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  58213. serializationObject.emitRate = this.emitRate;
  58214. serializationObject.gravity = this.gravity.asArray();
  58215. serializationObject.color1 = this.color1.asArray();
  58216. serializationObject.color2 = this.color2.asArray();
  58217. serializationObject.colorDead = this.colorDead.asArray();
  58218. serializationObject.updateSpeed = this.updateSpeed;
  58219. serializationObject.targetStopDuration = this.targetStopDuration;
  58220. serializationObject.blendMode = this.blendMode;
  58221. // Emitter
  58222. if (this.particleEmitterType) {
  58223. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  58224. }
  58225. return serializationObject;
  58226. };
  58227. /**
  58228. * Parses a JSON object to create a GPU particle system.
  58229. * @param parsedParticleSystem The JSON object to parse
  58230. * @param scene The scene to create the particle system in
  58231. * @param rootUrl The root url to use to load external dependencies like texture
  58232. * @returns the parsed GPU particle system
  58233. */
  58234. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  58235. var name = parsedParticleSystem.name;
  58236. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  58237. if (parsedParticleSystem.id) {
  58238. particleSystem.id = parsedParticleSystem.id;
  58239. }
  58240. // Texture
  58241. if (parsedParticleSystem.textureName) {
  58242. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  58243. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  58244. }
  58245. // Emitter
  58246. if (parsedParticleSystem.emitterId) {
  58247. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  58248. }
  58249. else {
  58250. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  58251. }
  58252. // Animations
  58253. if (parsedParticleSystem.animations) {
  58254. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  58255. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  58256. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58257. }
  58258. }
  58259. // Particle system
  58260. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  58261. particleSystem.minSize = parsedParticleSystem.minSize;
  58262. particleSystem.maxSize = parsedParticleSystem.maxSize;
  58263. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  58264. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  58265. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  58266. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  58267. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  58268. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  58269. particleSystem.emitRate = parsedParticleSystem.emitRate;
  58270. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  58271. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  58272. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  58273. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  58274. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  58275. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  58276. particleSystem.blendMode = parsedParticleSystem.blendMode;
  58277. // Emitter
  58278. if (parsedParticleSystem.particleEmitterType) {
  58279. var emitterType = void 0;
  58280. switch (parsedParticleSystem.particleEmitterType.type) {
  58281. case "SphereEmitter":
  58282. emitterType = new BABYLON.SphereParticleEmitter();
  58283. break;
  58284. case "SphereDirectedParticleEmitter":
  58285. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  58286. break;
  58287. case "ConeEmitter":
  58288. emitterType = new BABYLON.ConeParticleEmitter();
  58289. break;
  58290. case "BoxEmitter":
  58291. default:
  58292. emitterType = new BABYLON.BoxParticleEmitter();
  58293. break;
  58294. }
  58295. emitterType.parse(parsedParticleSystem.particleEmitterType);
  58296. particleSystem.particleEmitterType = emitterType;
  58297. }
  58298. return particleSystem;
  58299. };
  58300. return GPUParticleSystem;
  58301. }());
  58302. BABYLON.GPUParticleSystem = GPUParticleSystem;
  58303. })(BABYLON || (BABYLON = {}));
  58304. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  58305. var BABYLON;
  58306. (function (BABYLON) {
  58307. /**
  58308. * Represents one particle of a solid particle system.
  58309. */
  58310. var SolidParticle = /** @class */ (function () {
  58311. /**
  58312. * Creates a Solid Particle object.
  58313. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  58314. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  58315. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  58316. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  58317. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  58318. * @param shapeId (integer) is the model shape identifier in the SPS.
  58319. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  58320. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  58321. */
  58322. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  58323. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  58324. /**
  58325. * particle global index
  58326. */
  58327. this.idx = 0;
  58328. /**
  58329. * The color of the particle
  58330. */
  58331. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58332. /**
  58333. * The world space position of the particle.
  58334. */
  58335. this.position = BABYLON.Vector3.Zero();
  58336. /**
  58337. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  58338. */
  58339. this.rotation = BABYLON.Vector3.Zero();
  58340. /**
  58341. * The scaling of the particle.
  58342. */
  58343. this.scaling = BABYLON.Vector3.One();
  58344. /**
  58345. * The uvs of the particle.
  58346. */
  58347. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  58348. /**
  58349. * The current speed of the particle.
  58350. */
  58351. this.velocity = BABYLON.Vector3.Zero();
  58352. /**
  58353. * The pivot point in the particle local space.
  58354. */
  58355. this.pivot = BABYLON.Vector3.Zero();
  58356. /**
  58357. * Must the particle be translated from its pivot point in its local space ?
  58358. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  58359. * Default : false
  58360. */
  58361. this.translateFromPivot = false;
  58362. /**
  58363. * Is the particle active or not ?
  58364. */
  58365. this.alive = true;
  58366. /**
  58367. * Is the particle visible or not ?
  58368. */
  58369. this.isVisible = true;
  58370. /**
  58371. * Index of this particle in the global "positions" array (Internal use)
  58372. */
  58373. this._pos = 0;
  58374. /**
  58375. * Index of this particle in the global "indices" array (Internal use)
  58376. */
  58377. this._ind = 0;
  58378. /**
  58379. * ModelShape id of this particle
  58380. */
  58381. this.shapeId = 0;
  58382. /**
  58383. * Index of the particle in its shape id (Internal use)
  58384. */
  58385. this.idxInShape = 0;
  58386. /**
  58387. * Still set as invisible in order to skip useless computations (Internal use)
  58388. */
  58389. this._stillInvisible = false;
  58390. /**
  58391. * Last computed particle rotation matrix
  58392. */
  58393. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58394. /**
  58395. * Parent particle Id, if any.
  58396. * Default null.
  58397. */
  58398. this.parentId = null;
  58399. /**
  58400. * Internal global position in the SPS.
  58401. */
  58402. this._globalPosition = BABYLON.Vector3.Zero();
  58403. this.idx = particleIndex;
  58404. this._pos = positionIndex;
  58405. this._ind = indiceIndex;
  58406. this._model = model;
  58407. this.shapeId = shapeId;
  58408. this.idxInShape = idxInShape;
  58409. this._sps = sps;
  58410. if (modelBoundingInfo) {
  58411. this._modelBoundingInfo = modelBoundingInfo;
  58412. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58413. }
  58414. }
  58415. Object.defineProperty(SolidParticle.prototype, "scale", {
  58416. /**
  58417. * Legacy support, changed scale to scaling
  58418. */
  58419. get: function () {
  58420. return this.scaling;
  58421. },
  58422. /**
  58423. * Legacy support, changed scale to scaling
  58424. */
  58425. set: function (scale) {
  58426. this.scaling = scale;
  58427. },
  58428. enumerable: true,
  58429. configurable: true
  58430. });
  58431. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58432. /**
  58433. * Legacy support, changed quaternion to rotationQuaternion
  58434. */
  58435. get: function () {
  58436. return this.rotationQuaternion;
  58437. },
  58438. /**
  58439. * Legacy support, changed quaternion to rotationQuaternion
  58440. */
  58441. set: function (q) {
  58442. this.rotationQuaternion = q;
  58443. },
  58444. enumerable: true,
  58445. configurable: true
  58446. });
  58447. /**
  58448. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58449. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58450. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58451. * @returns true if it intersects
  58452. */
  58453. SolidParticle.prototype.intersectsMesh = function (target) {
  58454. if (!this._boundingInfo || !target._boundingInfo) {
  58455. return false;
  58456. }
  58457. if (this._sps._bSphereOnly) {
  58458. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58459. }
  58460. return this._boundingInfo.intersects(target._boundingInfo, false);
  58461. };
  58462. return SolidParticle;
  58463. }());
  58464. BABYLON.SolidParticle = SolidParticle;
  58465. /**
  58466. * Represents the shape of the model used by one particle of a solid particle system.
  58467. * SPS internal tool, don't use it manually.
  58468. */
  58469. var ModelShape = /** @class */ (function () {
  58470. /**
  58471. * Creates a ModelShape object. This is an internal simplified reference to a mesh used as for a model to replicate particles from by the SPS.
  58472. * SPS internal tool, don't use it manually.
  58473. * @hidden
  58474. */
  58475. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58476. /**
  58477. * length of the shape in the model indices array (internal use)
  58478. */
  58479. this._indicesLength = 0;
  58480. this.shapeID = id;
  58481. this._shape = shape;
  58482. this._indicesLength = indicesLength;
  58483. this._shapeUV = shapeUV;
  58484. this._positionFunction = posFunction;
  58485. this._vertexFunction = vtxFunction;
  58486. }
  58487. return ModelShape;
  58488. }());
  58489. BABYLON.ModelShape = ModelShape;
  58490. /**
  58491. * Represents a Depth Sorted Particle in the solid particle system.
  58492. */
  58493. var DepthSortedParticle = /** @class */ (function () {
  58494. function DepthSortedParticle() {
  58495. /**
  58496. * Index of the particle in the "indices" array
  58497. */
  58498. this.ind = 0;
  58499. /**
  58500. * Length of the particle shape in the "indices" array
  58501. */
  58502. this.indicesLength = 0;
  58503. /**
  58504. * Squared distance from the particle to the camera
  58505. */
  58506. this.sqDistance = 0.0;
  58507. }
  58508. return DepthSortedParticle;
  58509. }());
  58510. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58511. })(BABYLON || (BABYLON = {}));
  58512. //# sourceMappingURL=babylon.solidParticle.js.map
  58513. var BABYLON;
  58514. (function (BABYLON) {
  58515. /**
  58516. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58517. *As it is just a mesh, the SPS has all the same properties than any other BJS mesh : not more, not less. It can be scaled, rotated, translated, enlighted, textured, moved, etc.
  58518. * The SPS is also a particle system. It provides some methods to manage the particles.
  58519. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58520. *
  58521. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58522. */
  58523. var SolidParticleSystem = /** @class */ (function () {
  58524. /**
  58525. * Creates a SPS (Solid Particle System) object.
  58526. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58527. * @param scene (Scene) is the scene in which the SPS is added.
  58528. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58529. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58530. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58531. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58532. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58533. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58534. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58535. */
  58536. function SolidParticleSystem(name, scene, options) {
  58537. /**
  58538. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58539. * Example : var p = SPS.particles[i];
  58540. */
  58541. this.particles = new Array();
  58542. /**
  58543. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58544. */
  58545. this.nbParticles = 0;
  58546. /**
  58547. * If the particles must ever face the camera (default false). Useful for planar particles.
  58548. */
  58549. this.billboard = false;
  58550. /**
  58551. * Recompute normals when adding a shape
  58552. */
  58553. this.recomputeNormals = true;
  58554. /**
  58555. * This a counter ofr your own usage. It's not set by any SPS functions.
  58556. */
  58557. this.counter = 0;
  58558. /**
  58559. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58560. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58561. */
  58562. this.vars = {};
  58563. /**
  58564. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58565. */
  58566. this._bSphereOnly = false;
  58567. /**
  58568. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58569. */
  58570. this._bSphereRadiusFactor = 1.0;
  58571. this._positions = new Array();
  58572. this._indices = new Array();
  58573. this._normals = new Array();
  58574. this._colors = new Array();
  58575. this._uvs = new Array();
  58576. this._index = 0; // indices index
  58577. this._updatable = true;
  58578. this._pickable = false;
  58579. this._isVisibilityBoxLocked = false;
  58580. this._alwaysVisible = false;
  58581. this._depthSort = false;
  58582. this._shapeCounter = 0;
  58583. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58584. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58585. this._computeParticleColor = true;
  58586. this._computeParticleTexture = true;
  58587. this._computeParticleRotation = true;
  58588. this._computeParticleVertex = false;
  58589. this._computeBoundingBox = false;
  58590. this._depthSortParticles = true;
  58591. this._cam_axisZ = BABYLON.Vector3.Zero();
  58592. this._cam_axisY = BABYLON.Vector3.Zero();
  58593. this._cam_axisX = BABYLON.Vector3.Zero();
  58594. this._axisZ = BABYLON.Axis.Z;
  58595. this._camDir = BABYLON.Vector3.Zero();
  58596. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58597. this._rotMatrix = new BABYLON.Matrix();
  58598. this._invertMatrix = new BABYLON.Matrix();
  58599. this._rotated = BABYLON.Vector3.Zero();
  58600. this._quaternion = new BABYLON.Quaternion();
  58601. this._vertex = BABYLON.Vector3.Zero();
  58602. this._normal = BABYLON.Vector3.Zero();
  58603. this._yaw = 0.0;
  58604. this._pitch = 0.0;
  58605. this._roll = 0.0;
  58606. this._halfroll = 0.0;
  58607. this._halfpitch = 0.0;
  58608. this._halfyaw = 0.0;
  58609. this._sinRoll = 0.0;
  58610. this._cosRoll = 0.0;
  58611. this._sinPitch = 0.0;
  58612. this._cosPitch = 0.0;
  58613. this._sinYaw = 0.0;
  58614. this._cosYaw = 0.0;
  58615. this._mustUnrotateFixedNormals = false;
  58616. this._minimum = BABYLON.Vector3.Zero();
  58617. this._maximum = BABYLON.Vector3.Zero();
  58618. this._minBbox = BABYLON.Vector3.Zero();
  58619. this._maxBbox = BABYLON.Vector3.Zero();
  58620. this._particlesIntersect = false;
  58621. this._depthSortFunction = function (p1, p2) {
  58622. return (p2.sqDistance - p1.sqDistance);
  58623. };
  58624. this._needs32Bits = false;
  58625. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58626. this._scaledPivot = BABYLON.Vector3.Zero();
  58627. this._particleHasParent = false;
  58628. this.name = name;
  58629. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58630. this._camera = scene.activeCamera;
  58631. this._pickable = options ? options.isPickable : false;
  58632. this._depthSort = options ? options.enableDepthSort : false;
  58633. this._particlesIntersect = options ? options.particleIntersection : false;
  58634. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58635. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58636. if (options && options.updatable) {
  58637. this._updatable = options.updatable;
  58638. }
  58639. else {
  58640. this._updatable = true;
  58641. }
  58642. if (this._pickable) {
  58643. this.pickedParticles = [];
  58644. }
  58645. if (this._depthSort) {
  58646. this.depthSortedParticles = [];
  58647. }
  58648. }
  58649. /**
  58650. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58651. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58652. * @returns the created mesh
  58653. */
  58654. SolidParticleSystem.prototype.buildMesh = function () {
  58655. if (this.nbParticles === 0) {
  58656. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58657. this.addShape(triangle, 1);
  58658. triangle.dispose();
  58659. }
  58660. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58661. this._positions32 = new Float32Array(this._positions);
  58662. this._uvs32 = new Float32Array(this._uvs);
  58663. this._colors32 = new Float32Array(this._colors);
  58664. if (this.recomputeNormals) {
  58665. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58666. }
  58667. this._normals32 = new Float32Array(this._normals);
  58668. this._fixedNormal32 = new Float32Array(this._normals);
  58669. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58670. this._unrotateFixedNormals();
  58671. }
  58672. var vertexData = new BABYLON.VertexData();
  58673. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58674. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58675. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58676. if (this._uvs32.length > 0) {
  58677. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58678. }
  58679. if (this._colors32.length > 0) {
  58680. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58681. }
  58682. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58683. vertexData.applyToMesh(mesh, this._updatable);
  58684. this.mesh = mesh;
  58685. this.mesh.isPickable = this._pickable;
  58686. // free memory
  58687. if (!this._depthSort) {
  58688. this._indices = null;
  58689. }
  58690. this._positions = null;
  58691. this._normals = null;
  58692. this._uvs = null;
  58693. this._colors = null;
  58694. if (!this._updatable) {
  58695. this.particles.length = 0;
  58696. }
  58697. return mesh;
  58698. };
  58699. /**
  58700. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58701. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58702. * Thus the particles generated from `digest()` have their property `position` set yet.
  58703. * @param mesh ( Mesh ) is the mesh to be digested
  58704. * @param options {facetNb} (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  58705. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58706. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58707. * @returns the current SPS
  58708. */
  58709. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58710. var size = (options && options.facetNb) || 1;
  58711. var number = (options && options.number) || 0;
  58712. var delta = (options && options.delta) || 0;
  58713. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58714. var meshInd = mesh.getIndices();
  58715. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58716. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58717. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58718. var f = 0; // facet counter
  58719. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58720. // compute size from number
  58721. if (number) {
  58722. number = (number > totalFacets) ? totalFacets : number;
  58723. size = Math.round(totalFacets / number);
  58724. delta = 0;
  58725. }
  58726. else {
  58727. size = (size > totalFacets) ? totalFacets : size;
  58728. }
  58729. var facetPos = []; // submesh positions
  58730. var facetInd = []; // submesh indices
  58731. var facetUV = []; // submesh UV
  58732. var facetCol = []; // submesh colors
  58733. var barycenter = BABYLON.Vector3.Zero();
  58734. var sizeO = size;
  58735. while (f < totalFacets) {
  58736. size = sizeO + Math.floor((1 + delta) * Math.random());
  58737. if (f > totalFacets - size) {
  58738. size = totalFacets - f;
  58739. }
  58740. // reset temp arrays
  58741. facetPos.length = 0;
  58742. facetInd.length = 0;
  58743. facetUV.length = 0;
  58744. facetCol.length = 0;
  58745. // iterate over "size" facets
  58746. var fi = 0;
  58747. for (var j = f * 3; j < (f + size) * 3; j++) {
  58748. facetInd.push(fi);
  58749. var i = meshInd[j];
  58750. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58751. if (meshUV) {
  58752. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58753. }
  58754. if (meshCol) {
  58755. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58756. }
  58757. fi++;
  58758. }
  58759. // create a model shape for each single particle
  58760. var idx = this.nbParticles;
  58761. var shape = this._posToShape(facetPos);
  58762. var shapeUV = this._uvsToShapeUV(facetUV);
  58763. // compute the barycenter of the shape
  58764. var v;
  58765. for (v = 0; v < shape.length; v++) {
  58766. barycenter.addInPlace(shape[v]);
  58767. }
  58768. barycenter.scaleInPlace(1 / shape.length);
  58769. // shift the shape from its barycenter to the origin
  58770. for (v = 0; v < shape.length; v++) {
  58771. shape[v].subtractInPlace(barycenter);
  58772. }
  58773. var bInfo;
  58774. if (this._particlesIntersect) {
  58775. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58776. }
  58777. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58778. // add the particle in the SPS
  58779. var currentPos = this._positions.length;
  58780. var currentInd = this._indices.length;
  58781. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58782. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58783. // initialize the particle position
  58784. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58785. this._index += shape.length;
  58786. idx++;
  58787. this.nbParticles++;
  58788. this._shapeCounter++;
  58789. f += size;
  58790. }
  58791. return this;
  58792. };
  58793. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58794. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58795. var index = 0;
  58796. var idx = 0;
  58797. for (var p = 0; p < this.particles.length; p++) {
  58798. this._particle = this.particles[p];
  58799. this._shape = this._particle._model._shape;
  58800. if (this._particle.rotationQuaternion) {
  58801. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58802. }
  58803. else {
  58804. this._yaw = this._particle.rotation.y;
  58805. this._pitch = this._particle.rotation.x;
  58806. this._roll = this._particle.rotation.z;
  58807. this._quaternionRotationYPR();
  58808. }
  58809. this._quaternionToRotationMatrix();
  58810. this._rotMatrix.invertToRef(this._invertMatrix);
  58811. for (var pt = 0; pt < this._shape.length; pt++) {
  58812. idx = index + pt * 3;
  58813. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58814. this._fixedNormal32[idx] = this._normal.x;
  58815. this._fixedNormal32[idx + 1] = this._normal.y;
  58816. this._fixedNormal32[idx + 2] = this._normal.z;
  58817. }
  58818. index = idx + 3;
  58819. }
  58820. };
  58821. //reset copy
  58822. SolidParticleSystem.prototype._resetCopy = function () {
  58823. this._copy.position.x = 0;
  58824. this._copy.position.y = 0;
  58825. this._copy.position.z = 0;
  58826. this._copy.rotation.x = 0;
  58827. this._copy.rotation.y = 0;
  58828. this._copy.rotation.z = 0;
  58829. this._copy.rotationQuaternion = null;
  58830. this._copy.scaling.x = 1.0;
  58831. this._copy.scaling.y = 1.0;
  58832. this._copy.scaling.z = 1.0;
  58833. this._copy.uvs.x = 0;
  58834. this._copy.uvs.y = 0;
  58835. this._copy.uvs.z = 1.0;
  58836. this._copy.uvs.w = 1.0;
  58837. this._copy.color = null;
  58838. this._copy.translateFromPivot = false;
  58839. };
  58840. // _meshBuilder : inserts the shape model in the global SPS mesh
  58841. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58842. var i;
  58843. var u = 0;
  58844. var c = 0;
  58845. var n = 0;
  58846. this._resetCopy();
  58847. if (options && options.positionFunction) { // call to custom positionFunction
  58848. options.positionFunction(this._copy, idx, idxInShape);
  58849. this._mustUnrotateFixedNormals = true;
  58850. }
  58851. if (this._copy.rotationQuaternion) {
  58852. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58853. }
  58854. else {
  58855. this._yaw = this._copy.rotation.y;
  58856. this._pitch = this._copy.rotation.x;
  58857. this._roll = this._copy.rotation.z;
  58858. this._quaternionRotationYPR();
  58859. }
  58860. this._quaternionToRotationMatrix();
  58861. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58862. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58863. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58864. if (this._copy.translateFromPivot) {
  58865. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58866. }
  58867. else {
  58868. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58869. }
  58870. for (i = 0; i < shape.length; i++) {
  58871. this._vertex.x = shape[i].x;
  58872. this._vertex.y = shape[i].y;
  58873. this._vertex.z = shape[i].z;
  58874. if (options && options.vertexFunction) {
  58875. options.vertexFunction(this._copy, this._vertex, i);
  58876. }
  58877. this._vertex.x *= this._copy.scaling.x;
  58878. this._vertex.y *= this._copy.scaling.y;
  58879. this._vertex.z *= this._copy.scaling.z;
  58880. this._vertex.x -= this._scaledPivot.x;
  58881. this._vertex.y -= this._scaledPivot.y;
  58882. this._vertex.z -= this._scaledPivot.z;
  58883. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58884. this._rotated.addInPlace(this._pivotBackTranslation);
  58885. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58886. if (meshUV) {
  58887. uvs.push((this._copy.uvs.z - this._copy.uvs.x) * meshUV[u] + this._copy.uvs.x, (this._copy.uvs.w - this._copy.uvs.y) * meshUV[u + 1] + this._copy.uvs.y);
  58888. u += 2;
  58889. }
  58890. if (this._copy.color) {
  58891. this._color = this._copy.color;
  58892. }
  58893. else if (meshCol && meshCol[c] !== undefined) {
  58894. this._color.r = meshCol[c];
  58895. this._color.g = meshCol[c + 1];
  58896. this._color.b = meshCol[c + 2];
  58897. this._color.a = meshCol[c + 3];
  58898. }
  58899. else {
  58900. this._color.r = 1.0;
  58901. this._color.g = 1.0;
  58902. this._color.b = 1.0;
  58903. this._color.a = 1.0;
  58904. }
  58905. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58906. c += 4;
  58907. if (!this.recomputeNormals && meshNor) {
  58908. this._normal.x = meshNor[n];
  58909. this._normal.y = meshNor[n + 1];
  58910. this._normal.z = meshNor[n + 2];
  58911. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58912. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58913. n += 3;
  58914. }
  58915. }
  58916. for (i = 0; i < meshInd.length; i++) {
  58917. var current_ind = p + meshInd[i];
  58918. indices.push(current_ind);
  58919. if (current_ind > 65535) {
  58920. this._needs32Bits = true;
  58921. }
  58922. }
  58923. if (this._pickable) {
  58924. var nbfaces = meshInd.length / 3;
  58925. for (i = 0; i < nbfaces; i++) {
  58926. this.pickedParticles.push({ idx: idx, faceId: i });
  58927. }
  58928. }
  58929. if (this._depthSort) {
  58930. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58931. }
  58932. return this._copy;
  58933. };
  58934. // returns a shape array from positions array
  58935. SolidParticleSystem.prototype._posToShape = function (positions) {
  58936. var shape = [];
  58937. for (var i = 0; i < positions.length; i += 3) {
  58938. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58939. }
  58940. return shape;
  58941. };
  58942. // returns a shapeUV array from a Vector4 uvs
  58943. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58944. var shapeUV = [];
  58945. if (uvs) {
  58946. for (var i = 0; i < uvs.length; i++)
  58947. shapeUV.push(uvs[i]);
  58948. }
  58949. return shapeUV;
  58950. };
  58951. // adds a new particle object in the particles array
  58952. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58953. if (bInfo === void 0) { bInfo = null; }
  58954. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58955. this.particles.push(sp);
  58956. return sp;
  58957. };
  58958. /**
  58959. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58960. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58961. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58962. * @param nb (positive integer) the number of particles to be created from this model
  58963. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58964. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58965. * @returns the number of shapes in the system
  58966. */
  58967. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58968. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58969. var meshInd = mesh.getIndices();
  58970. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58971. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58972. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58973. var bbInfo;
  58974. if (this._particlesIntersect) {
  58975. bbInfo = mesh.getBoundingInfo();
  58976. }
  58977. var shape = this._posToShape(meshPos);
  58978. var shapeUV = this._uvsToShapeUV(meshUV);
  58979. var posfunc = options ? options.positionFunction : null;
  58980. var vtxfunc = options ? options.vertexFunction : null;
  58981. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58982. // particles
  58983. var sp;
  58984. var currentCopy;
  58985. var idx = this.nbParticles;
  58986. for (var i = 0; i < nb; i++) {
  58987. var currentPos = this._positions.length;
  58988. var currentInd = this._indices.length;
  58989. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58990. if (this._updatable) {
  58991. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58992. sp.position.copyFrom(currentCopy.position);
  58993. sp.rotation.copyFrom(currentCopy.rotation);
  58994. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58995. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58996. }
  58997. if (currentCopy.color && sp.color) {
  58998. sp.color.copyFrom(currentCopy.color);
  58999. }
  59000. sp.scaling.copyFrom(currentCopy.scaling);
  59001. sp.uvs.copyFrom(currentCopy.uvs);
  59002. }
  59003. this._index += shape.length;
  59004. idx++;
  59005. }
  59006. this.nbParticles += nb;
  59007. this._shapeCounter++;
  59008. return this._shapeCounter - 1;
  59009. };
  59010. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  59011. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  59012. this._resetCopy();
  59013. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  59014. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  59015. }
  59016. if (this._copy.rotationQuaternion) {
  59017. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  59018. }
  59019. else {
  59020. this._yaw = this._copy.rotation.y;
  59021. this._pitch = this._copy.rotation.x;
  59022. this._roll = this._copy.rotation.z;
  59023. this._quaternionRotationYPR();
  59024. }
  59025. this._quaternionToRotationMatrix();
  59026. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59027. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59028. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59029. if (this._copy.translateFromPivot) {
  59030. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  59031. }
  59032. else {
  59033. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  59034. }
  59035. this._shape = particle._model._shape;
  59036. for (var pt = 0; pt < this._shape.length; pt++) {
  59037. this._vertex.x = this._shape[pt].x;
  59038. this._vertex.y = this._shape[pt].y;
  59039. this._vertex.z = this._shape[pt].z;
  59040. if (particle._model._vertexFunction) {
  59041. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  59042. }
  59043. this._vertex.x *= this._copy.scaling.x;
  59044. this._vertex.y *= this._copy.scaling.y;
  59045. this._vertex.z *= this._copy.scaling.z;
  59046. this._vertex.x -= this._scaledPivot.x;
  59047. this._vertex.y -= this._scaledPivot.y;
  59048. this._vertex.z -= this._scaledPivot.z;
  59049. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  59050. this._rotated.addInPlace(this._pivotBackTranslation);
  59051. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  59052. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  59053. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  59054. }
  59055. particle.position.x = 0.0;
  59056. particle.position.y = 0.0;
  59057. particle.position.z = 0.0;
  59058. particle.rotation.x = 0.0;
  59059. particle.rotation.y = 0.0;
  59060. particle.rotation.z = 0.0;
  59061. particle.rotationQuaternion = null;
  59062. particle.scaling.x = 1.0;
  59063. particle.scaling.y = 1.0;
  59064. particle.scaling.z = 1.0;
  59065. particle.uvs.x = 0.0;
  59066. particle.uvs.y = 0.0;
  59067. particle.uvs.z = 1.0;
  59068. particle.uvs.w = 1.0;
  59069. particle.pivot.x = 0.0;
  59070. particle.pivot.y = 0.0;
  59071. particle.pivot.z = 0.0;
  59072. particle.translateFromPivot = false;
  59073. particle.parentId = null;
  59074. };
  59075. /**
  59076. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  59077. * @returns the SPS.
  59078. */
  59079. SolidParticleSystem.prototype.rebuildMesh = function () {
  59080. for (var p = 0; p < this.particles.length; p++) {
  59081. this._rebuildParticle(this.particles[p]);
  59082. }
  59083. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59084. return this;
  59085. };
  59086. /**
  59087. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  59088. * This method calls `updateParticle()` for each particle of the SPS.
  59089. * For an animated SPS, it is usually called within the render loop.
  59090. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  59091. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  59092. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  59093. * @returns the SPS.
  59094. */
  59095. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  59096. if (start === void 0) { start = 0; }
  59097. if (end === void 0) { end = this.nbParticles - 1; }
  59098. if (update === void 0) { update = true; }
  59099. if (!this._updatable) {
  59100. return this;
  59101. }
  59102. // custom beforeUpdate
  59103. this.beforeUpdateParticles(start, end, update);
  59104. this._cam_axisX.x = 1.0;
  59105. this._cam_axisX.y = 0.0;
  59106. this._cam_axisX.z = 0.0;
  59107. this._cam_axisY.x = 0.0;
  59108. this._cam_axisY.y = 1.0;
  59109. this._cam_axisY.z = 0.0;
  59110. this._cam_axisZ.x = 0.0;
  59111. this._cam_axisZ.y = 0.0;
  59112. this._cam_axisZ.z = 1.0;
  59113. // cases when the World Matrix is to be computed first
  59114. if (this.billboard || this._depthSort) {
  59115. this.mesh.computeWorldMatrix(true);
  59116. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  59117. }
  59118. // if the particles will always face the camera
  59119. if (this.billboard) {
  59120. // compute the camera position and un-rotate it by the current mesh rotation
  59121. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  59122. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  59123. this._cam_axisZ.normalize();
  59124. // same for camera up vector extracted from the cam view matrix
  59125. var view = this._camera.getViewMatrix(true);
  59126. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  59127. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  59128. this._cam_axisY.normalize();
  59129. this._cam_axisX.normalize();
  59130. }
  59131. // if depthSort, compute the camera global position in the mesh local system
  59132. if (this._depthSort) {
  59133. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  59134. }
  59135. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  59136. var idx = 0; // current position index in the global array positions32
  59137. var index = 0; // position start index in the global array positions32 of the current particle
  59138. var colidx = 0; // current color index in the global array colors32
  59139. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  59140. var uvidx = 0; // current uv index in the global array uvs32
  59141. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  59142. var pt = 0; // current index in the particle model shape
  59143. if (this.mesh.isFacetDataEnabled) {
  59144. this._computeBoundingBox = true;
  59145. }
  59146. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  59147. if (this._computeBoundingBox) {
  59148. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  59149. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  59150. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  59151. }
  59152. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  59153. if (this.mesh._boundingInfo) {
  59154. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  59155. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  59156. }
  59157. }
  59158. }
  59159. // particle loop
  59160. index = this.particles[start]._pos;
  59161. var vpos = (index / 3) | 0;
  59162. colorIndex = vpos * 4;
  59163. uvIndex = vpos * 2;
  59164. for (var p = start; p <= end; p++) {
  59165. this._particle = this.particles[p];
  59166. this._shape = this._particle._model._shape;
  59167. this._shapeUV = this._particle._model._shapeUV;
  59168. // call to custom user function to update the particle properties
  59169. this.updateParticle(this._particle);
  59170. // camera-particle distance for depth sorting
  59171. if (this._depthSort && this._depthSortParticles) {
  59172. var dsp = this.depthSortedParticles[p];
  59173. dsp.ind = this._particle._ind;
  59174. dsp.indicesLength = this._particle._model._indicesLength;
  59175. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  59176. }
  59177. // skip the computations for inactive or already invisible particles
  59178. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  59179. // increment indexes for the next particle
  59180. pt = this._shape.length;
  59181. index += pt * 3;
  59182. colorIndex += pt * 4;
  59183. uvIndex += pt * 2;
  59184. continue;
  59185. }
  59186. if (this._particle.isVisible) {
  59187. this._particle._stillInvisible = false; // un-mark permanent invisibility
  59188. this._particleHasParent = (this._particle.parentId !== null);
  59189. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59190. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59191. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59192. // particle rotation matrix
  59193. if (this.billboard) {
  59194. this._particle.rotation.x = 0.0;
  59195. this._particle.rotation.y = 0.0;
  59196. }
  59197. if (this._computeParticleRotation || this.billboard) {
  59198. if (this._particle.rotationQuaternion) {
  59199. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  59200. }
  59201. else {
  59202. this._yaw = this._particle.rotation.y;
  59203. this._pitch = this._particle.rotation.x;
  59204. this._roll = this._particle.rotation.z;
  59205. this._quaternionRotationYPR();
  59206. }
  59207. this._quaternionToRotationMatrix();
  59208. }
  59209. if (this._particleHasParent) {
  59210. this._parent = this.particles[this._particle.parentId];
  59211. this._rotated.x = this._particle.position.x * this._parent._rotationMatrix[0] + this._particle.position.y * this._parent._rotationMatrix[3] + this._particle.position.z * this._parent._rotationMatrix[6];
  59212. this._rotated.y = this._particle.position.x * this._parent._rotationMatrix[1] + this._particle.position.y * this._parent._rotationMatrix[4] + this._particle.position.z * this._parent._rotationMatrix[7];
  59213. this._rotated.z = this._particle.position.x * this._parent._rotationMatrix[2] + this._particle.position.y * this._parent._rotationMatrix[5] + this._particle.position.z * this._parent._rotationMatrix[8];
  59214. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  59215. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  59216. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  59217. if (this._computeParticleRotation || this.billboard) {
  59218. this._particle._rotationMatrix[0] = this._rotMatrix.m[0] * this._parent._rotationMatrix[0] + this._rotMatrix.m[1] * this._parent._rotationMatrix[3] + this._rotMatrix.m[2] * this._parent._rotationMatrix[6];
  59219. this._particle._rotationMatrix[1] = this._rotMatrix.m[0] * this._parent._rotationMatrix[1] + this._rotMatrix.m[1] * this._parent._rotationMatrix[4] + this._rotMatrix.m[2] * this._parent._rotationMatrix[7];
  59220. this._particle._rotationMatrix[2] = this._rotMatrix.m[0] * this._parent._rotationMatrix[2] + this._rotMatrix.m[1] * this._parent._rotationMatrix[5] + this._rotMatrix.m[2] * this._parent._rotationMatrix[8];
  59221. this._particle._rotationMatrix[3] = this._rotMatrix.m[4] * this._parent._rotationMatrix[0] + this._rotMatrix.m[5] * this._parent._rotationMatrix[3] + this._rotMatrix.m[6] * this._parent._rotationMatrix[6];
  59222. this._particle._rotationMatrix[4] = this._rotMatrix.m[4] * this._parent._rotationMatrix[1] + this._rotMatrix.m[5] * this._parent._rotationMatrix[4] + this._rotMatrix.m[6] * this._parent._rotationMatrix[7];
  59223. this._particle._rotationMatrix[5] = this._rotMatrix.m[4] * this._parent._rotationMatrix[2] + this._rotMatrix.m[5] * this._parent._rotationMatrix[5] + this._rotMatrix.m[6] * this._parent._rotationMatrix[8];
  59224. this._particle._rotationMatrix[6] = this._rotMatrix.m[8] * this._parent._rotationMatrix[0] + this._rotMatrix.m[9] * this._parent._rotationMatrix[3] + this._rotMatrix.m[10] * this._parent._rotationMatrix[6];
  59225. this._particle._rotationMatrix[7] = this._rotMatrix.m[8] * this._parent._rotationMatrix[1] + this._rotMatrix.m[9] * this._parent._rotationMatrix[4] + this._rotMatrix.m[10] * this._parent._rotationMatrix[7];
  59226. this._particle._rotationMatrix[8] = this._rotMatrix.m[8] * this._parent._rotationMatrix[2] + this._rotMatrix.m[9] * this._parent._rotationMatrix[5] + this._rotMatrix.m[10] * this._parent._rotationMatrix[8];
  59227. }
  59228. }
  59229. else {
  59230. this._particle._globalPosition.x = this._particle.position.x;
  59231. this._particle._globalPosition.y = this._particle.position.y;
  59232. this._particle._globalPosition.z = this._particle.position.z;
  59233. if (this._computeParticleRotation || this.billboard) {
  59234. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  59235. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  59236. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  59237. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  59238. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  59239. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  59240. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  59241. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  59242. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  59243. }
  59244. }
  59245. if (this._particle.translateFromPivot) {
  59246. this._pivotBackTranslation.x = 0.0;
  59247. this._pivotBackTranslation.y = 0.0;
  59248. this._pivotBackTranslation.z = 0.0;
  59249. }
  59250. else {
  59251. this._pivotBackTranslation.x = this._scaledPivot.x;
  59252. this._pivotBackTranslation.y = this._scaledPivot.y;
  59253. this._pivotBackTranslation.z = this._scaledPivot.z;
  59254. }
  59255. // particle vertex loop
  59256. for (pt = 0; pt < this._shape.length; pt++) {
  59257. idx = index + pt * 3;
  59258. colidx = colorIndex + pt * 4;
  59259. uvidx = uvIndex + pt * 2;
  59260. this._vertex.x = this._shape[pt].x;
  59261. this._vertex.y = this._shape[pt].y;
  59262. this._vertex.z = this._shape[pt].z;
  59263. if (this._computeParticleVertex) {
  59264. this.updateParticleVertex(this._particle, this._vertex, pt);
  59265. }
  59266. // positions
  59267. this._vertex.x *= this._particle.scaling.x;
  59268. this._vertex.y *= this._particle.scaling.y;
  59269. this._vertex.z *= this._particle.scaling.z;
  59270. this._vertex.x -= this._scaledPivot.x;
  59271. this._vertex.y -= this._scaledPivot.y;
  59272. this._vertex.z -= this._scaledPivot.z;
  59273. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59274. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59275. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59276. this._rotated.x += this._pivotBackTranslation.x;
  59277. this._rotated.y += this._pivotBackTranslation.y;
  59278. this._rotated.z += this._pivotBackTranslation.z;
  59279. this._positions32[idx] = this._particle._globalPosition.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59280. this._positions32[idx + 1] = this._particle._globalPosition.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  59281. this._positions32[idx + 2] = this._particle._globalPosition.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  59282. if (this._computeBoundingBox) {
  59283. if (this._positions32[idx] < this._minimum.x) {
  59284. this._minimum.x = this._positions32[idx];
  59285. }
  59286. if (this._positions32[idx] > this._maximum.x) {
  59287. this._maximum.x = this._positions32[idx];
  59288. }
  59289. if (this._positions32[idx + 1] < this._minimum.y) {
  59290. this._minimum.y = this._positions32[idx + 1];
  59291. }
  59292. if (this._positions32[idx + 1] > this._maximum.y) {
  59293. this._maximum.y = this._positions32[idx + 1];
  59294. }
  59295. if (this._positions32[idx + 2] < this._minimum.z) {
  59296. this._minimum.z = this._positions32[idx + 2];
  59297. }
  59298. if (this._positions32[idx + 2] > this._maximum.z) {
  59299. this._maximum.z = this._positions32[idx + 2];
  59300. }
  59301. }
  59302. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  59303. if (!this._computeParticleVertex) {
  59304. this._normal.x = this._fixedNormal32[idx];
  59305. this._normal.y = this._fixedNormal32[idx + 1];
  59306. this._normal.z = this._fixedNormal32[idx + 2];
  59307. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  59308. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  59309. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  59310. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59311. this._normals32[idx + 1] = this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  59312. this._normals32[idx + 2] = this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  59313. }
  59314. if (this._computeParticleColor && this._particle.color) {
  59315. this._colors32[colidx] = this._particle.color.r;
  59316. this._colors32[colidx + 1] = this._particle.color.g;
  59317. this._colors32[colidx + 2] = this._particle.color.b;
  59318. this._colors32[colidx + 3] = this._particle.color.a;
  59319. }
  59320. if (this._computeParticleTexture) {
  59321. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59322. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59323. }
  59324. }
  59325. }
  59326. // particle just set invisible : scaled to zero and positioned at the origin
  59327. else {
  59328. this._particle._stillInvisible = true; // mark the particle as invisible
  59329. for (pt = 0; pt < this._shape.length; pt++) {
  59330. idx = index + pt * 3;
  59331. colidx = colorIndex + pt * 4;
  59332. uvidx = uvIndex + pt * 2;
  59333. this._positions32[idx] = 0.0;
  59334. this._positions32[idx + 1] = 0.0;
  59335. this._positions32[idx + 2] = 0.0;
  59336. this._normals32[idx] = 0.0;
  59337. this._normals32[idx + 1] = 0.0;
  59338. this._normals32[idx + 2] = 0.0;
  59339. if (this._computeParticleColor && this._particle.color) {
  59340. this._colors32[colidx] = this._particle.color.r;
  59341. this._colors32[colidx + 1] = this._particle.color.g;
  59342. this._colors32[colidx + 2] = this._particle.color.b;
  59343. this._colors32[colidx + 3] = this._particle.color.a;
  59344. }
  59345. if (this._computeParticleTexture) {
  59346. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59347. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59348. }
  59349. }
  59350. }
  59351. // if the particle intersections must be computed : update the bbInfo
  59352. if (this._particlesIntersect) {
  59353. var bInfo = this._particle._boundingInfo;
  59354. var bBox = bInfo.boundingBox;
  59355. var bSphere = bInfo.boundingSphere;
  59356. if (!this._bSphereOnly) {
  59357. // place, scale and rotate the particle bbox within the SPS local system, then update it
  59358. for (var b = 0; b < bBox.vectors.length; b++) {
  59359. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  59360. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  59361. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  59362. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59363. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59364. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59365. bBox.vectors[b].x = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59366. bBox.vectors[b].y = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  59367. bBox.vectors[b].z = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  59368. }
  59369. bBox._update(this.mesh._worldMatrix);
  59370. }
  59371. // place and scale the particle bouding sphere in the SPS local system, then update it
  59372. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  59373. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  59374. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  59375. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  59376. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59377. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59378. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59379. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59380. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59381. bSphere.radius = this._bSphereRadiusFactor * 0.5 * Math.sqrt((this._maxBbox.x - this._minBbox.x) * (this._maxBbox.x - this._minBbox.x) + (this._maxBbox.y - this._minBbox.y) * (this._maxBbox.y - this._minBbox.y) + (this._maxBbox.z - this._minBbox.z) * (this._maxBbox.z - this._minBbox.z));
  59382. bSphere._update(this.mesh._worldMatrix);
  59383. }
  59384. // increment indexes for the next particle
  59385. index = idx + 3;
  59386. colorIndex = colidx + 4;
  59387. uvIndex = uvidx + 2;
  59388. }
  59389. // if the VBO must be updated
  59390. if (update) {
  59391. if (this._computeParticleColor) {
  59392. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59393. }
  59394. if (this._computeParticleTexture) {
  59395. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59396. }
  59397. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59398. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59399. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59400. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59401. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59402. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59403. for (var i = 0; i < this._normals32.length; i++) {
  59404. this._fixedNormal32[i] = this._normals32[i];
  59405. }
  59406. }
  59407. if (!this.mesh.areNormalsFrozen) {
  59408. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59409. }
  59410. }
  59411. if (this._depthSort && this._depthSortParticles) {
  59412. this.depthSortedParticles.sort(this._depthSortFunction);
  59413. var dspl = this.depthSortedParticles.length;
  59414. var sorted = 0;
  59415. var lind = 0;
  59416. var sind = 0;
  59417. var sid = 0;
  59418. for (sorted = 0; sorted < dspl; sorted++) {
  59419. lind = this.depthSortedParticles[sorted].indicesLength;
  59420. sind = this.depthSortedParticles[sorted].ind;
  59421. for (var i = 0; i < lind; i++) {
  59422. this._indices32[sid] = this._indices[sind + i];
  59423. sid++;
  59424. }
  59425. }
  59426. this.mesh.updateIndices(this._indices32);
  59427. }
  59428. }
  59429. if (this._computeBoundingBox) {
  59430. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59431. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59432. }
  59433. this.afterUpdateParticles(start, end, update);
  59434. return this;
  59435. };
  59436. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59437. this._halfroll = this._roll * 0.5;
  59438. this._halfpitch = this._pitch * 0.5;
  59439. this._halfyaw = this._yaw * 0.5;
  59440. this._sinRoll = Math.sin(this._halfroll);
  59441. this._cosRoll = Math.cos(this._halfroll);
  59442. this._sinPitch = Math.sin(this._halfpitch);
  59443. this._cosPitch = Math.cos(this._halfpitch);
  59444. this._sinYaw = Math.sin(this._halfyaw);
  59445. this._cosYaw = Math.cos(this._halfyaw);
  59446. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59447. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59448. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59449. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59450. };
  59451. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59452. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59453. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59454. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59455. this._rotMatrix.m[3] = 0;
  59456. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59457. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59458. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59459. this._rotMatrix.m[7] = 0;
  59460. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59461. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59462. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59463. this._rotMatrix.m[11] = 0;
  59464. this._rotMatrix.m[12] = 0;
  59465. this._rotMatrix.m[13] = 0;
  59466. this._rotMatrix.m[14] = 0;
  59467. this._rotMatrix.m[15] = 1.0;
  59468. };
  59469. /**
  59470. * Disposes the SPS.
  59471. */
  59472. SolidParticleSystem.prototype.dispose = function () {
  59473. this.mesh.dispose();
  59474. this.vars = null;
  59475. // drop references to internal big arrays for the GC
  59476. this._positions = null;
  59477. this._indices = null;
  59478. this._normals = null;
  59479. this._uvs = null;
  59480. this._colors = null;
  59481. this._indices32 = null;
  59482. this._positions32 = null;
  59483. this._normals32 = null;
  59484. this._fixedNormal32 = null;
  59485. this._uvs32 = null;
  59486. this._colors32 = null;
  59487. this.pickedParticles = null;
  59488. };
  59489. /**
  59490. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59491. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59492. * @returns the SPS.
  59493. */
  59494. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59495. if (!this._isVisibilityBoxLocked) {
  59496. this.mesh.refreshBoundingInfo();
  59497. }
  59498. return this;
  59499. };
  59500. /**
  59501. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59502. * @param size the size (float) of the visibility box
  59503. * note : this doesn't lock the SPS mesh bounding box.
  59504. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59505. */
  59506. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59507. var vis = size / 2;
  59508. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59509. };
  59510. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59511. /**
  59512. * Gets whether the SPS as always visible or not
  59513. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59514. */
  59515. get: function () {
  59516. return this._alwaysVisible;
  59517. },
  59518. /**
  59519. * Sets the SPS as always visible or not
  59520. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59521. */
  59522. set: function (val) {
  59523. this._alwaysVisible = val;
  59524. this.mesh.alwaysSelectAsActiveMesh = val;
  59525. },
  59526. enumerable: true,
  59527. configurable: true
  59528. });
  59529. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59530. /**
  59531. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59532. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59533. */
  59534. get: function () {
  59535. return this._isVisibilityBoxLocked;
  59536. },
  59537. /**
  59538. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59539. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59540. */
  59541. set: function (val) {
  59542. this._isVisibilityBoxLocked = val;
  59543. var boundingInfo = this.mesh.getBoundingInfo();
  59544. boundingInfo.isLocked = val;
  59545. },
  59546. enumerable: true,
  59547. configurable: true
  59548. });
  59549. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59550. /**
  59551. * Gets if `setParticles()` computes the particle rotations or not.
  59552. * Default value : true. The SPS is faster when it's set to false.
  59553. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59554. */
  59555. get: function () {
  59556. return this._computeParticleRotation;
  59557. },
  59558. /**
  59559. * Tells to `setParticles()` to compute the particle rotations or not.
  59560. * Default value : true. The SPS is faster when it's set to false.
  59561. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59562. */
  59563. set: function (val) {
  59564. this._computeParticleRotation = val;
  59565. },
  59566. enumerable: true,
  59567. configurable: true
  59568. });
  59569. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59570. /**
  59571. * Gets if `setParticles()` computes the particle colors or not.
  59572. * Default value : true. The SPS is faster when it's set to false.
  59573. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59574. */
  59575. get: function () {
  59576. return this._computeParticleColor;
  59577. },
  59578. /**
  59579. * Tells to `setParticles()` to compute the particle colors or not.
  59580. * Default value : true. The SPS is faster when it's set to false.
  59581. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59582. */
  59583. set: function (val) {
  59584. this._computeParticleColor = val;
  59585. },
  59586. enumerable: true,
  59587. configurable: true
  59588. });
  59589. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59590. /**
  59591. * Gets if `setParticles()` computes the particle textures or not.
  59592. * Default value : true. The SPS is faster when it's set to false.
  59593. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59594. */
  59595. get: function () {
  59596. return this._computeParticleTexture;
  59597. },
  59598. set: function (val) {
  59599. this._computeParticleTexture = val;
  59600. },
  59601. enumerable: true,
  59602. configurable: true
  59603. });
  59604. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59605. /**
  59606. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59607. * Default value : false. The SPS is faster when it's set to false.
  59608. * Note : the particle custom vertex positions aren't stored values.
  59609. */
  59610. get: function () {
  59611. return this._computeParticleVertex;
  59612. },
  59613. /**
  59614. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59615. * Default value : false. The SPS is faster when it's set to false.
  59616. * Note : the particle custom vertex positions aren't stored values.
  59617. */
  59618. set: function (val) {
  59619. this._computeParticleVertex = val;
  59620. },
  59621. enumerable: true,
  59622. configurable: true
  59623. });
  59624. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59625. /**
  59626. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59627. */
  59628. get: function () {
  59629. return this._computeBoundingBox;
  59630. },
  59631. /**
  59632. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59633. */
  59634. set: function (val) {
  59635. this._computeBoundingBox = val;
  59636. },
  59637. enumerable: true,
  59638. configurable: true
  59639. });
  59640. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59641. /**
  59642. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59643. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59644. * Default : `true`
  59645. */
  59646. get: function () {
  59647. return this._depthSortParticles;
  59648. },
  59649. /**
  59650. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59651. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59652. * Default : `true`
  59653. */
  59654. set: function (val) {
  59655. this._depthSortParticles = val;
  59656. },
  59657. enumerable: true,
  59658. configurable: true
  59659. });
  59660. // =======================================================================
  59661. // Particle behavior logic
  59662. // these following methods may be overwritten by the user to fit his needs
  59663. /**
  59664. * This function does nothing. It may be overwritten to set all the particle first values.
  59665. * The SPS doesn't call this function, you may have to call it by your own.
  59666. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59667. */
  59668. SolidParticleSystem.prototype.initParticles = function () {
  59669. };
  59670. /**
  59671. * This function does nothing. It may be overwritten to recycle a particle.
  59672. * The SPS doesn't call this function, you may have to call it by your own.
  59673. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59674. * @param particle The particle to recycle
  59675. * @returns the recycled particle
  59676. */
  59677. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59678. return particle;
  59679. };
  59680. /**
  59681. * Updates a particle : this function should be overwritten by the user.
  59682. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59683. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59684. * @example : just set a particle position or velocity and recycle conditions
  59685. * @param particle The particle to update
  59686. * @returns the updated particle
  59687. */
  59688. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59689. return particle;
  59690. };
  59691. /**
  59692. * Updates a vertex of a particle : it can be overwritten by the user.
  59693. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59694. * @param particle the current particle
  59695. * @param vertex the current index of the current particle
  59696. * @param pt the index of the current vertex in the particle shape
  59697. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59698. * @example : just set a vertex particle position
  59699. * @returns the updated vertex
  59700. */
  59701. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59702. return vertex;
  59703. };
  59704. /**
  59705. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59706. * This does nothing and may be overwritten by the user.
  59707. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59708. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59709. * @param update the boolean update value actually passed to setParticles()
  59710. */
  59711. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59712. };
  59713. /**
  59714. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59715. * This will be passed three parameters.
  59716. * This does nothing and may be overwritten by the user.
  59717. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59718. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59719. * @param update the boolean update value actually passed to setParticles()
  59720. */
  59721. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59722. };
  59723. return SolidParticleSystem;
  59724. }());
  59725. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59726. })(BABYLON || (BABYLON = {}));
  59727. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59728. var BABYLON;
  59729. (function (BABYLON) {
  59730. var ShaderMaterial = /** @class */ (function (_super) {
  59731. __extends(ShaderMaterial, _super);
  59732. function ShaderMaterial(name, scene, shaderPath, options) {
  59733. var _this = _super.call(this, name, scene) || this;
  59734. _this._textures = {};
  59735. _this._textureArrays = {};
  59736. _this._floats = {};
  59737. _this._ints = {};
  59738. _this._floatsArrays = {};
  59739. _this._colors3 = {};
  59740. _this._colors3Arrays = {};
  59741. _this._colors4 = {};
  59742. _this._vectors2 = {};
  59743. _this._vectors3 = {};
  59744. _this._vectors4 = {};
  59745. _this._matrices = {};
  59746. _this._matrices3x3 = {};
  59747. _this._matrices2x2 = {};
  59748. _this._vectors2Arrays = {};
  59749. _this._vectors3Arrays = {};
  59750. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59751. _this._shaderPath = shaderPath;
  59752. options.needAlphaBlending = options.needAlphaBlending || false;
  59753. options.needAlphaTesting = options.needAlphaTesting || false;
  59754. options.attributes = options.attributes || ["position", "normal", "uv"];
  59755. options.uniforms = options.uniforms || ["worldViewProjection"];
  59756. options.uniformBuffers = options.uniformBuffers || [];
  59757. options.samplers = options.samplers || [];
  59758. options.defines = options.defines || [];
  59759. _this._options = options;
  59760. return _this;
  59761. }
  59762. ShaderMaterial.prototype.getClassName = function () {
  59763. return "ShaderMaterial";
  59764. };
  59765. ShaderMaterial.prototype.needAlphaBlending = function () {
  59766. return this._options.needAlphaBlending;
  59767. };
  59768. ShaderMaterial.prototype.needAlphaTesting = function () {
  59769. return this._options.needAlphaTesting;
  59770. };
  59771. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59772. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59773. this._options.uniforms.push(uniformName);
  59774. }
  59775. };
  59776. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59777. if (this._options.samplers.indexOf(name) === -1) {
  59778. this._options.samplers.push(name);
  59779. }
  59780. this._textures[name] = texture;
  59781. return this;
  59782. };
  59783. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59784. if (this._options.samplers.indexOf(name) === -1) {
  59785. this._options.samplers.push(name);
  59786. }
  59787. this._checkUniform(name);
  59788. this._textureArrays[name] = textures;
  59789. return this;
  59790. };
  59791. ShaderMaterial.prototype.setFloat = function (name, value) {
  59792. this._checkUniform(name);
  59793. this._floats[name] = value;
  59794. return this;
  59795. };
  59796. ShaderMaterial.prototype.setInt = function (name, value) {
  59797. this._checkUniform(name);
  59798. this._ints[name] = value;
  59799. return this;
  59800. };
  59801. ShaderMaterial.prototype.setFloats = function (name, value) {
  59802. this._checkUniform(name);
  59803. this._floatsArrays[name] = value;
  59804. return this;
  59805. };
  59806. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59807. this._checkUniform(name);
  59808. this._colors3[name] = value;
  59809. return this;
  59810. };
  59811. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59812. this._checkUniform(name);
  59813. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59814. color.toArray(arr, arr.length);
  59815. return arr;
  59816. }, []);
  59817. return this;
  59818. };
  59819. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59820. this._checkUniform(name);
  59821. this._colors4[name] = value;
  59822. return this;
  59823. };
  59824. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59825. this._checkUniform(name);
  59826. this._vectors2[name] = value;
  59827. return this;
  59828. };
  59829. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59830. this._checkUniform(name);
  59831. this._vectors3[name] = value;
  59832. return this;
  59833. };
  59834. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59835. this._checkUniform(name);
  59836. this._vectors4[name] = value;
  59837. return this;
  59838. };
  59839. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59840. this._checkUniform(name);
  59841. this._matrices[name] = value;
  59842. return this;
  59843. };
  59844. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59845. this._checkUniform(name);
  59846. this._matrices3x3[name] = value;
  59847. return this;
  59848. };
  59849. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59850. this._checkUniform(name);
  59851. this._matrices2x2[name] = value;
  59852. return this;
  59853. };
  59854. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59855. this._checkUniform(name);
  59856. this._vectors2Arrays[name] = value;
  59857. return this;
  59858. };
  59859. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59860. this._checkUniform(name);
  59861. this._vectors3Arrays[name] = value;
  59862. return this;
  59863. };
  59864. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59865. if (!mesh) {
  59866. return true;
  59867. }
  59868. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59869. return false;
  59870. }
  59871. return false;
  59872. };
  59873. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59874. var scene = this.getScene();
  59875. var engine = scene.getEngine();
  59876. if (!this.checkReadyOnEveryCall) {
  59877. if (this._renderId === scene.getRenderId()) {
  59878. if (this._checkCache(scene, mesh, useInstances)) {
  59879. return true;
  59880. }
  59881. }
  59882. }
  59883. // Instances
  59884. var defines = [];
  59885. var attribs = [];
  59886. var fallbacks = new BABYLON.EffectFallbacks();
  59887. if (useInstances) {
  59888. defines.push("#define INSTANCES");
  59889. }
  59890. for (var index = 0; index < this._options.defines.length; index++) {
  59891. defines.push(this._options.defines[index]);
  59892. }
  59893. for (var index = 0; index < this._options.attributes.length; index++) {
  59894. attribs.push(this._options.attributes[index]);
  59895. }
  59896. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59897. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59898. defines.push("#define VERTEXCOLOR");
  59899. }
  59900. // Bones
  59901. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59902. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59903. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59904. if (mesh.numBoneInfluencers > 4) {
  59905. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59906. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59907. }
  59908. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59909. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59910. fallbacks.addCPUSkinningFallback(0, mesh);
  59911. if (this._options.uniforms.indexOf("mBones") === -1) {
  59912. this._options.uniforms.push("mBones");
  59913. }
  59914. }
  59915. else {
  59916. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59917. }
  59918. // Textures
  59919. for (var name in this._textures) {
  59920. if (!this._textures[name].isReady()) {
  59921. return false;
  59922. }
  59923. }
  59924. // Alpha test
  59925. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59926. defines.push("#define ALPHATEST");
  59927. }
  59928. var previousEffect = this._effect;
  59929. var join = defines.join("\n");
  59930. this._effect = engine.createEffect(this._shaderPath, {
  59931. attributes: attribs,
  59932. uniformsNames: this._options.uniforms,
  59933. uniformBuffersNames: this._options.uniformBuffers,
  59934. samplers: this._options.samplers,
  59935. defines: join,
  59936. fallbacks: fallbacks,
  59937. onCompiled: this.onCompiled,
  59938. onError: this.onError
  59939. }, engine);
  59940. if (!this._effect.isReady()) {
  59941. return false;
  59942. }
  59943. if (previousEffect !== this._effect) {
  59944. scene.resetCachedMaterial();
  59945. }
  59946. this._renderId = scene.getRenderId();
  59947. return true;
  59948. };
  59949. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59950. var scene = this.getScene();
  59951. if (!this._effect) {
  59952. return;
  59953. }
  59954. if (this._options.uniforms.indexOf("world") !== -1) {
  59955. this._effect.setMatrix("world", world);
  59956. }
  59957. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59958. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59959. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59960. }
  59961. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59962. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59963. }
  59964. };
  59965. ShaderMaterial.prototype.bind = function (world, mesh) {
  59966. // Std values
  59967. this.bindOnlyWorldMatrix(world);
  59968. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59969. if (this._options.uniforms.indexOf("view") !== -1) {
  59970. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59971. }
  59972. if (this._options.uniforms.indexOf("projection") !== -1) {
  59973. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59974. }
  59975. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59976. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59977. }
  59978. // Bones
  59979. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59980. var name;
  59981. // Texture
  59982. for (name in this._textures) {
  59983. this._effect.setTexture(name, this._textures[name]);
  59984. }
  59985. // Texture arrays
  59986. for (name in this._textureArrays) {
  59987. this._effect.setTextureArray(name, this._textureArrays[name]);
  59988. }
  59989. // Int
  59990. for (name in this._ints) {
  59991. this._effect.setInt(name, this._ints[name]);
  59992. }
  59993. // Float
  59994. for (name in this._floats) {
  59995. this._effect.setFloat(name, this._floats[name]);
  59996. }
  59997. // Floats
  59998. for (name in this._floatsArrays) {
  59999. this._effect.setArray(name, this._floatsArrays[name]);
  60000. }
  60001. // Color3
  60002. for (name in this._colors3) {
  60003. this._effect.setColor3(name, this._colors3[name]);
  60004. }
  60005. for (name in this._colors3Arrays) {
  60006. this._effect.setArray3(name, this._colors3Arrays[name]);
  60007. }
  60008. // Color4
  60009. for (name in this._colors4) {
  60010. var color = this._colors4[name];
  60011. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  60012. }
  60013. // Vector2
  60014. for (name in this._vectors2) {
  60015. this._effect.setVector2(name, this._vectors2[name]);
  60016. }
  60017. // Vector3
  60018. for (name in this._vectors3) {
  60019. this._effect.setVector3(name, this._vectors3[name]);
  60020. }
  60021. // Vector4
  60022. for (name in this._vectors4) {
  60023. this._effect.setVector4(name, this._vectors4[name]);
  60024. }
  60025. // Matrix
  60026. for (name in this._matrices) {
  60027. this._effect.setMatrix(name, this._matrices[name]);
  60028. }
  60029. // Matrix 3x3
  60030. for (name in this._matrices3x3) {
  60031. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  60032. }
  60033. // Matrix 2x2
  60034. for (name in this._matrices2x2) {
  60035. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  60036. }
  60037. // Vector2Array
  60038. for (name in this._vectors2Arrays) {
  60039. this._effect.setArray2(name, this._vectors2Arrays[name]);
  60040. }
  60041. // Vector3Array
  60042. for (name in this._vectors3Arrays) {
  60043. this._effect.setArray3(name, this._vectors3Arrays[name]);
  60044. }
  60045. }
  60046. this._afterBind(mesh);
  60047. };
  60048. ShaderMaterial.prototype.getActiveTextures = function () {
  60049. var activeTextures = _super.prototype.getActiveTextures.call(this);
  60050. for (var name in this._textures) {
  60051. activeTextures.push(this._textures[name]);
  60052. }
  60053. for (var name in this._textureArrays) {
  60054. var array = this._textureArrays[name];
  60055. for (var index = 0; index < array.length; index++) {
  60056. activeTextures.push(array[index]);
  60057. }
  60058. }
  60059. return activeTextures;
  60060. };
  60061. ShaderMaterial.prototype.hasTexture = function (texture) {
  60062. if (_super.prototype.hasTexture.call(this, texture)) {
  60063. return true;
  60064. }
  60065. for (var name in this._textures) {
  60066. if (this._textures[name] === texture) {
  60067. return true;
  60068. }
  60069. }
  60070. for (var name in this._textureArrays) {
  60071. var array = this._textureArrays[name];
  60072. for (var index = 0; index < array.length; index++) {
  60073. if (array[index] === texture) {
  60074. return true;
  60075. }
  60076. }
  60077. }
  60078. return false;
  60079. };
  60080. ShaderMaterial.prototype.clone = function (name) {
  60081. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  60082. return newShaderMaterial;
  60083. };
  60084. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  60085. if (forceDisposeTextures) {
  60086. var name;
  60087. for (name in this._textures) {
  60088. this._textures[name].dispose();
  60089. }
  60090. for (name in this._textureArrays) {
  60091. var array = this._textureArrays[name];
  60092. for (var index = 0; index < array.length; index++) {
  60093. array[index].dispose();
  60094. }
  60095. }
  60096. }
  60097. this._textures = {};
  60098. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  60099. };
  60100. ShaderMaterial.prototype.serialize = function () {
  60101. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60102. serializationObject.customType = "BABYLON.ShaderMaterial";
  60103. serializationObject.options = this._options;
  60104. serializationObject.shaderPath = this._shaderPath;
  60105. var name;
  60106. // Texture
  60107. serializationObject.textures = {};
  60108. for (name in this._textures) {
  60109. serializationObject.textures[name] = this._textures[name].serialize();
  60110. }
  60111. // Texture arrays
  60112. serializationObject.textureArrays = {};
  60113. for (name in this._textureArrays) {
  60114. serializationObject.textureArrays[name] = [];
  60115. var array = this._textureArrays[name];
  60116. for (var index = 0; index < array.length; index++) {
  60117. serializationObject.textureArrays[name].push(array[index].serialize());
  60118. }
  60119. }
  60120. // Float
  60121. serializationObject.floats = {};
  60122. for (name in this._floats) {
  60123. serializationObject.floats[name] = this._floats[name];
  60124. }
  60125. // Float s
  60126. serializationObject.FloatArrays = {};
  60127. for (name in this._floatsArrays) {
  60128. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  60129. }
  60130. // Color3
  60131. serializationObject.colors3 = {};
  60132. for (name in this._colors3) {
  60133. serializationObject.colors3[name] = this._colors3[name].asArray();
  60134. }
  60135. // Color3 array
  60136. serializationObject.colors3Arrays = {};
  60137. for (name in this._colors3Arrays) {
  60138. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  60139. }
  60140. // Color4
  60141. serializationObject.colors4 = {};
  60142. for (name in this._colors4) {
  60143. serializationObject.colors4[name] = this._colors4[name].asArray();
  60144. }
  60145. // Vector2
  60146. serializationObject.vectors2 = {};
  60147. for (name in this._vectors2) {
  60148. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  60149. }
  60150. // Vector3
  60151. serializationObject.vectors3 = {};
  60152. for (name in this._vectors3) {
  60153. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  60154. }
  60155. // Vector4
  60156. serializationObject.vectors4 = {};
  60157. for (name in this._vectors4) {
  60158. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  60159. }
  60160. // Matrix
  60161. serializationObject.matrices = {};
  60162. for (name in this._matrices) {
  60163. serializationObject.matrices[name] = this._matrices[name].asArray();
  60164. }
  60165. // Matrix 3x3
  60166. serializationObject.matrices3x3 = {};
  60167. for (name in this._matrices3x3) {
  60168. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  60169. }
  60170. // Matrix 2x2
  60171. serializationObject.matrices2x2 = {};
  60172. for (name in this._matrices2x2) {
  60173. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  60174. }
  60175. // Vector2Array
  60176. serializationObject.vectors2Arrays = {};
  60177. for (name in this._vectors2Arrays) {
  60178. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  60179. }
  60180. // Vector3Array
  60181. serializationObject.vectors3Arrays = {};
  60182. for (name in this._vectors3Arrays) {
  60183. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  60184. }
  60185. return serializationObject;
  60186. };
  60187. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  60188. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  60189. var name;
  60190. // Texture
  60191. for (name in source.textures) {
  60192. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  60193. }
  60194. // Texture arrays
  60195. for (name in source.textureArrays) {
  60196. var array = source.textureArrays[name];
  60197. var textureArray = new Array();
  60198. for (var index = 0; index < array.length; index++) {
  60199. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  60200. }
  60201. material.setTextureArray(name, textureArray);
  60202. }
  60203. // Float
  60204. for (name in source.floats) {
  60205. material.setFloat(name, source.floats[name]);
  60206. }
  60207. // Float s
  60208. for (name in source.floatsArrays) {
  60209. material.setFloats(name, source.floatsArrays[name]);
  60210. }
  60211. // Color3
  60212. for (name in source.colors3) {
  60213. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  60214. }
  60215. // Color3 arrays
  60216. for (name in source.colors3Arrays) {
  60217. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  60218. if (i % 3 === 0) {
  60219. arr.push([num]);
  60220. }
  60221. else {
  60222. arr[arr.length - 1].push(num);
  60223. }
  60224. return arr;
  60225. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  60226. material.setColor3Array(name, colors);
  60227. }
  60228. // Color4
  60229. for (name in source.colors4) {
  60230. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  60231. }
  60232. // Vector2
  60233. for (name in source.vectors2) {
  60234. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  60235. }
  60236. // Vector3
  60237. for (name in source.vectors3) {
  60238. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  60239. }
  60240. // Vector4
  60241. for (name in source.vectors4) {
  60242. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  60243. }
  60244. // Matrix
  60245. for (name in source.matrices) {
  60246. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  60247. }
  60248. // Matrix 3x3
  60249. for (name in source.matrices3x3) {
  60250. material.setMatrix3x3(name, source.matrices3x3[name]);
  60251. }
  60252. // Matrix 2x2
  60253. for (name in source.matrices2x2) {
  60254. material.setMatrix2x2(name, source.matrices2x2[name]);
  60255. }
  60256. // Vector2Array
  60257. for (name in source.vectors2Arrays) {
  60258. material.setArray2(name, source.vectors2Arrays[name]);
  60259. }
  60260. // Vector3Array
  60261. for (name in source.vectors3Arrays) {
  60262. material.setArray3(name, source.vectors3Arrays[name]);
  60263. }
  60264. return material;
  60265. };
  60266. return ShaderMaterial;
  60267. }(BABYLON.Material));
  60268. BABYLON.ShaderMaterial = ShaderMaterial;
  60269. })(BABYLON || (BABYLON = {}));
  60270. //# sourceMappingURL=babylon.shaderMaterial.js.map
  60271. var BABYLON;
  60272. (function (BABYLON) {
  60273. var GroundMesh = /** @class */ (function (_super) {
  60274. __extends(GroundMesh, _super);
  60275. function GroundMesh(name, scene) {
  60276. var _this = _super.call(this, name, scene) || this;
  60277. _this.generateOctree = false;
  60278. return _this;
  60279. }
  60280. GroundMesh.prototype.getClassName = function () {
  60281. return "GroundMesh";
  60282. };
  60283. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  60284. get: function () {
  60285. return Math.min(this._subdivisionsX, this._subdivisionsY);
  60286. },
  60287. enumerable: true,
  60288. configurable: true
  60289. });
  60290. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  60291. get: function () {
  60292. return this._subdivisionsX;
  60293. },
  60294. enumerable: true,
  60295. configurable: true
  60296. });
  60297. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  60298. get: function () {
  60299. return this._subdivisionsY;
  60300. },
  60301. enumerable: true,
  60302. configurable: true
  60303. });
  60304. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  60305. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  60306. this._subdivisionsX = chunksCount;
  60307. this._subdivisionsY = chunksCount;
  60308. this.subdivide(chunksCount);
  60309. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  60310. };
  60311. /**
  60312. * Returns a height (y) value in the Worl system :
  60313. * the ground altitude at the coordinates (x, z) expressed in the World system.
  60314. * Returns the ground y position if (x, z) are outside the ground surface.
  60315. */
  60316. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  60317. var world = this.getWorldMatrix();
  60318. var invMat = BABYLON.Tmp.Matrix[5];
  60319. world.invertToRef(invMat);
  60320. var tmpVect = BABYLON.Tmp.Vector3[8];
  60321. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  60322. x = tmpVect.x;
  60323. z = tmpVect.z;
  60324. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60325. return this.position.y;
  60326. }
  60327. if (!this._heightQuads || this._heightQuads.length == 0) {
  60328. this._initHeightQuads();
  60329. this._computeHeightQuads();
  60330. }
  60331. var facet = this._getFacetAt(x, z);
  60332. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  60333. // return y in the World system
  60334. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  60335. return tmpVect.y;
  60336. };
  60337. /**
  60338. * Returns a normalized vector (Vector3) orthogonal to the ground
  60339. * at the ground coordinates (x, z) expressed in the World system.
  60340. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  60341. */
  60342. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  60343. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  60344. this.getNormalAtCoordinatesToRef(x, z, normal);
  60345. return normal;
  60346. };
  60347. /**
  60348. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60349. * at the ground coordinates (x, z) expressed in the World system.
  60350. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60351. * Returns the GroundMesh.
  60352. */
  60353. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60354. var world = this.getWorldMatrix();
  60355. var tmpMat = BABYLON.Tmp.Matrix[5];
  60356. world.invertToRef(tmpMat);
  60357. var tmpVect = BABYLON.Tmp.Vector3[8];
  60358. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60359. x = tmpVect.x;
  60360. z = tmpVect.z;
  60361. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60362. return this;
  60363. }
  60364. if (!this._heightQuads || this._heightQuads.length == 0) {
  60365. this._initHeightQuads();
  60366. this._computeHeightQuads();
  60367. }
  60368. var facet = this._getFacetAt(x, z);
  60369. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60370. return this;
  60371. };
  60372. /**
  60373. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60374. * if the ground has been updated.
  60375. * This can be used in the render loop.
  60376. * Returns the GroundMesh.
  60377. */
  60378. GroundMesh.prototype.updateCoordinateHeights = function () {
  60379. if (!this._heightQuads || this._heightQuads.length == 0) {
  60380. this._initHeightQuads();
  60381. }
  60382. this._computeHeightQuads();
  60383. return this;
  60384. };
  60385. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60386. GroundMesh.prototype._getFacetAt = function (x, z) {
  60387. // retrieve col and row from x, z coordinates in the ground local system
  60388. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60389. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60390. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60391. var facet;
  60392. if (z < quad.slope.x * x + quad.slope.y) {
  60393. facet = quad.facet1;
  60394. }
  60395. else {
  60396. facet = quad.facet2;
  60397. }
  60398. return facet;
  60399. };
  60400. // Creates and populates the heightMap array with "facet" elements :
  60401. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60402. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60403. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60404. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60405. // Returns the GroundMesh.
  60406. GroundMesh.prototype._initHeightQuads = function () {
  60407. var subdivisionsX = this._subdivisionsX;
  60408. var subdivisionsY = this._subdivisionsY;
  60409. this._heightQuads = new Array();
  60410. for (var row = 0; row < subdivisionsY; row++) {
  60411. for (var col = 0; col < subdivisionsX; col++) {
  60412. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0), facet2: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0) };
  60413. this._heightQuads[row * subdivisionsX + col] = quad;
  60414. }
  60415. }
  60416. return this;
  60417. };
  60418. // Compute each quad element values and update the the heightMap array :
  60419. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60420. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60421. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60422. // Returns the GroundMesh.
  60423. GroundMesh.prototype._computeHeightQuads = function () {
  60424. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60425. if (!positions) {
  60426. return this;
  60427. }
  60428. var v1 = BABYLON.Tmp.Vector3[3];
  60429. var v2 = BABYLON.Tmp.Vector3[2];
  60430. var v3 = BABYLON.Tmp.Vector3[1];
  60431. var v4 = BABYLON.Tmp.Vector3[0];
  60432. var v1v2 = BABYLON.Tmp.Vector3[4];
  60433. var v1v3 = BABYLON.Tmp.Vector3[5];
  60434. var v1v4 = BABYLON.Tmp.Vector3[6];
  60435. var norm1 = BABYLON.Tmp.Vector3[7];
  60436. var norm2 = BABYLON.Tmp.Vector3[8];
  60437. var i = 0;
  60438. var j = 0;
  60439. var k = 0;
  60440. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60441. var h = 0;
  60442. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60443. var d2 = 0;
  60444. var subdivisionsX = this._subdivisionsX;
  60445. var subdivisionsY = this._subdivisionsY;
  60446. for (var row = 0; row < subdivisionsY; row++) {
  60447. for (var col = 0; col < subdivisionsX; col++) {
  60448. i = col * 3;
  60449. j = row * (subdivisionsX + 1) * 3;
  60450. k = (row + 1) * (subdivisionsX + 1) * 3;
  60451. v1.x = positions[j + i];
  60452. v1.y = positions[j + i + 1];
  60453. v1.z = positions[j + i + 2];
  60454. v2.x = positions[j + i + 3];
  60455. v2.y = positions[j + i + 4];
  60456. v2.z = positions[j + i + 5];
  60457. v3.x = positions[k + i];
  60458. v3.y = positions[k + i + 1];
  60459. v3.z = positions[k + i + 2];
  60460. v4.x = positions[k + i + 3];
  60461. v4.y = positions[k + i + 4];
  60462. v4.z = positions[k + i + 5];
  60463. // 2D slope V1V4
  60464. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60465. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60466. // facet equations :
  60467. // we compute each facet normal vector
  60468. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60469. // we compute the value d by applying the equation to v1 which belongs to the plane
  60470. // then we store the facet equation in a Vector4
  60471. v2.subtractToRef(v1, v1v2);
  60472. v3.subtractToRef(v1, v1v3);
  60473. v4.subtractToRef(v1, v1v4);
  60474. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60475. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60476. norm1.normalize();
  60477. norm2.normalize();
  60478. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60479. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60480. var quad = this._heightQuads[row * subdivisionsX + col];
  60481. quad.slope.copyFromFloats(cd, h);
  60482. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60483. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60484. }
  60485. }
  60486. return this;
  60487. };
  60488. GroundMesh.prototype.serialize = function (serializationObject) {
  60489. _super.prototype.serialize.call(this, serializationObject);
  60490. serializationObject.subdivisionsX = this._subdivisionsX;
  60491. serializationObject.subdivisionsY = this._subdivisionsY;
  60492. serializationObject.minX = this._minX;
  60493. serializationObject.maxX = this._maxX;
  60494. serializationObject.minZ = this._minZ;
  60495. serializationObject.maxZ = this._maxZ;
  60496. serializationObject.width = this._width;
  60497. serializationObject.height = this._height;
  60498. };
  60499. GroundMesh.Parse = function (parsedMesh, scene) {
  60500. var result = new GroundMesh(parsedMesh.name, scene);
  60501. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60502. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60503. result._minX = parsedMesh.minX;
  60504. result._maxX = parsedMesh.maxX;
  60505. result._minZ = parsedMesh.minZ;
  60506. result._maxZ = parsedMesh.maxZ;
  60507. result._width = parsedMesh.width;
  60508. result._height = parsedMesh.height;
  60509. return result;
  60510. };
  60511. return GroundMesh;
  60512. }(BABYLON.Mesh));
  60513. BABYLON.GroundMesh = GroundMesh;
  60514. })(BABYLON || (BABYLON = {}));
  60515. //# sourceMappingURL=babylon.groundMesh.js.map
  60516. var BABYLON;
  60517. (function (BABYLON) {
  60518. /**
  60519. * Creates an instance based on a source mesh.
  60520. */
  60521. var InstancedMesh = /** @class */ (function (_super) {
  60522. __extends(InstancedMesh, _super);
  60523. function InstancedMesh(name, source) {
  60524. var _this = _super.call(this, name, source.getScene()) || this;
  60525. source.instances.push(_this);
  60526. _this._sourceMesh = source;
  60527. _this.position.copyFrom(source.position);
  60528. _this.rotation.copyFrom(source.rotation);
  60529. _this.scaling.copyFrom(source.scaling);
  60530. if (source.rotationQuaternion) {
  60531. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60532. }
  60533. _this.infiniteDistance = source.infiniteDistance;
  60534. _this.setPivotMatrix(source.getPivotMatrix());
  60535. _this.refreshBoundingInfo();
  60536. _this._syncSubMeshes();
  60537. return _this;
  60538. }
  60539. /**
  60540. * Returns the string "InstancedMesh".
  60541. */
  60542. InstancedMesh.prototype.getClassName = function () {
  60543. return "InstancedMesh";
  60544. };
  60545. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60546. // Methods
  60547. get: function () {
  60548. return this._sourceMesh.receiveShadows;
  60549. },
  60550. enumerable: true,
  60551. configurable: true
  60552. });
  60553. Object.defineProperty(InstancedMesh.prototype, "material", {
  60554. get: function () {
  60555. return this._sourceMesh.material;
  60556. },
  60557. enumerable: true,
  60558. configurable: true
  60559. });
  60560. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60561. get: function () {
  60562. return this._sourceMesh.visibility;
  60563. },
  60564. enumerable: true,
  60565. configurable: true
  60566. });
  60567. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60568. get: function () {
  60569. return this._sourceMesh.skeleton;
  60570. },
  60571. enumerable: true,
  60572. configurable: true
  60573. });
  60574. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60575. get: function () {
  60576. return this._sourceMesh.renderingGroupId;
  60577. },
  60578. set: function (value) {
  60579. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60580. return;
  60581. }
  60582. //no-op with warning
  60583. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60584. },
  60585. enumerable: true,
  60586. configurable: true
  60587. });
  60588. /**
  60589. * Returns the total number of vertices (integer).
  60590. */
  60591. InstancedMesh.prototype.getTotalVertices = function () {
  60592. return this._sourceMesh.getTotalVertices();
  60593. };
  60594. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60595. get: function () {
  60596. return this._sourceMesh;
  60597. },
  60598. enumerable: true,
  60599. configurable: true
  60600. });
  60601. /**
  60602. * Is this node ready to be used/rendered
  60603. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60604. * @return {boolean} is it ready
  60605. */
  60606. InstancedMesh.prototype.isReady = function (completeCheck) {
  60607. if (completeCheck === void 0) { completeCheck = false; }
  60608. return this._sourceMesh.isReady(completeCheck, true);
  60609. };
  60610. /**
  60611. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60612. */
  60613. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60614. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60615. };
  60616. /**
  60617. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60618. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60619. * The `data` are either a numeric array either a Float32Array.
  60620. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60621. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  60622. * Note that a new underlying VertexBuffer object is created each call.
  60623. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60624. *
  60625. * Possible `kind` values :
  60626. * - BABYLON.VertexBuffer.PositionKind
  60627. * - BABYLON.VertexBuffer.UVKind
  60628. * - BABYLON.VertexBuffer.UV2Kind
  60629. * - BABYLON.VertexBuffer.UV3Kind
  60630. * - BABYLON.VertexBuffer.UV4Kind
  60631. * - BABYLON.VertexBuffer.UV5Kind
  60632. * - BABYLON.VertexBuffer.UV6Kind
  60633. * - BABYLON.VertexBuffer.ColorKind
  60634. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60635. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60636. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60637. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60638. *
  60639. * Returns the Mesh.
  60640. */
  60641. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60642. if (this.sourceMesh) {
  60643. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60644. }
  60645. return this.sourceMesh;
  60646. };
  60647. /**
  60648. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60649. * If the mesh has no geometry, it is simply returned as it is.
  60650. * The `data` are either a numeric array either a Float32Array.
  60651. * No new underlying VertexBuffer object is created.
  60652. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60653. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60654. *
  60655. * Possible `kind` values :
  60656. * - BABYLON.VertexBuffer.PositionKind
  60657. * - BABYLON.VertexBuffer.UVKind
  60658. * - BABYLON.VertexBuffer.UV2Kind
  60659. * - BABYLON.VertexBuffer.UV3Kind
  60660. * - BABYLON.VertexBuffer.UV4Kind
  60661. * - BABYLON.VertexBuffer.UV5Kind
  60662. * - BABYLON.VertexBuffer.UV6Kind
  60663. * - BABYLON.VertexBuffer.ColorKind
  60664. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60665. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60666. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60667. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60668. *
  60669. * Returns the Mesh.
  60670. */
  60671. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60672. if (this.sourceMesh) {
  60673. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60674. }
  60675. return this.sourceMesh;
  60676. };
  60677. /**
  60678. * Sets the mesh indices.
  60679. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60680. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60681. * This method creates a new index buffer each call.
  60682. * Returns the Mesh.
  60683. */
  60684. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60685. if (totalVertices === void 0) { totalVertices = null; }
  60686. if (this.sourceMesh) {
  60687. this.sourceMesh.setIndices(indices, totalVertices);
  60688. }
  60689. return this.sourceMesh;
  60690. };
  60691. /**
  60692. * Boolean : True if the mesh owns the requested kind of data.
  60693. */
  60694. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60695. return this._sourceMesh.isVerticesDataPresent(kind);
  60696. };
  60697. /**
  60698. * Returns an array of indices (IndicesArray).
  60699. */
  60700. InstancedMesh.prototype.getIndices = function () {
  60701. return this._sourceMesh.getIndices();
  60702. };
  60703. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60704. get: function () {
  60705. return this._sourceMesh._positions;
  60706. },
  60707. enumerable: true,
  60708. configurable: true
  60709. });
  60710. /**
  60711. * Sets a new updated BoundingInfo to the mesh.
  60712. * Returns the mesh.
  60713. */
  60714. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60715. var meshBB = this._sourceMesh.getBoundingInfo();
  60716. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60717. this._updateBoundingInfo();
  60718. return this;
  60719. };
  60720. InstancedMesh.prototype._preActivate = function () {
  60721. if (this._currentLOD) {
  60722. this._currentLOD._preActivate();
  60723. }
  60724. return this;
  60725. };
  60726. InstancedMesh.prototype._activate = function (renderId) {
  60727. if (this._currentLOD) {
  60728. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60729. }
  60730. return this;
  60731. };
  60732. /**
  60733. * Returns the current associated LOD AbstractMesh.
  60734. */
  60735. InstancedMesh.prototype.getLOD = function (camera) {
  60736. if (!camera) {
  60737. return this;
  60738. }
  60739. var boundingInfo = this.getBoundingInfo();
  60740. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60741. if (this._currentLOD === this.sourceMesh) {
  60742. return this;
  60743. }
  60744. return this._currentLOD;
  60745. };
  60746. InstancedMesh.prototype._syncSubMeshes = function () {
  60747. this.releaseSubMeshes();
  60748. if (this._sourceMesh.subMeshes) {
  60749. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60750. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60751. }
  60752. }
  60753. return this;
  60754. };
  60755. InstancedMesh.prototype._generatePointsArray = function () {
  60756. return this._sourceMesh._generatePointsArray();
  60757. };
  60758. /**
  60759. * Creates a new InstancedMesh from the current mesh.
  60760. * - name (string) : the cloned mesh name
  60761. * - newParent (optional Node) : the optional Node to parent the clone to.
  60762. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60763. *
  60764. * Returns the clone.
  60765. */
  60766. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60767. var result = this._sourceMesh.createInstance(name);
  60768. // Deep copy
  60769. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60770. // Bounding info
  60771. this.refreshBoundingInfo();
  60772. // Parent
  60773. if (newParent) {
  60774. result.parent = newParent;
  60775. }
  60776. if (!doNotCloneChildren) {
  60777. // Children
  60778. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60779. var mesh = this.getScene().meshes[index];
  60780. if (mesh.parent === this) {
  60781. mesh.clone(mesh.name, result);
  60782. }
  60783. }
  60784. }
  60785. result.computeWorldMatrix(true);
  60786. return result;
  60787. };
  60788. /**
  60789. * Disposes the InstancedMesh.
  60790. * Returns nothing.
  60791. */
  60792. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60793. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60794. // Remove from mesh
  60795. var index = this._sourceMesh.instances.indexOf(this);
  60796. this._sourceMesh.instances.splice(index, 1);
  60797. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60798. };
  60799. return InstancedMesh;
  60800. }(BABYLON.AbstractMesh));
  60801. BABYLON.InstancedMesh = InstancedMesh;
  60802. })(BABYLON || (BABYLON = {}));
  60803. //# sourceMappingURL=babylon.instancedMesh.js.map
  60804. var BABYLON;
  60805. (function (BABYLON) {
  60806. var LinesMesh = /** @class */ (function (_super) {
  60807. __extends(LinesMesh, _super);
  60808. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60809. if (scene === void 0) { scene = null; }
  60810. if (parent === void 0) { parent = null; }
  60811. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60812. _this.useVertexColor = useVertexColor;
  60813. _this.useVertexAlpha = useVertexAlpha;
  60814. _this.color = new BABYLON.Color3(1, 1, 1);
  60815. _this.alpha = 1;
  60816. if (source) {
  60817. _this.color = source.color.clone();
  60818. _this.alpha = source.alpha;
  60819. _this.useVertexColor = source.useVertexColor;
  60820. _this.useVertexAlpha = source.useVertexAlpha;
  60821. }
  60822. _this._intersectionThreshold = 0.1;
  60823. var defines = [];
  60824. var options = {
  60825. attributes: [BABYLON.VertexBuffer.PositionKind],
  60826. uniforms: ["world", "viewProjection"],
  60827. needAlphaBlending: true,
  60828. defines: defines
  60829. };
  60830. if (useVertexAlpha === false) {
  60831. options.needAlphaBlending = false;
  60832. }
  60833. if (!useVertexColor) {
  60834. options.uniforms.push("color");
  60835. }
  60836. else {
  60837. options.defines.push("#define VERTEXCOLOR");
  60838. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60839. }
  60840. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60841. return _this;
  60842. }
  60843. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60844. /**
  60845. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60846. * This margin is expressed in world space coordinates, so its value may vary.
  60847. * Default value is 0.1
  60848. * @returns the intersection Threshold value.
  60849. */
  60850. get: function () {
  60851. return this._intersectionThreshold;
  60852. },
  60853. /**
  60854. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60855. * This margin is expressed in world space coordinates, so its value may vary.
  60856. * @param value the new threshold to apply
  60857. */
  60858. set: function (value) {
  60859. if (this._intersectionThreshold === value) {
  60860. return;
  60861. }
  60862. this._intersectionThreshold = value;
  60863. if (this.geometry) {
  60864. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60865. }
  60866. },
  60867. enumerable: true,
  60868. configurable: true
  60869. });
  60870. /**
  60871. * Returns the string "LineMesh"
  60872. */
  60873. LinesMesh.prototype.getClassName = function () {
  60874. return "LinesMesh";
  60875. };
  60876. Object.defineProperty(LinesMesh.prototype, "material", {
  60877. get: function () {
  60878. return this._colorShader;
  60879. },
  60880. set: function (value) {
  60881. // Do nothing
  60882. },
  60883. enumerable: true,
  60884. configurable: true
  60885. });
  60886. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60887. get: function () {
  60888. return false;
  60889. },
  60890. enumerable: true,
  60891. configurable: true
  60892. });
  60893. LinesMesh.prototype.createInstance = function (name) {
  60894. throw new Error("LinesMeshes do not support createInstance.");
  60895. };
  60896. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60897. if (!this._geometry) {
  60898. return this;
  60899. }
  60900. // VBOs
  60901. this._geometry._bind(this._colorShader.getEffect());
  60902. // Color
  60903. if (!this.useVertexColor) {
  60904. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60905. }
  60906. return this;
  60907. };
  60908. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60909. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60910. return this;
  60911. }
  60912. var engine = this.getScene().getEngine();
  60913. // Draw order
  60914. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60915. return this;
  60916. };
  60917. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60918. this._colorShader.dispose();
  60919. _super.prototype.dispose.call(this, doNotRecurse);
  60920. };
  60921. /**
  60922. * Returns a new LineMesh object cloned from the current one.
  60923. */
  60924. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60925. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60926. };
  60927. return LinesMesh;
  60928. }(BABYLON.Mesh));
  60929. BABYLON.LinesMesh = LinesMesh;
  60930. })(BABYLON || (BABYLON = {}));
  60931. //# sourceMappingURL=babylon.linesMesh.js.map
  60932. var BABYLON;
  60933. (function (BABYLON) {
  60934. /**
  60935. * Class containing static functions to help procedurally build meshes
  60936. */
  60937. var MeshBuilder = /** @class */ (function () {
  60938. function MeshBuilder() {
  60939. }
  60940. MeshBuilder.updateSideOrientation = function (orientation) {
  60941. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60942. return BABYLON.Mesh.DOUBLESIDE;
  60943. }
  60944. if (orientation === undefined || orientation === null) {
  60945. return BABYLON.Mesh.FRONTSIDE;
  60946. }
  60947. return orientation;
  60948. };
  60949. /**
  60950. * Creates a box mesh
  60951. * * The parameter `size` sets the size (float) of each box side (default 1)
  60952. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60953. * * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of 6 Color3 elements) and `faceUV` (an array of 6 Vector4 elements)
  60954. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60955. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60956. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60957. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60958. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60959. * @param name defines the name of the mesh
  60960. * @param options defines the options used to create the mesh
  60961. * @param scene defines the hosting scene
  60962. * @returns the box mesh
  60963. */
  60964. MeshBuilder.CreateBox = function (name, options, scene) {
  60965. if (scene === void 0) { scene = null; }
  60966. var box = new BABYLON.Mesh(name, scene);
  60967. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60968. box._originalBuilderSideOrientation = options.sideOrientation;
  60969. var vertexData = BABYLON.VertexData.CreateBox(options);
  60970. vertexData.applyToMesh(box, options.updatable);
  60971. return box;
  60972. };
  60973. /**
  60974. * Creates a sphere mesh
  60975. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60976. * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`)
  60977. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60978. * * You can create an unclosed sphere with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference (latitude) : 2 x PI x ratio
  60979. * * You can create an unclosed sphere on its height with the parameter `slice` (positive float, default1), valued between 0 and 1, what is the height ratio (longitude)
  60980. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60981. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60982. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60983. * @param name defines the name of the mesh
  60984. * @param options defines the options used to create the mesh
  60985. * @param scene defines the hosting scene
  60986. * @returns the sphere mesh
  60987. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60988. */
  60989. MeshBuilder.CreateSphere = function (name, options, scene) {
  60990. var sphere = new BABYLON.Mesh(name, scene);
  60991. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60992. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60993. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60994. vertexData.applyToMesh(sphere, options.updatable);
  60995. return sphere;
  60996. };
  60997. /**
  60998. * Creates a plane polygonal mesh. By default, this is a disc
  60999. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  61000. * * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc
  61001. * * You can create an unclosed polygon with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference : 2 x PI x ratio
  61002. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61003. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61004. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61005. * @param name defines the name of the mesh
  61006. * @param options defines the options used to create the mesh
  61007. * @param scene defines the hosting scene
  61008. * @returns the plane polygonal mesh
  61009. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  61010. */
  61011. MeshBuilder.CreateDisc = function (name, options, scene) {
  61012. if (scene === void 0) { scene = null; }
  61013. var disc = new BABYLON.Mesh(name, scene);
  61014. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61015. disc._originalBuilderSideOrientation = options.sideOrientation;
  61016. var vertexData = BABYLON.VertexData.CreateDisc(options);
  61017. vertexData.applyToMesh(disc, options.updatable);
  61018. return disc;
  61019. };
  61020. /**
  61021. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  61022. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  61023. * * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`)
  61024. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  61025. * * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface
  61026. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61027. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61028. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61029. * @param name defines the name of the mesh
  61030. * @param options defines the options used to create the mesh
  61031. * @param scene defines the hosting scene
  61032. * @returns the icosahedron mesh
  61033. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  61034. */
  61035. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  61036. var sphere = new BABYLON.Mesh(name, scene);
  61037. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61038. sphere._originalBuilderSideOrientation = options.sideOrientation;
  61039. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  61040. vertexData.applyToMesh(sphere, options.updatable);
  61041. return sphere;
  61042. };
  61043. ;
  61044. /**
  61045. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61046. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  61047. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  61048. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  61049. * * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path
  61050. * * It's the offset to join the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11
  61051. * * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  61052. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61053. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61054. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61055. * * The parameter `uvs` is an optional flat array of `Vector2` to update/set each ribbon vertex with its own custom UV values instead of the computed ones
  61056. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  61057. * * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that if you set `closePath` to `true`, there's one extra vertex per path in the geometry
  61058. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  61059. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61060. * @param name defines the name of the mesh
  61061. * @param options defines the options used to create the mesh
  61062. * @param scene defines the hosting scene
  61063. * @returns the ribbon mesh
  61064. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  61065. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61066. */
  61067. MeshBuilder.CreateRibbon = function (name, options, scene) {
  61068. if (scene === void 0) { scene = null; }
  61069. var pathArray = options.pathArray;
  61070. var closeArray = options.closeArray;
  61071. var closePath = options.closePath;
  61072. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61073. var instance = options.instance;
  61074. var updatable = options.updatable;
  61075. if (instance) { // existing ribbon instance update
  61076. // positionFunction : ribbon case
  61077. // only pathArray and sideOrientation parameters are taken into account for positions update
  61078. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  61079. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  61080. var positionFunction = function (positions) {
  61081. var minlg = pathArray[0].length;
  61082. var i = 0;
  61083. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  61084. for (var si = 1; si <= ns; si++) {
  61085. for (var p = 0; p < pathArray.length; p++) {
  61086. var path = pathArray[p];
  61087. var l = path.length;
  61088. minlg = (minlg < l) ? minlg : l;
  61089. var j = 0;
  61090. while (j < minlg) {
  61091. positions[i] = path[j].x;
  61092. positions[i + 1] = path[j].y;
  61093. positions[i + 2] = path[j].z;
  61094. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  61095. BABYLON.Tmp.Vector3[0].x = path[j].x;
  61096. }
  61097. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  61098. BABYLON.Tmp.Vector3[1].x = path[j].x;
  61099. }
  61100. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  61101. BABYLON.Tmp.Vector3[0].y = path[j].y;
  61102. }
  61103. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  61104. BABYLON.Tmp.Vector3[1].y = path[j].y;
  61105. }
  61106. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  61107. BABYLON.Tmp.Vector3[0].z = path[j].z;
  61108. }
  61109. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  61110. BABYLON.Tmp.Vector3[1].z = path[j].z;
  61111. }
  61112. j++;
  61113. i += 3;
  61114. }
  61115. if (instance._closePath) {
  61116. positions[i] = path[0].x;
  61117. positions[i + 1] = path[0].y;
  61118. positions[i + 2] = path[0].z;
  61119. i += 3;
  61120. }
  61121. }
  61122. }
  61123. };
  61124. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61125. positionFunction(positions);
  61126. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  61127. instance._boundingInfo.update(instance._worldMatrix);
  61128. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61129. if (options.colors) {
  61130. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61131. for (var c = 0; c < options.colors.length; c++) {
  61132. colors[c * 4] = options.colors[c].r;
  61133. colors[c * 4 + 1] = options.colors[c].g;
  61134. colors[c * 4 + 2] = options.colors[c].b;
  61135. colors[c * 4 + 3] = options.colors[c].a;
  61136. }
  61137. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  61138. }
  61139. if (options.uvs) {
  61140. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61141. for (var i = 0; i < options.uvs.length; i++) {
  61142. uvs[i * 2] = options.uvs[i].x;
  61143. uvs[i * 2 + 1] = options.uvs[i].y;
  61144. }
  61145. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  61146. }
  61147. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  61148. var indices = instance.getIndices();
  61149. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61150. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  61151. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  61152. if (instance._closePath) {
  61153. var indexFirst = 0;
  61154. var indexLast = 0;
  61155. for (var p = 0; p < pathArray.length; p++) {
  61156. indexFirst = instance._idx[p] * 3;
  61157. if (p + 1 < pathArray.length) {
  61158. indexLast = (instance._idx[p + 1] - 1) * 3;
  61159. }
  61160. else {
  61161. indexLast = normals.length - 3;
  61162. }
  61163. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  61164. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  61165. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  61166. normals[indexLast] = normals[indexFirst];
  61167. normals[indexLast + 1] = normals[indexFirst + 1];
  61168. normals[indexLast + 2] = normals[indexFirst + 2];
  61169. }
  61170. }
  61171. if (!(instance.areNormalsFrozen)) {
  61172. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  61173. }
  61174. }
  61175. return instance;
  61176. }
  61177. else { // new ribbon creation
  61178. var ribbon = new BABYLON.Mesh(name, scene);
  61179. ribbon._originalBuilderSideOrientation = sideOrientation;
  61180. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  61181. if (closePath) {
  61182. ribbon._idx = vertexData._idx;
  61183. }
  61184. ribbon._closePath = closePath;
  61185. ribbon._closeArray = closeArray;
  61186. vertexData.applyToMesh(ribbon, updatable);
  61187. return ribbon;
  61188. }
  61189. };
  61190. /**
  61191. * Creates a cylinder or a cone mesh
  61192. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  61193. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  61194. * * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  61195. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  61196. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  61197. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  61198. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  61199. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  61200. * * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of n Color3 elements) and `faceUV` (an array of n Vector4 elements).
  61201. * * The value of n is the number of cylinder faces. If the cylinder has only 1 subdivisions, n equals : top face + cylinder surface + bottom face = 3
  61202. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  61203. * * Finally, if the cylinder has 5 independent subdivisions and is enclose, n equals : top face + 5 x (stripe surface + 2 closing faces) + bottom face = 2 + 5 * 3 = 17
  61204. * * Each array (color or UVs) is always ordered the same way : the first element is the bottom cap, the last element is the top cap. The other elements are each a ring surface.
  61205. * * If `enclose` is false, a ring surface is one element.
  61206. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  61207. * * Example how to set colors and textures on a sliced cylinder : http://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379
  61208. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61209. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61210. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61211. * @param name defines the name of the mesh
  61212. * @param options defines the options used to create the mesh
  61213. * @param scene defines the hosting scene
  61214. * @returns the cylinder mesh
  61215. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  61216. */
  61217. MeshBuilder.CreateCylinder = function (name, options, scene) {
  61218. var cylinder = new BABYLON.Mesh(name, scene);
  61219. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61220. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  61221. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  61222. vertexData.applyToMesh(cylinder, options.updatable);
  61223. return cylinder;
  61224. };
  61225. /**
  61226. * Creates a torus mesh
  61227. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  61228. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  61229. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  61230. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61231. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61232. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61233. * @param name defines the name of the mesh
  61234. * @param options defines the options used to create the mesh
  61235. * @param scene defines the hosting scene
  61236. * @returns the torus mesh
  61237. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  61238. */
  61239. MeshBuilder.CreateTorus = function (name, options, scene) {
  61240. var torus = new BABYLON.Mesh(name, scene);
  61241. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61242. torus._originalBuilderSideOrientation = options.sideOrientation;
  61243. var vertexData = BABYLON.VertexData.CreateTorus(options);
  61244. vertexData.applyToMesh(torus, options.updatable);
  61245. return torus;
  61246. };
  61247. /**
  61248. * Creates a torus knot mesh
  61249. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  61250. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  61251. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  61252. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  61253. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61254. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61255. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61256. * @param name defines the name of the mesh
  61257. * @param options defines the options used to create the mesh
  61258. * @param scene defines the hosting scene
  61259. * @returns the torus knot mesh
  61260. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  61261. */
  61262. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  61263. var torusKnot = new BABYLON.Mesh(name, scene);
  61264. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61265. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  61266. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  61267. vertexData.applyToMesh(torusKnot, options.updatable);
  61268. return torusKnot;
  61269. };
  61270. /**
  61271. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  61272. * * A line system mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of lines as an input parameter
  61273. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  61274. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  61275. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  61276. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  61277. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  61278. * * Updating a simple Line mesh, you just need to update every line in the `lines` array : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  61279. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  61280. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61281. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  61282. * @param name defines the name of the new line system
  61283. * @param options defines the options used to create the line system
  61284. * @param scene defines the hosting scene
  61285. * @returns a new line system mesh
  61286. */
  61287. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  61288. var instance = options.instance;
  61289. var lines = options.lines;
  61290. var colors = options.colors;
  61291. if (instance) { // lines update
  61292. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61293. var vertexColor;
  61294. var lineColors;
  61295. if (colors) {
  61296. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61297. }
  61298. var i = 0;
  61299. var c = 0;
  61300. for (var l = 0; l < lines.length; l++) {
  61301. var points = lines[l];
  61302. for (var p = 0; p < points.length; p++) {
  61303. positions[i] = points[p].x;
  61304. positions[i + 1] = points[p].y;
  61305. positions[i + 2] = points[p].z;
  61306. if (colors && vertexColor) {
  61307. lineColors = colors[l];
  61308. vertexColor[c] = lineColors[p].r;
  61309. vertexColor[c + 1] = lineColors[p].g;
  61310. vertexColor[c + 2] = lineColors[p].b;
  61311. vertexColor[c + 3] = lineColors[p].a;
  61312. c += 4;
  61313. }
  61314. i += 3;
  61315. }
  61316. }
  61317. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61318. if (colors && vertexColor) {
  61319. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  61320. }
  61321. return instance;
  61322. }
  61323. // line system creation
  61324. var useVertexColor = (colors) ? true : false;
  61325. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  61326. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  61327. vertexData.applyToMesh(lineSystem, options.updatable);
  61328. return lineSystem;
  61329. };
  61330. /**
  61331. * Creates a line mesh
  61332. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter
  61333. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61334. * * The parameter `points` is an array successive Vector3
  61335. * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  61336. * * The optional parameter `colors` is an array of successive Color4, one per line point
  61337. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  61338. * * When updating an instance, remember that only point positions can change, not the number of points
  61339. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61340. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  61341. * @param name defines the name of the new line system
  61342. * @param options defines the options used to create the line system
  61343. * @param scene defines the hosting scene
  61344. * @returns a new line mesh
  61345. */
  61346. MeshBuilder.CreateLines = function (name, options, scene) {
  61347. if (scene === void 0) { scene = null; }
  61348. var colors = (options.colors) ? [options.colors] : null;
  61349. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  61350. return lines;
  61351. };
  61352. /**
  61353. * Creates a dashed line mesh
  61354. * * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter
  61355. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61356. * * The parameter `points` is an array successive Vector3
  61357. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  61358. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  61359. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  61360. * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  61361. * * When updating an instance, remember that only point positions can change, not the number of points
  61362. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61363. * @param name defines the name of the mesh
  61364. * @param options defines the options used to create the mesh
  61365. * @param scene defines the hosting scene
  61366. * @returns the dashed line mesh
  61367. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  61368. */
  61369. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  61370. if (scene === void 0) { scene = null; }
  61371. var points = options.points;
  61372. var instance = options.instance;
  61373. var gapSize = options.gapSize || 1;
  61374. var dashSize = options.dashSize || 3;
  61375. if (instance) { // dashed lines update
  61376. var positionFunction = function (positions) {
  61377. var curvect = BABYLON.Vector3.Zero();
  61378. var nbSeg = positions.length / 6;
  61379. var lg = 0;
  61380. var nb = 0;
  61381. var shft = 0;
  61382. var dashshft = 0;
  61383. var curshft = 0;
  61384. var p = 0;
  61385. var i = 0;
  61386. var j = 0;
  61387. for (i = 0; i < points.length - 1; i++) {
  61388. points[i + 1].subtractToRef(points[i], curvect);
  61389. lg += curvect.length();
  61390. }
  61391. shft = lg / nbSeg;
  61392. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61393. for (i = 0; i < points.length - 1; i++) {
  61394. points[i + 1].subtractToRef(points[i], curvect);
  61395. nb = Math.floor(curvect.length() / shft);
  61396. curvect.normalize();
  61397. j = 0;
  61398. while (j < nb && p < positions.length) {
  61399. curshft = shft * j;
  61400. positions[p] = points[i].x + curshft * curvect.x;
  61401. positions[p + 1] = points[i].y + curshft * curvect.y;
  61402. positions[p + 2] = points[i].z + curshft * curvect.z;
  61403. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61404. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61405. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61406. p += 6;
  61407. j++;
  61408. }
  61409. }
  61410. while (p < positions.length) {
  61411. positions[p] = points[i].x;
  61412. positions[p + 1] = points[i].y;
  61413. positions[p + 2] = points[i].z;
  61414. p += 3;
  61415. }
  61416. };
  61417. instance.updateMeshPositions(positionFunction, false);
  61418. return instance;
  61419. }
  61420. // dashed lines creation
  61421. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61422. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61423. vertexData.applyToMesh(dashedLines, options.updatable);
  61424. dashedLines.dashSize = dashSize;
  61425. dashedLines.gapSize = gapSize;
  61426. return dashedLines;
  61427. };
  61428. /**
  61429. * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61430. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
  61431. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61432. * * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  61433. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61434. * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  61435. * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  61436. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61437. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61438. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61439. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61440. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61441. * @param name defines the name of the mesh
  61442. * @param options defines the options used to create the mesh
  61443. * @param scene defines the hosting scene
  61444. * @returns the extruded shape mesh
  61445. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61446. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61447. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61448. */
  61449. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61450. if (scene === void 0) { scene = null; }
  61451. var path = options.path;
  61452. var shape = options.shape;
  61453. var scale = options.scale || 1;
  61454. var rotation = options.rotation || 0;
  61455. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61456. var updatable = options.updatable;
  61457. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61458. var instance = options.instance || null;
  61459. var invertUV = options.invertUV || false;
  61460. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable ? true : false, sideOrientation, instance, invertUV, options.frontUVs || null, options.backUVs || null);
  61461. };
  61462. /**
  61463. * Creates an custom extruded shape mesh.
  61464. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61465. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
  61466. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61467. * * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path
  61468. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61469. * * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path
  61470. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61471. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61472. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61473. * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  61474. * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  61475. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61476. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61477. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61478. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61479. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61480. * @param name defines the name of the mesh
  61481. * @param options defines the options used to create the mesh
  61482. * @param scene defines the hosting scene
  61483. * @returns the custom extruded shape mesh
  61484. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61485. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61486. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61487. */
  61488. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61489. var path = options.path;
  61490. var shape = options.shape;
  61491. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61492. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61493. var ribbonCloseArray = options.ribbonCloseArray || false;
  61494. var ribbonClosePath = options.ribbonClosePath || false;
  61495. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61496. var updatable = options.updatable;
  61497. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61498. var instance = options.instance;
  61499. var invertUV = options.invertUV || false;
  61500. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable ? true : false, sideOrientation, instance || null, invertUV, options.frontUVs || null, options.backUVs || null);
  61501. };
  61502. /**
  61503. * Creates lathe mesh.
  61504. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61505. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
  61506. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61507. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61508. * * The parameter `arc` (positive float, default 1) is the ratio of the lathe. 0.5 builds for instance half a lathe, so an opened shape
  61509. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61510. * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  61511. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61512. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61513. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61514. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61515. * @param name defines the name of the mesh
  61516. * @param options defines the options used to create the mesh
  61517. * @param scene defines the hosting scene
  61518. * @returns the lathe mesh
  61519. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61520. */
  61521. MeshBuilder.CreateLathe = function (name, options, scene) {
  61522. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61523. var closed = (options.closed === undefined) ? true : options.closed;
  61524. var shape = options.shape;
  61525. var radius = options.radius || 1;
  61526. var tessellation = options.tessellation || 64;
  61527. var updatable = options.updatable;
  61528. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61529. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61530. var pi2 = Math.PI * 2;
  61531. var paths = new Array();
  61532. var invertUV = options.invertUV || false;
  61533. var i = 0;
  61534. var p = 0;
  61535. var step = pi2 / tessellation * arc;
  61536. var rotated;
  61537. var path = new Array();
  61538. for (i = 0; i <= tessellation; i++) {
  61539. var path = [];
  61540. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61541. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61542. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61543. }
  61544. for (p = 0; p < shape.length; p++) {
  61545. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61546. path.push(rotated);
  61547. }
  61548. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61549. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[shape.length - 1].x * radius, shape[shape.length - 1].y, Math.sin(i * step) * shape[shape.length - 1].x * radius));
  61550. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61551. }
  61552. paths.push(path);
  61553. }
  61554. // lathe ribbon
  61555. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61556. return lathe;
  61557. };
  61558. /**
  61559. * Creates a plane mesh
  61560. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61561. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61562. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61563. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61564. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61565. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61566. * @param name defines the name of the mesh
  61567. * @param options defines the options used to create the mesh
  61568. * @param scene defines the hosting scene
  61569. * @returns the plane mesh
  61570. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61571. */
  61572. MeshBuilder.CreatePlane = function (name, options, scene) {
  61573. var plane = new BABYLON.Mesh(name, scene);
  61574. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61575. plane._originalBuilderSideOrientation = options.sideOrientation;
  61576. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61577. vertexData.applyToMesh(plane, options.updatable);
  61578. if (options.sourcePlane) {
  61579. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61580. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61581. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61582. plane.rotate(vectorProduct, product);
  61583. }
  61584. return plane;
  61585. };
  61586. /**
  61587. * Creates a ground mesh
  61588. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61589. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61590. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61591. * @param name defines the name of the mesh
  61592. * @param options defines the options used to create the mesh
  61593. * @param scene defines the hosting scene
  61594. * @returns the ground mesh
  61595. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61596. */
  61597. MeshBuilder.CreateGround = function (name, options, scene) {
  61598. var ground = new BABYLON.GroundMesh(name, scene);
  61599. ground._setReady(false);
  61600. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61601. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61602. ground._width = options.width || 1;
  61603. ground._height = options.height || 1;
  61604. ground._maxX = ground._width / 2;
  61605. ground._maxZ = ground._height / 2;
  61606. ground._minX = -ground._maxX;
  61607. ground._minZ = -ground._maxZ;
  61608. var vertexData = BABYLON.VertexData.CreateGround(options);
  61609. vertexData.applyToMesh(ground, options.updatable);
  61610. ground._setReady(true);
  61611. return ground;
  61612. };
  61613. /**
  61614. * Creates a tiled ground mesh
  61615. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61616. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61617. * * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
  61618. * * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
  61619. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61620. * @param name defines the name of the mesh
  61621. * @param options defines the options used to create the mesh
  61622. * @param scene defines the hosting scene
  61623. * @returns the tiled ground mesh
  61624. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61625. */
  61626. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61627. var tiledGround = new BABYLON.Mesh(name, scene);
  61628. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61629. vertexData.applyToMesh(tiledGround, options.updatable);
  61630. return tiledGround;
  61631. };
  61632. /**
  61633. * Creates a ground mesh from a height map
  61634. * * The parameter `url` sets the URL of the height map image resource.
  61635. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61636. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61637. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61638. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61639. * * The parameter `colorFilter` (optional Color3, default (0.3, 0.59, 0.11) ) is the filter to apply to the image pixel colors to compute the height.
  61640. * * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  61641. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61642. * @param name defines the name of the mesh
  61643. * @param url defines the url to the height map
  61644. * @param options defines the options used to create the mesh
  61645. * @param scene defines the hosting scene
  61646. * @returns the ground mesh
  61647. * @see http://doc.babylonjs.com/babylon101/height_map
  61648. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61649. */
  61650. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61651. var width = options.width || 10.0;
  61652. var height = options.height || 10.0;
  61653. var subdivisions = options.subdivisions || 1 | 0;
  61654. var minHeight = options.minHeight || 0.0;
  61655. var maxHeight = options.maxHeight || 1.0;
  61656. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61657. var updatable = options.updatable;
  61658. var onReady = options.onReady;
  61659. var ground = new BABYLON.GroundMesh(name, scene);
  61660. ground._subdivisionsX = subdivisions;
  61661. ground._subdivisionsY = subdivisions;
  61662. ground._width = width;
  61663. ground._height = height;
  61664. ground._maxX = ground._width / 2.0;
  61665. ground._maxZ = ground._height / 2.0;
  61666. ground._minX = -ground._maxX;
  61667. ground._minZ = -ground._maxZ;
  61668. ground._setReady(false);
  61669. var onload = function (img) {
  61670. // Getting height map data
  61671. var canvas = document.createElement("canvas");
  61672. var context = canvas.getContext("2d");
  61673. if (!context) {
  61674. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61675. }
  61676. if (scene.isDisposed) {
  61677. return;
  61678. }
  61679. var bufferWidth = img.width;
  61680. var bufferHeight = img.height;
  61681. canvas.width = bufferWidth;
  61682. canvas.height = bufferHeight;
  61683. context.drawImage(img, 0, 0);
  61684. // Create VertexData from map data
  61685. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61686. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61687. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61688. width: width, height: height,
  61689. subdivisions: subdivisions,
  61690. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61691. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61692. });
  61693. vertexData.applyToMesh(ground, updatable);
  61694. //execute ready callback, if set
  61695. if (onReady) {
  61696. onReady(ground);
  61697. }
  61698. ground._setReady(true);
  61699. };
  61700. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61701. return ground;
  61702. };
  61703. /**
  61704. * Creates a polygon mesh
  61705. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61706. * * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors
  61707. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61708. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61709. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4)
  61710. * * Remember you can only change the shape positions, not their number when updating a polygon
  61711. * @param name defines the name of the mesh
  61712. * @param options defines the options used to create the mesh
  61713. * @param scene defines the hosting scene
  61714. * @returns the polygon mesh
  61715. */
  61716. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61717. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61718. var shape = options.shape;
  61719. var holes = options.holes || [];
  61720. var depth = options.depth || 0;
  61721. var contours = [];
  61722. var hole = [];
  61723. for (var i = 0; i < shape.length; i++) {
  61724. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61725. }
  61726. var epsilon = 0.00000001;
  61727. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61728. contours.pop();
  61729. }
  61730. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61731. for (var hNb = 0; hNb < holes.length; hNb++) {
  61732. hole = [];
  61733. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61734. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61735. }
  61736. polygonTriangulation.addHole(hole);
  61737. }
  61738. var polygon = polygonTriangulation.build(options.updatable, depth);
  61739. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61740. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61741. vertexData.applyToMesh(polygon, options.updatable);
  61742. return polygon;
  61743. };
  61744. ;
  61745. /**
  61746. * Creates an extruded polygon mesh, with depth in the Y direction.
  61747. * * You can set different colors and different images to the top, bottom and extruded side by using the parameters `faceColors` (an array of 3 Color3 elements) and `faceUV` (an array of 3 Vector4 elements)
  61748. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61749. * @param name defines the name of the mesh
  61750. * @param options defines the options used to create the mesh
  61751. * @param scene defines the hosting scene
  61752. * @returns the polygon mesh
  61753. */
  61754. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61755. return MeshBuilder.CreatePolygon(name, options, scene);
  61756. };
  61757. ;
  61758. /**
  61759. * Creates a tube mesh.
  61760. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61761. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61762. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61763. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61764. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61765. * * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path. It must return a radius value (positive float)
  61766. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61767. * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  61768. * * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  61769. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61770. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61771. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61772. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61773. * @param name defines the name of the mesh
  61774. * @param options defines the options used to create the mesh
  61775. * @param scene defines the hosting scene
  61776. * @returns the tube mesh
  61777. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61778. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61779. */
  61780. MeshBuilder.CreateTube = function (name, options, scene) {
  61781. var path = options.path;
  61782. var instance = options.instance;
  61783. var radius = 1.0;
  61784. if (instance) {
  61785. radius = instance.radius;
  61786. }
  61787. if (options.radius !== undefined) {
  61788. radius = options.radius;
  61789. }
  61790. ;
  61791. var tessellation = options.tessellation || 64 | 0;
  61792. var radiusFunction = options.radiusFunction || null;
  61793. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61794. var invertUV = options.invertUV || false;
  61795. var updatable = options.updatable;
  61796. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61797. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61798. // tube geometry
  61799. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61800. var tangents = path3D.getTangents();
  61801. var normals = path3D.getNormals();
  61802. var distances = path3D.getDistances();
  61803. var pi2 = Math.PI * 2;
  61804. var step = pi2 / tessellation * arc;
  61805. var returnRadius = function () { return radius; };
  61806. var radiusFunctionFinal = radiusFunction || returnRadius;
  61807. var circlePath;
  61808. var rad;
  61809. var normal;
  61810. var rotated;
  61811. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61812. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61813. for (var i = 0; i < path.length; i++) {
  61814. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61815. circlePath = Array(); // current circle array
  61816. normal = normals[i]; // current normal
  61817. for (var t = 0; t < tessellation; t++) {
  61818. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61819. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61820. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61821. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61822. circlePath[t] = rotated;
  61823. }
  61824. circlePaths[index] = circlePath;
  61825. index++;
  61826. }
  61827. // cap
  61828. var capPath = function (nbPoints, pathIndex) {
  61829. var pointCap = Array();
  61830. for (var i = 0; i < nbPoints; i++) {
  61831. pointCap.push(path[pathIndex]);
  61832. }
  61833. return pointCap;
  61834. };
  61835. switch (cap) {
  61836. case BABYLON.Mesh.NO_CAP:
  61837. break;
  61838. case BABYLON.Mesh.CAP_START:
  61839. circlePaths[0] = capPath(tessellation, 0);
  61840. circlePaths[1] = circlePaths[2].slice(0);
  61841. break;
  61842. case BABYLON.Mesh.CAP_END:
  61843. circlePaths[index] = circlePaths[index - 1].slice(0);
  61844. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61845. break;
  61846. case BABYLON.Mesh.CAP_ALL:
  61847. circlePaths[0] = capPath(tessellation, 0);
  61848. circlePaths[1] = circlePaths[2].slice(0);
  61849. circlePaths[index] = circlePaths[index - 1].slice(0);
  61850. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61851. break;
  61852. default:
  61853. break;
  61854. }
  61855. return circlePaths;
  61856. };
  61857. var path3D;
  61858. var pathArray;
  61859. if (instance) { // tube update
  61860. var arc = options.arc || instance.arc;
  61861. path3D = (instance.path3D).update(path);
  61862. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61863. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61864. instance.path3D = path3D;
  61865. instance.pathArray = pathArray;
  61866. instance.arc = arc;
  61867. instance.radius = radius;
  61868. return instance;
  61869. }
  61870. // tube creation
  61871. path3D = new BABYLON.Path3D(path);
  61872. var newPathArray = new Array();
  61873. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61874. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61875. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61876. tube.pathArray = pathArray;
  61877. tube.path3D = path3D;
  61878. tube.tessellation = tessellation;
  61879. tube.cap = cap;
  61880. tube.arc = options.arc;
  61881. tube.radius = radius;
  61882. return tube;
  61883. };
  61884. /**
  61885. * Creates a polyhedron mesh
  61886. * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial to choose the wanted type
  61887. * * The parameter `size` (positive float, default 1) sets the polygon size
  61888. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61889. * * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`
  61890. * * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  61891. * * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`)
  61892. * * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61893. * * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored
  61894. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61895. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61896. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61897. * @param name defines the name of the mesh
  61898. * @param options defines the options used to create the mesh
  61899. * @param scene defines the hosting scene
  61900. * @returns the polyhedron mesh
  61901. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61902. */
  61903. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61904. var polyhedron = new BABYLON.Mesh(name, scene);
  61905. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61906. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61907. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61908. vertexData.applyToMesh(polyhedron, options.updatable);
  61909. return polyhedron;
  61910. };
  61911. /**
  61912. * Creates a decal mesh.
  61913. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal
  61914. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61915. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61916. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61917. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61918. * @param name defines the name of the mesh
  61919. * @param sourceMesh defines the mesh where the decal must be applied
  61920. * @param options defines the options used to create the mesh
  61921. * @param scene defines the hosting scene
  61922. * @returns the decal mesh
  61923. * @see http://doc.babylonjs.com/how_to/decals
  61924. */
  61925. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61926. var indices = sourceMesh.getIndices();
  61927. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61928. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61929. var position = options.position || BABYLON.Vector3.Zero();
  61930. var normal = options.normal || BABYLON.Vector3.Up();
  61931. var size = options.size || BABYLON.Vector3.One();
  61932. var angle = options.angle || 0;
  61933. // Getting correct rotation
  61934. if (!normal) {
  61935. var target = new BABYLON.Vector3(0, 0, 1);
  61936. var camera = sourceMesh.getScene().activeCamera;
  61937. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61938. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61939. }
  61940. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61941. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61942. var pitch = Math.atan2(normal.y, len);
  61943. // Matrix
  61944. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61945. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61946. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61947. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61948. var vertexData = new BABYLON.VertexData();
  61949. vertexData.indices = [];
  61950. vertexData.positions = [];
  61951. vertexData.normals = [];
  61952. vertexData.uvs = [];
  61953. var currentVertexDataIndex = 0;
  61954. var extractDecalVector3 = function (indexId) {
  61955. var result = new BABYLON.PositionNormalVertex();
  61956. if (!indices || !positions || !normals) {
  61957. return result;
  61958. }
  61959. var vertexId = indices[indexId];
  61960. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61961. // Send vector to decal local world
  61962. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61963. // Get normal
  61964. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61965. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61966. return result;
  61967. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61968. var clip = function (vertices, axis) {
  61969. if (vertices.length === 0) {
  61970. return vertices;
  61971. }
  61972. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61973. var clipVertices = function (v0, v1) {
  61974. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61975. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61976. };
  61977. var result = new Array();
  61978. for (var index = 0; index < vertices.length; index += 3) {
  61979. var v1Out;
  61980. var v2Out;
  61981. var v3Out;
  61982. var total = 0;
  61983. var nV1 = null;
  61984. var nV2 = null;
  61985. var nV3 = null;
  61986. var nV4 = null;
  61987. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61988. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61989. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61990. v1Out = d1 > 0;
  61991. v2Out = d2 > 0;
  61992. v3Out = d3 > 0;
  61993. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61994. switch (total) {
  61995. case 0:
  61996. result.push(vertices[index]);
  61997. result.push(vertices[index + 1]);
  61998. result.push(vertices[index + 2]);
  61999. break;
  62000. case 1:
  62001. if (v1Out) {
  62002. nV1 = vertices[index + 1];
  62003. nV2 = vertices[index + 2];
  62004. nV3 = clipVertices(vertices[index], nV1);
  62005. nV4 = clipVertices(vertices[index], nV2);
  62006. }
  62007. if (v2Out) {
  62008. nV1 = vertices[index];
  62009. nV2 = vertices[index + 2];
  62010. nV3 = clipVertices(vertices[index + 1], nV1);
  62011. nV4 = clipVertices(vertices[index + 1], nV2);
  62012. result.push(nV3);
  62013. result.push(nV2.clone());
  62014. result.push(nV1.clone());
  62015. result.push(nV2.clone());
  62016. result.push(nV3.clone());
  62017. result.push(nV4);
  62018. break;
  62019. }
  62020. if (v3Out) {
  62021. nV1 = vertices[index];
  62022. nV2 = vertices[index + 1];
  62023. nV3 = clipVertices(vertices[index + 2], nV1);
  62024. nV4 = clipVertices(vertices[index + 2], nV2);
  62025. }
  62026. if (nV1 && nV2 && nV3 && nV4) {
  62027. result.push(nV1.clone());
  62028. result.push(nV2.clone());
  62029. result.push(nV3);
  62030. result.push(nV4);
  62031. result.push(nV3.clone());
  62032. result.push(nV2.clone());
  62033. }
  62034. break;
  62035. case 2:
  62036. if (!v1Out) {
  62037. nV1 = vertices[index].clone();
  62038. nV2 = clipVertices(nV1, vertices[index + 1]);
  62039. nV3 = clipVertices(nV1, vertices[index + 2]);
  62040. result.push(nV1);
  62041. result.push(nV2);
  62042. result.push(nV3);
  62043. }
  62044. if (!v2Out) {
  62045. nV1 = vertices[index + 1].clone();
  62046. nV2 = clipVertices(nV1, vertices[index + 2]);
  62047. nV3 = clipVertices(nV1, vertices[index]);
  62048. result.push(nV1);
  62049. result.push(nV2);
  62050. result.push(nV3);
  62051. }
  62052. if (!v3Out) {
  62053. nV1 = vertices[index + 2].clone();
  62054. nV2 = clipVertices(nV1, vertices[index]);
  62055. nV3 = clipVertices(nV1, vertices[index + 1]);
  62056. result.push(nV1);
  62057. result.push(nV2);
  62058. result.push(nV3);
  62059. }
  62060. break;
  62061. case 3:
  62062. break;
  62063. }
  62064. }
  62065. return result;
  62066. };
  62067. for (var index = 0; index < indices.length; index += 3) {
  62068. var faceVertices = new Array();
  62069. faceVertices.push(extractDecalVector3(index));
  62070. faceVertices.push(extractDecalVector3(index + 1));
  62071. faceVertices.push(extractDecalVector3(index + 2));
  62072. // Clip
  62073. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  62074. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  62075. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  62076. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  62077. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  62078. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  62079. if (faceVertices.length === 0) {
  62080. continue;
  62081. }
  62082. // Add UVs and get back to world
  62083. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  62084. var vertex = faceVertices[vIndex];
  62085. //TODO check for Int32Array | Uint32Array | Uint16Array
  62086. vertexData.indices.push(currentVertexDataIndex);
  62087. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  62088. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  62089. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  62090. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  62091. currentVertexDataIndex++;
  62092. }
  62093. }
  62094. // Return mesh
  62095. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  62096. vertexData.applyToMesh(decal);
  62097. decal.position = position.clone();
  62098. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  62099. return decal;
  62100. };
  62101. // Privates
  62102. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  62103. // extrusion geometry
  62104. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  62105. var tangents = path3D.getTangents();
  62106. var normals = path3D.getNormals();
  62107. var binormals = path3D.getBinormals();
  62108. var distances = path3D.getDistances();
  62109. var angle = 0;
  62110. var returnScale = function () { return scale !== null ? scale : 1; };
  62111. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  62112. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  62113. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  62114. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  62115. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  62116. for (var i = 0; i < curve.length; i++) {
  62117. var shapePath = new Array();
  62118. var angleStep = rotate(i, distances[i]);
  62119. var scaleRatio = scl(i, distances[i]);
  62120. for (var p = 0; p < shape.length; p++) {
  62121. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  62122. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  62123. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  62124. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  62125. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  62126. shapePath[p] = rotated;
  62127. }
  62128. shapePaths[index] = shapePath;
  62129. angle += angleStep;
  62130. index++;
  62131. }
  62132. // cap
  62133. var capPath = function (shapePath) {
  62134. var pointCap = Array();
  62135. var barycenter = BABYLON.Vector3.Zero();
  62136. var i;
  62137. for (i = 0; i < shapePath.length; i++) {
  62138. barycenter.addInPlace(shapePath[i]);
  62139. }
  62140. barycenter.scaleInPlace(1.0 / shapePath.length);
  62141. for (i = 0; i < shapePath.length; i++) {
  62142. pointCap.push(barycenter);
  62143. }
  62144. return pointCap;
  62145. };
  62146. switch (cap) {
  62147. case BABYLON.Mesh.NO_CAP:
  62148. break;
  62149. case BABYLON.Mesh.CAP_START:
  62150. shapePaths[0] = capPath(shapePaths[2]);
  62151. shapePaths[1] = shapePaths[2];
  62152. break;
  62153. case BABYLON.Mesh.CAP_END:
  62154. shapePaths[index] = shapePaths[index - 1];
  62155. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62156. break;
  62157. case BABYLON.Mesh.CAP_ALL:
  62158. shapePaths[0] = capPath(shapePaths[2]);
  62159. shapePaths[1] = shapePaths[2];
  62160. shapePaths[index] = shapePaths[index - 1];
  62161. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62162. break;
  62163. default:
  62164. break;
  62165. }
  62166. return shapePaths;
  62167. };
  62168. var path3D;
  62169. var pathArray;
  62170. if (instance) { // instance update
  62171. path3D = (instance.path3D).update(curve);
  62172. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  62173. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  62174. return instance;
  62175. }
  62176. // extruded shape creation
  62177. path3D = new BABYLON.Path3D(curve);
  62178. var newShapePaths = new Array();
  62179. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62180. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  62181. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  62182. extrudedGeneric.pathArray = pathArray;
  62183. extrudedGeneric.path3D = path3D;
  62184. extrudedGeneric.cap = cap;
  62185. return extrudedGeneric;
  62186. };
  62187. return MeshBuilder;
  62188. }());
  62189. BABYLON.MeshBuilder = MeshBuilder;
  62190. })(BABYLON || (BABYLON = {}));
  62191. //# sourceMappingURL=babylon.meshBuilder.js.map
  62192. var BABYLON;
  62193. (function (BABYLON) {
  62194. /**
  62195. * Draco compression (https://google.github.io/draco/)
  62196. *
  62197. * This class wraps the Draco module.
  62198. *
  62199. * **Encoder**
  62200. *
  62201. * The encoder is not currently implemented.
  62202. *
  62203. * **Decoder**
  62204. *
  62205. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  62206. *
  62207. * To update the configuration, use the following code:
  62208. * ```javascript
  62209. * BABYLON.DracoCompression.Configuration = {
  62210. * decoder: {
  62211. * wasmUrl: "<url to the WebAssembly library>",
  62212. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  62213. * fallbackUrl: "<url to the fallback JavaScript library>",
  62214. * }
  62215. * };
  62216. * ```
  62217. *
  62218. * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.
  62219. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  62220. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  62221. *
  62222. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  62223. * ```javascript
  62224. * var dracoCompression = new BABYLON.DracoCompression();
  62225. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  62226. * [BABYLON.VertexBuffer.PositionKind]: 0
  62227. * });
  62228. * ```
  62229. *
  62230. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  62231. */
  62232. var DracoCompression = /** @class */ (function () {
  62233. /**
  62234. * Constructor
  62235. */
  62236. function DracoCompression() {
  62237. }
  62238. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  62239. /**
  62240. * Returns true if the decoder is available.
  62241. */
  62242. get: function () {
  62243. if (typeof DracoDecoderModule !== "undefined") {
  62244. return true;
  62245. }
  62246. var decoder = DracoCompression.Configuration.decoder;
  62247. if (decoder) {
  62248. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62249. return true;
  62250. }
  62251. if (decoder.fallbackUrl) {
  62252. return true;
  62253. }
  62254. }
  62255. return false;
  62256. },
  62257. enumerable: true,
  62258. configurable: true
  62259. });
  62260. /**
  62261. * Stop all async operations and release resources.
  62262. */
  62263. DracoCompression.prototype.dispose = function () {
  62264. };
  62265. /**
  62266. * Decode Draco compressed mesh data to vertex data.
  62267. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  62268. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  62269. * @returns A promise that resolves with the decoded vertex data
  62270. */
  62271. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  62272. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  62273. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  62274. var module = wrappedModule.module;
  62275. var vertexData = new BABYLON.VertexData();
  62276. var buffer = new module.DecoderBuffer();
  62277. buffer.Init(dataView, dataView.byteLength);
  62278. var decoder = new module.Decoder();
  62279. var geometry;
  62280. var status;
  62281. try {
  62282. var type = decoder.GetEncodedGeometryType(buffer);
  62283. switch (type) {
  62284. case module.TRIANGULAR_MESH:
  62285. geometry = new module.Mesh();
  62286. status = decoder.DecodeBufferToMesh(buffer, geometry);
  62287. break;
  62288. case module.POINT_CLOUD:
  62289. geometry = new module.PointCloud();
  62290. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  62291. break;
  62292. default:
  62293. throw new Error("Invalid geometry type " + type);
  62294. }
  62295. if (!status.ok() || !geometry.ptr) {
  62296. throw new Error(status.error_msg());
  62297. }
  62298. var numPoints = geometry.num_points();
  62299. if (type === module.TRIANGULAR_MESH) {
  62300. var numFaces = geometry.num_faces();
  62301. var faceIndices = new module.DracoInt32Array();
  62302. try {
  62303. var indices = new Uint32Array(numFaces * 3);
  62304. for (var i = 0; i < numFaces; i++) {
  62305. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  62306. var offset = i * 3;
  62307. indices[offset + 0] = faceIndices.GetValue(0);
  62308. indices[offset + 1] = faceIndices.GetValue(1);
  62309. indices[offset + 2] = faceIndices.GetValue(2);
  62310. }
  62311. vertexData.indices = indices;
  62312. }
  62313. finally {
  62314. module.destroy(faceIndices);
  62315. }
  62316. }
  62317. for (var kind in attributes) {
  62318. var uniqueId = attributes[kind];
  62319. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  62320. var dracoData = new module.DracoFloat32Array();
  62321. try {
  62322. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  62323. var babylonData = new Float32Array(numPoints * attribute.num_components());
  62324. for (var i = 0; i < babylonData.length; i++) {
  62325. babylonData[i] = dracoData.GetValue(i);
  62326. }
  62327. vertexData.set(babylonData, kind);
  62328. }
  62329. finally {
  62330. module.destroy(dracoData);
  62331. }
  62332. }
  62333. }
  62334. finally {
  62335. if (geometry) {
  62336. module.destroy(geometry);
  62337. }
  62338. module.destroy(decoder);
  62339. module.destroy(buffer);
  62340. }
  62341. return vertexData;
  62342. });
  62343. };
  62344. DracoCompression._GetDecoderModule = function () {
  62345. if (!DracoCompression._DecoderModulePromise) {
  62346. var promise = null;
  62347. var config_1 = {};
  62348. if (typeof DracoDecoderModule !== "undefined") {
  62349. promise = Promise.resolve();
  62350. }
  62351. else {
  62352. var decoder = DracoCompression.Configuration.decoder;
  62353. if (decoder) {
  62354. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62355. promise = Promise.all([
  62356. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  62357. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  62358. config_1.wasmBinary = data;
  62359. })
  62360. ]);
  62361. }
  62362. else if (decoder.fallbackUrl) {
  62363. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  62364. }
  62365. }
  62366. }
  62367. if (!promise) {
  62368. throw new Error("Draco decoder module is not available");
  62369. }
  62370. DracoCompression._DecoderModulePromise = promise.then(function () {
  62371. return new Promise(function (resolve) {
  62372. config_1.onModuleLoaded = function (decoderModule) {
  62373. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  62374. resolve({ module: decoderModule });
  62375. };
  62376. DracoDecoderModule(config_1);
  62377. });
  62378. });
  62379. }
  62380. return DracoCompression._DecoderModulePromise;
  62381. };
  62382. DracoCompression._LoadScriptAsync = function (url) {
  62383. return new Promise(function (resolve, reject) {
  62384. BABYLON.Tools.LoadScript(url, function () {
  62385. resolve();
  62386. }, function (message) {
  62387. reject(new Error(message));
  62388. });
  62389. });
  62390. };
  62391. DracoCompression._LoadFileAsync = function (url) {
  62392. return new Promise(function (resolve, reject) {
  62393. BABYLON.Tools.LoadFile(url, function (data) {
  62394. resolve(data);
  62395. }, undefined, undefined, true, function (request, exception) {
  62396. reject(exception);
  62397. });
  62398. });
  62399. };
  62400. /**
  62401. * The configuration. Defaults to the following urls:
  62402. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  62403. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  62404. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62405. */
  62406. DracoCompression.Configuration = {
  62407. decoder: {
  62408. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62409. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62410. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62411. }
  62412. };
  62413. return DracoCompression;
  62414. }());
  62415. BABYLON.DracoCompression = DracoCompression;
  62416. })(BABYLON || (BABYLON = {}));
  62417. //# sourceMappingURL=babylon.dracoCompression.js.map
  62418. var BABYLON;
  62419. (function (BABYLON) {
  62420. var AudioEngine = /** @class */ (function () {
  62421. function AudioEngine() {
  62422. this._audioContext = null;
  62423. this._audioContextInitialized = false;
  62424. this.canUseWebAudio = false;
  62425. this.WarnedWebAudioUnsupported = false;
  62426. this.unlocked = false;
  62427. this.isMP3supported = false;
  62428. this.isOGGsupported = false;
  62429. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62430. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62431. this.canUseWebAudio = true;
  62432. }
  62433. var audioElem = document.createElement('audio');
  62434. try {
  62435. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62436. this.isMP3supported = true;
  62437. }
  62438. }
  62439. catch (e) {
  62440. // protect error during capability check.
  62441. }
  62442. try {
  62443. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62444. this.isOGGsupported = true;
  62445. }
  62446. }
  62447. catch (e) {
  62448. // protect error during capability check.
  62449. }
  62450. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62451. this._unlockiOSaudio();
  62452. }
  62453. else {
  62454. this.unlocked = true;
  62455. }
  62456. }
  62457. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62458. get: function () {
  62459. if (!this._audioContextInitialized) {
  62460. this._initializeAudioContext();
  62461. }
  62462. return this._audioContext;
  62463. },
  62464. enumerable: true,
  62465. configurable: true
  62466. });
  62467. AudioEngine.prototype._unlockiOSaudio = function () {
  62468. var _this = this;
  62469. var unlockaudio = function () {
  62470. if (!_this.audioContext) {
  62471. return;
  62472. }
  62473. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62474. var source = _this.audioContext.createBufferSource();
  62475. source.buffer = buffer;
  62476. source.connect(_this.audioContext.destination);
  62477. source.start(0);
  62478. setTimeout(function () {
  62479. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62480. _this.unlocked = true;
  62481. window.removeEventListener('touchend', unlockaudio, false);
  62482. if (_this.onAudioUnlocked) {
  62483. _this.onAudioUnlocked();
  62484. }
  62485. }
  62486. }, 0);
  62487. };
  62488. window.addEventListener('touchend', unlockaudio, false);
  62489. };
  62490. AudioEngine.prototype._initializeAudioContext = function () {
  62491. try {
  62492. if (this.canUseWebAudio) {
  62493. this._audioContext = new AudioContext();
  62494. // create a global volume gain node
  62495. this.masterGain = this._audioContext.createGain();
  62496. this.masterGain.gain.value = 1;
  62497. this.masterGain.connect(this._audioContext.destination);
  62498. this._audioContextInitialized = true;
  62499. }
  62500. }
  62501. catch (e) {
  62502. this.canUseWebAudio = false;
  62503. BABYLON.Tools.Error("Web Audio: " + e.message);
  62504. }
  62505. };
  62506. AudioEngine.prototype.dispose = function () {
  62507. if (this.canUseWebAudio && this._audioContextInitialized) {
  62508. if (this._connectedAnalyser && this._audioContext) {
  62509. this._connectedAnalyser.stopDebugCanvas();
  62510. this._connectedAnalyser.dispose();
  62511. this.masterGain.disconnect();
  62512. this.masterGain.connect(this._audioContext.destination);
  62513. this._connectedAnalyser = null;
  62514. }
  62515. this.masterGain.gain.value = 1;
  62516. }
  62517. this.WarnedWebAudioUnsupported = false;
  62518. };
  62519. AudioEngine.prototype.getGlobalVolume = function () {
  62520. if (this.canUseWebAudio && this._audioContextInitialized) {
  62521. return this.masterGain.gain.value;
  62522. }
  62523. else {
  62524. return -1;
  62525. }
  62526. };
  62527. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62528. if (this.canUseWebAudio && this._audioContextInitialized) {
  62529. this.masterGain.gain.value = newVolume;
  62530. }
  62531. };
  62532. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62533. if (this._connectedAnalyser) {
  62534. this._connectedAnalyser.stopDebugCanvas();
  62535. }
  62536. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62537. this._connectedAnalyser = analyser;
  62538. this.masterGain.disconnect();
  62539. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62540. }
  62541. };
  62542. return AudioEngine;
  62543. }());
  62544. BABYLON.AudioEngine = AudioEngine;
  62545. })(BABYLON || (BABYLON = {}));
  62546. //# sourceMappingURL=babylon.audioEngine.js.map
  62547. var BABYLON;
  62548. (function (BABYLON) {
  62549. var Sound = /** @class */ (function () {
  62550. /**
  62551. * Create a sound and attach it to a scene
  62552. * @param name Name of your sound
  62553. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  62554. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62555. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62556. */
  62557. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62558. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62559. var _this = this;
  62560. this.autoplay = false;
  62561. this.loop = false;
  62562. this.useCustomAttenuation = false;
  62563. this.spatialSound = false;
  62564. this.refDistance = 1;
  62565. this.rolloffFactor = 1;
  62566. this.maxDistance = 100;
  62567. this.distanceModel = "linear";
  62568. this._panningModel = "equalpower";
  62569. this._playbackRate = 1;
  62570. this._streaming = false;
  62571. this._startTime = 0;
  62572. this._startOffset = 0;
  62573. this._position = BABYLON.Vector3.Zero();
  62574. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62575. this._volume = 1;
  62576. this._isReadyToPlay = false;
  62577. this.isPlaying = false;
  62578. this.isPaused = false;
  62579. this._isDirectional = false;
  62580. // Used if you'd like to create a directional sound.
  62581. // If not set, the sound will be omnidirectional
  62582. this._coneInnerAngle = 360;
  62583. this._coneOuterAngle = 360;
  62584. this._coneOuterGain = 0;
  62585. this._isOutputConnected = false;
  62586. this._urlType = "Unknown";
  62587. this.name = name;
  62588. this._scene = scene;
  62589. this._readyToPlayCallback = readyToPlayCallback;
  62590. // Default custom attenuation function is a linear attenuation
  62591. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62592. if (currentDistance < maxDistance) {
  62593. return currentVolume * (1 - currentDistance / maxDistance);
  62594. }
  62595. else {
  62596. return 0;
  62597. }
  62598. };
  62599. if (options) {
  62600. this.autoplay = options.autoplay || false;
  62601. this.loop = options.loop || false;
  62602. // if volume === 0, we need another way to check this option
  62603. if (options.volume !== undefined) {
  62604. this._volume = options.volume;
  62605. }
  62606. this.spatialSound = options.spatialSound || false;
  62607. this.maxDistance = options.maxDistance || 100;
  62608. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62609. this.rolloffFactor = options.rolloffFactor || 1;
  62610. this.refDistance = options.refDistance || 1;
  62611. this.distanceModel = options.distanceModel || "linear";
  62612. this._playbackRate = options.playbackRate || 1;
  62613. this._streaming = options.streaming || false;
  62614. }
  62615. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62616. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62617. this._soundGain.gain.value = this._volume;
  62618. this._inputAudioNode = this._soundGain;
  62619. this._ouputAudioNode = this._soundGain;
  62620. if (this.spatialSound) {
  62621. this._createSpatialParameters();
  62622. }
  62623. this._scene.mainSoundTrack.AddSound(this);
  62624. var validParameter = true;
  62625. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62626. if (urlOrArrayBuffer) {
  62627. try {
  62628. if (typeof (urlOrArrayBuffer) === "string")
  62629. this._urlType = "String";
  62630. if (Array.isArray(urlOrArrayBuffer))
  62631. this._urlType = "Array";
  62632. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62633. this._urlType = "ArrayBuffer";
  62634. var urls = [];
  62635. var codecSupportedFound = false;
  62636. switch (this._urlType) {
  62637. case "ArrayBuffer":
  62638. if (urlOrArrayBuffer.byteLength > 0) {
  62639. codecSupportedFound = true;
  62640. this._soundLoaded(urlOrArrayBuffer);
  62641. }
  62642. break;
  62643. case "String":
  62644. urls.push(urlOrArrayBuffer);
  62645. case "Array":
  62646. if (urls.length === 0)
  62647. urls = urlOrArrayBuffer;
  62648. // If we found a supported format, we load it immediately and stop the loop
  62649. for (var i = 0; i < urls.length; i++) {
  62650. var url = urls[i];
  62651. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62652. codecSupportedFound = true;
  62653. }
  62654. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62655. codecSupportedFound = true;
  62656. }
  62657. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62658. codecSupportedFound = true;
  62659. }
  62660. if (url.indexOf("blob:") !== -1) {
  62661. codecSupportedFound = true;
  62662. }
  62663. if (codecSupportedFound) {
  62664. // Loading sound using XHR2
  62665. if (!this._streaming) {
  62666. this._scene._loadFile(url, function (data) {
  62667. _this._soundLoaded(data);
  62668. }, undefined, true, true, function (exception) {
  62669. if (exception) {
  62670. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62671. }
  62672. BABYLON.Tools.Error("Sound creation aborted.");
  62673. _this._scene.mainSoundTrack.RemoveSound(_this);
  62674. });
  62675. }
  62676. // Streaming sound using HTML5 Audio tag
  62677. else {
  62678. this._htmlAudioElement = new Audio(url);
  62679. this._htmlAudioElement.controls = false;
  62680. this._htmlAudioElement.loop = this.loop;
  62681. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62682. this._htmlAudioElement.preload = "auto";
  62683. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62684. _this._isReadyToPlay = true;
  62685. if (_this.autoplay) {
  62686. _this.play();
  62687. }
  62688. if (_this._readyToPlayCallback) {
  62689. _this._readyToPlayCallback();
  62690. }
  62691. });
  62692. document.body.appendChild(this._htmlAudioElement);
  62693. }
  62694. break;
  62695. }
  62696. }
  62697. break;
  62698. default:
  62699. validParameter = false;
  62700. break;
  62701. }
  62702. if (!validParameter) {
  62703. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62704. }
  62705. else {
  62706. if (!codecSupportedFound) {
  62707. this._isReadyToPlay = true;
  62708. // Simulating a ready to play event to avoid breaking code path
  62709. if (this._readyToPlayCallback) {
  62710. window.setTimeout(function () {
  62711. if (_this._readyToPlayCallback) {
  62712. _this._readyToPlayCallback();
  62713. }
  62714. }, 1000);
  62715. }
  62716. }
  62717. }
  62718. }
  62719. catch (ex) {
  62720. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62721. this._scene.mainSoundTrack.RemoveSound(this);
  62722. }
  62723. }
  62724. }
  62725. else {
  62726. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62727. this._scene.mainSoundTrack.AddSound(this);
  62728. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62729. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62730. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62731. }
  62732. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62733. if (this._readyToPlayCallback) {
  62734. window.setTimeout(function () {
  62735. if (_this._readyToPlayCallback) {
  62736. _this._readyToPlayCallback();
  62737. }
  62738. }, 1000);
  62739. }
  62740. }
  62741. }
  62742. Sound.prototype.dispose = function () {
  62743. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62744. if (this.isPlaying) {
  62745. this.stop();
  62746. }
  62747. this._isReadyToPlay = false;
  62748. if (this.soundTrackId === -1) {
  62749. this._scene.mainSoundTrack.RemoveSound(this);
  62750. }
  62751. else {
  62752. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62753. }
  62754. if (this._soundGain) {
  62755. this._soundGain.disconnect();
  62756. this._soundGain = null;
  62757. }
  62758. if (this._soundPanner) {
  62759. this._soundPanner.disconnect();
  62760. this._soundPanner = null;
  62761. }
  62762. if (this._soundSource) {
  62763. this._soundSource.disconnect();
  62764. this._soundSource = null;
  62765. }
  62766. this._audioBuffer = null;
  62767. if (this._htmlAudioElement) {
  62768. this._htmlAudioElement.pause();
  62769. this._htmlAudioElement.src = "";
  62770. document.body.removeChild(this._htmlAudioElement);
  62771. }
  62772. if (this._connectedMesh && this._registerFunc) {
  62773. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62774. this._connectedMesh = null;
  62775. }
  62776. }
  62777. };
  62778. Sound.prototype.isReady = function () {
  62779. return this._isReadyToPlay;
  62780. };
  62781. Sound.prototype._soundLoaded = function (audioData) {
  62782. var _this = this;
  62783. if (!BABYLON.Engine.audioEngine.audioContext) {
  62784. return;
  62785. }
  62786. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62787. _this._audioBuffer = buffer;
  62788. _this._isReadyToPlay = true;
  62789. if (_this.autoplay) {
  62790. _this.play();
  62791. }
  62792. if (_this._readyToPlayCallback) {
  62793. _this._readyToPlayCallback();
  62794. }
  62795. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62796. };
  62797. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62798. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62799. this._audioBuffer = audioBuffer;
  62800. this._isReadyToPlay = true;
  62801. }
  62802. };
  62803. Sound.prototype.updateOptions = function (options) {
  62804. if (options) {
  62805. this.loop = options.loop || this.loop;
  62806. this.maxDistance = options.maxDistance || this.maxDistance;
  62807. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62808. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62809. this.refDistance = options.refDistance || this.refDistance;
  62810. this.distanceModel = options.distanceModel || this.distanceModel;
  62811. this._playbackRate = options.playbackRate || this._playbackRate;
  62812. this._updateSpatialParameters();
  62813. if (this.isPlaying) {
  62814. if (this._streaming) {
  62815. this._htmlAudioElement.playbackRate = this._playbackRate;
  62816. }
  62817. else {
  62818. if (this._soundSource) {
  62819. this._soundSource.playbackRate.value = this._playbackRate;
  62820. }
  62821. }
  62822. }
  62823. }
  62824. };
  62825. Sound.prototype._createSpatialParameters = function () {
  62826. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62827. if (this._scene.headphone) {
  62828. this._panningModel = "HRTF";
  62829. }
  62830. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62831. this._updateSpatialParameters();
  62832. this._soundPanner.connect(this._ouputAudioNode);
  62833. this._inputAudioNode = this._soundPanner;
  62834. }
  62835. };
  62836. Sound.prototype._updateSpatialParameters = function () {
  62837. if (this.spatialSound && this._soundPanner) {
  62838. if (this.useCustomAttenuation) {
  62839. // Tricks to disable in a way embedded Web Audio attenuation
  62840. this._soundPanner.distanceModel = "linear";
  62841. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62842. this._soundPanner.refDistance = 1;
  62843. this._soundPanner.rolloffFactor = 1;
  62844. this._soundPanner.panningModel = this._panningModel;
  62845. }
  62846. else {
  62847. this._soundPanner.distanceModel = this.distanceModel;
  62848. this._soundPanner.maxDistance = this.maxDistance;
  62849. this._soundPanner.refDistance = this.refDistance;
  62850. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62851. this._soundPanner.panningModel = this._panningModel;
  62852. }
  62853. }
  62854. };
  62855. Sound.prototype.switchPanningModelToHRTF = function () {
  62856. this._panningModel = "HRTF";
  62857. this._switchPanningModel();
  62858. };
  62859. Sound.prototype.switchPanningModelToEqualPower = function () {
  62860. this._panningModel = "equalpower";
  62861. this._switchPanningModel();
  62862. };
  62863. Sound.prototype._switchPanningModel = function () {
  62864. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62865. this._soundPanner.panningModel = this._panningModel;
  62866. }
  62867. };
  62868. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62869. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62870. if (this._isOutputConnected) {
  62871. this._ouputAudioNode.disconnect();
  62872. }
  62873. this._ouputAudioNode.connect(soundTrackAudioNode);
  62874. this._isOutputConnected = true;
  62875. }
  62876. };
  62877. /**
  62878. * Transform this sound into a directional source
  62879. * @param coneInnerAngle Size of the inner cone in degree
  62880. * @param coneOuterAngle Size of the outer cone in degree
  62881. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62882. */
  62883. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62884. if (coneOuterAngle < coneInnerAngle) {
  62885. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62886. return;
  62887. }
  62888. this._coneInnerAngle = coneInnerAngle;
  62889. this._coneOuterAngle = coneOuterAngle;
  62890. this._coneOuterGain = coneOuterGain;
  62891. this._isDirectional = true;
  62892. if (this.isPlaying && this.loop) {
  62893. this.stop();
  62894. this.play();
  62895. }
  62896. };
  62897. Sound.prototype.setPosition = function (newPosition) {
  62898. this._position = newPosition;
  62899. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62900. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62901. }
  62902. };
  62903. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62904. this._localDirection = newLocalDirection;
  62905. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62906. this._updateDirection();
  62907. }
  62908. };
  62909. Sound.prototype._updateDirection = function () {
  62910. if (!this._connectedMesh || !this._soundPanner) {
  62911. return;
  62912. }
  62913. var mat = this._connectedMesh.getWorldMatrix();
  62914. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62915. direction.normalize();
  62916. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62917. };
  62918. Sound.prototype.updateDistanceFromListener = function () {
  62919. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62920. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62921. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62922. }
  62923. };
  62924. Sound.prototype.setAttenuationFunction = function (callback) {
  62925. this._customAttenuationFunction = callback;
  62926. };
  62927. /**
  62928. * Play the sound
  62929. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62930. * @param offset (optional) Start the sound setting it at a specific time
  62931. */
  62932. Sound.prototype.play = function (time, offset) {
  62933. var _this = this;
  62934. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62935. try {
  62936. if (this._startOffset < 0) {
  62937. time = -this._startOffset;
  62938. this._startOffset = 0;
  62939. }
  62940. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62941. if (!this._soundSource || !this._streamingSource) {
  62942. if (this.spatialSound && this._soundPanner) {
  62943. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62944. if (this._isDirectional) {
  62945. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62946. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62947. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62948. if (this._connectedMesh) {
  62949. this._updateDirection();
  62950. }
  62951. else {
  62952. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62953. }
  62954. }
  62955. }
  62956. }
  62957. if (this._streaming) {
  62958. if (!this._streamingSource) {
  62959. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62960. this._htmlAudioElement.onended = function () { _this._onended(); };
  62961. this._htmlAudioElement.playbackRate = this._playbackRate;
  62962. }
  62963. this._streamingSource.disconnect();
  62964. this._streamingSource.connect(this._inputAudioNode);
  62965. this._htmlAudioElement.play();
  62966. }
  62967. else {
  62968. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62969. this._soundSource.buffer = this._audioBuffer;
  62970. this._soundSource.connect(this._inputAudioNode);
  62971. this._soundSource.loop = this.loop;
  62972. this._soundSource.playbackRate.value = this._playbackRate;
  62973. this._soundSource.onended = function () { _this._onended(); };
  62974. if (this._soundSource.buffer) {
  62975. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62976. }
  62977. }
  62978. this._startTime = startTime;
  62979. this.isPlaying = true;
  62980. this.isPaused = false;
  62981. }
  62982. catch (ex) {
  62983. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62984. }
  62985. }
  62986. };
  62987. Sound.prototype._onended = function () {
  62988. this.isPlaying = false;
  62989. if (this.onended) {
  62990. this.onended();
  62991. }
  62992. };
  62993. /**
  62994. * Stop the sound
  62995. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62996. */
  62997. Sound.prototype.stop = function (time) {
  62998. if (this.isPlaying) {
  62999. if (this._streaming) {
  63000. this._htmlAudioElement.pause();
  63001. // Test needed for Firefox or it will generate an Invalid State Error
  63002. if (this._htmlAudioElement.currentTime > 0) {
  63003. this._htmlAudioElement.currentTime = 0;
  63004. }
  63005. }
  63006. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  63007. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  63008. this._soundSource.stop(stopTime);
  63009. this._soundSource.onended = function () { };
  63010. if (!this.isPaused) {
  63011. this._startOffset = 0;
  63012. }
  63013. }
  63014. this.isPlaying = false;
  63015. }
  63016. };
  63017. Sound.prototype.pause = function () {
  63018. if (this.isPlaying) {
  63019. this.isPaused = true;
  63020. if (this._streaming) {
  63021. this._htmlAudioElement.pause();
  63022. }
  63023. else if (BABYLON.Engine.audioEngine.audioContext) {
  63024. this.stop(0);
  63025. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  63026. }
  63027. }
  63028. };
  63029. Sound.prototype.setVolume = function (newVolume, time) {
  63030. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  63031. if (time && BABYLON.Engine.audioEngine.audioContext) {
  63032. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  63033. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  63034. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  63035. }
  63036. else {
  63037. this._soundGain.gain.value = newVolume;
  63038. }
  63039. }
  63040. this._volume = newVolume;
  63041. };
  63042. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  63043. this._playbackRate = newPlaybackRate;
  63044. if (this.isPlaying) {
  63045. if (this._streaming) {
  63046. this._htmlAudioElement.playbackRate = this._playbackRate;
  63047. }
  63048. else if (this._soundSource) {
  63049. this._soundSource.playbackRate.value = this._playbackRate;
  63050. }
  63051. }
  63052. };
  63053. Sound.prototype.getVolume = function () {
  63054. return this._volume;
  63055. };
  63056. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  63057. var _this = this;
  63058. if (this._connectedMesh && this._registerFunc) {
  63059. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63060. this._registerFunc = null;
  63061. }
  63062. this._connectedMesh = meshToConnectTo;
  63063. if (!this.spatialSound) {
  63064. this.spatialSound = true;
  63065. this._createSpatialParameters();
  63066. if (this.isPlaying && this.loop) {
  63067. this.stop();
  63068. this.play();
  63069. }
  63070. }
  63071. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  63072. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  63073. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  63074. };
  63075. Sound.prototype.detachFromMesh = function () {
  63076. if (this._connectedMesh && this._registerFunc) {
  63077. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63078. this._registerFunc = null;
  63079. this._connectedMesh = null;
  63080. }
  63081. };
  63082. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  63083. if (!node.getBoundingInfo) {
  63084. return;
  63085. }
  63086. var mesh = node;
  63087. var boundingInfo = mesh.getBoundingInfo();
  63088. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  63089. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  63090. this._updateDirection();
  63091. }
  63092. };
  63093. Sound.prototype.clone = function () {
  63094. var _this = this;
  63095. if (!this._streaming) {
  63096. var setBufferAndRun = function () {
  63097. if (_this._isReadyToPlay) {
  63098. clonedSound._audioBuffer = _this.getAudioBuffer();
  63099. clonedSound._isReadyToPlay = true;
  63100. if (clonedSound.autoplay) {
  63101. clonedSound.play();
  63102. }
  63103. }
  63104. else {
  63105. window.setTimeout(setBufferAndRun, 300);
  63106. }
  63107. };
  63108. var currentOptions = {
  63109. autoplay: this.autoplay, loop: this.loop,
  63110. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  63111. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  63112. refDistance: this.refDistance, distanceModel: this.distanceModel
  63113. };
  63114. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  63115. if (this.useCustomAttenuation) {
  63116. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  63117. }
  63118. clonedSound.setPosition(this._position);
  63119. clonedSound.setPlaybackRate(this._playbackRate);
  63120. setBufferAndRun();
  63121. return clonedSound;
  63122. }
  63123. // Can't clone a streaming sound
  63124. else {
  63125. return null;
  63126. }
  63127. };
  63128. Sound.prototype.getAudioBuffer = function () {
  63129. return this._audioBuffer;
  63130. };
  63131. Sound.prototype.serialize = function () {
  63132. var serializationObject = {
  63133. name: this.name,
  63134. url: this.name,
  63135. autoplay: this.autoplay,
  63136. loop: this.loop,
  63137. volume: this._volume,
  63138. spatialSound: this.spatialSound,
  63139. maxDistance: this.maxDistance,
  63140. rolloffFactor: this.rolloffFactor,
  63141. refDistance: this.refDistance,
  63142. distanceModel: this.distanceModel,
  63143. playbackRate: this._playbackRate,
  63144. panningModel: this._panningModel,
  63145. soundTrackId: this.soundTrackId
  63146. };
  63147. if (this.spatialSound) {
  63148. if (this._connectedMesh)
  63149. serializationObject.connectedMeshId = this._connectedMesh.id;
  63150. serializationObject.position = this._position.asArray();
  63151. serializationObject.refDistance = this.refDistance;
  63152. serializationObject.distanceModel = this.distanceModel;
  63153. serializationObject.isDirectional = this._isDirectional;
  63154. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  63155. serializationObject.coneInnerAngle = this._coneInnerAngle;
  63156. serializationObject.coneOuterAngle = this._coneOuterAngle;
  63157. serializationObject.coneOuterGain = this._coneOuterGain;
  63158. }
  63159. return serializationObject;
  63160. };
  63161. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  63162. var soundName = parsedSound.name;
  63163. var soundUrl;
  63164. if (parsedSound.url) {
  63165. soundUrl = rootUrl + parsedSound.url;
  63166. }
  63167. else {
  63168. soundUrl = rootUrl + soundName;
  63169. }
  63170. var options = {
  63171. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  63172. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  63173. rolloffFactor: parsedSound.rolloffFactor,
  63174. refDistance: parsedSound.refDistance,
  63175. distanceModel: parsedSound.distanceModel,
  63176. playbackRate: parsedSound.playbackRate
  63177. };
  63178. var newSound;
  63179. if (!sourceSound) {
  63180. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  63181. scene._addPendingData(newSound);
  63182. }
  63183. else {
  63184. var setBufferAndRun = function () {
  63185. if (sourceSound._isReadyToPlay) {
  63186. newSound._audioBuffer = sourceSound.getAudioBuffer();
  63187. newSound._isReadyToPlay = true;
  63188. if (newSound.autoplay) {
  63189. newSound.play();
  63190. }
  63191. }
  63192. else {
  63193. window.setTimeout(setBufferAndRun, 300);
  63194. }
  63195. };
  63196. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  63197. setBufferAndRun();
  63198. }
  63199. if (parsedSound.position) {
  63200. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  63201. newSound.setPosition(soundPosition);
  63202. }
  63203. if (parsedSound.isDirectional) {
  63204. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  63205. if (parsedSound.localDirectionToMesh) {
  63206. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  63207. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  63208. }
  63209. }
  63210. if (parsedSound.connectedMeshId) {
  63211. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  63212. if (connectedMesh) {
  63213. newSound.attachToMesh(connectedMesh);
  63214. }
  63215. }
  63216. return newSound;
  63217. };
  63218. return Sound;
  63219. }());
  63220. BABYLON.Sound = Sound;
  63221. })(BABYLON || (BABYLON = {}));
  63222. //# sourceMappingURL=babylon.sound.js.map
  63223. var BABYLON;
  63224. (function (BABYLON) {
  63225. var SoundTrack = /** @class */ (function () {
  63226. function SoundTrack(scene, options) {
  63227. this.id = -1;
  63228. this._isMainTrack = false;
  63229. this._isInitialized = false;
  63230. this._scene = scene;
  63231. this.soundCollection = new Array();
  63232. this._options = options;
  63233. if (!this._isMainTrack) {
  63234. this._scene.soundTracks.push(this);
  63235. this.id = this._scene.soundTracks.length - 1;
  63236. }
  63237. }
  63238. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  63239. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63240. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  63241. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  63242. if (this._options) {
  63243. if (this._options.volume) {
  63244. this._outputAudioNode.gain.value = this._options.volume;
  63245. }
  63246. if (this._options.mainTrack) {
  63247. this._isMainTrack = this._options.mainTrack;
  63248. }
  63249. }
  63250. this._isInitialized = true;
  63251. }
  63252. };
  63253. SoundTrack.prototype.dispose = function () {
  63254. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  63255. if (this._connectedAnalyser) {
  63256. this._connectedAnalyser.stopDebugCanvas();
  63257. }
  63258. while (this.soundCollection.length) {
  63259. this.soundCollection[0].dispose();
  63260. }
  63261. if (this._outputAudioNode) {
  63262. this._outputAudioNode.disconnect();
  63263. }
  63264. this._outputAudioNode = null;
  63265. }
  63266. };
  63267. SoundTrack.prototype.AddSound = function (sound) {
  63268. if (!this._isInitialized) {
  63269. this._initializeSoundTrackAudioGraph();
  63270. }
  63271. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63272. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  63273. }
  63274. if (sound.soundTrackId) {
  63275. if (sound.soundTrackId === -1) {
  63276. this._scene.mainSoundTrack.RemoveSound(sound);
  63277. }
  63278. else {
  63279. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  63280. }
  63281. }
  63282. this.soundCollection.push(sound);
  63283. sound.soundTrackId = this.id;
  63284. };
  63285. SoundTrack.prototype.RemoveSound = function (sound) {
  63286. var index = this.soundCollection.indexOf(sound);
  63287. if (index !== -1) {
  63288. this.soundCollection.splice(index, 1);
  63289. }
  63290. };
  63291. SoundTrack.prototype.setVolume = function (newVolume) {
  63292. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63293. this._outputAudioNode.gain.value = newVolume;
  63294. }
  63295. };
  63296. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  63297. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63298. for (var i = 0; i < this.soundCollection.length; i++) {
  63299. this.soundCollection[i].switchPanningModelToHRTF();
  63300. }
  63301. }
  63302. };
  63303. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  63304. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63305. for (var i = 0; i < this.soundCollection.length; i++) {
  63306. this.soundCollection[i].switchPanningModelToEqualPower();
  63307. }
  63308. }
  63309. };
  63310. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  63311. if (this._connectedAnalyser) {
  63312. this._connectedAnalyser.stopDebugCanvas();
  63313. }
  63314. this._connectedAnalyser = analyser;
  63315. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63316. this._outputAudioNode.disconnect();
  63317. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  63318. }
  63319. };
  63320. return SoundTrack;
  63321. }());
  63322. BABYLON.SoundTrack = SoundTrack;
  63323. })(BABYLON || (BABYLON = {}));
  63324. //# sourceMappingURL=babylon.soundtrack.js.map
  63325. var BABYLON;
  63326. (function (BABYLON) {
  63327. /**
  63328. * Class used to work with sound analyzer using fast fourier transform (FFT)
  63329. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  63330. */
  63331. var Analyser = /** @class */ (function () {
  63332. /**
  63333. * Creates a new analyser
  63334. * @param scene defines hosting scene
  63335. */
  63336. function Analyser(scene) {
  63337. /**
  63338. * Gets or sets the smoothing
  63339. * @ignorenaming
  63340. */
  63341. this.SMOOTHING = 0.75;
  63342. /**
  63343. * Gets or sets the FFT table size
  63344. * @ignorenaming
  63345. */
  63346. this.FFT_SIZE = 512;
  63347. /**
  63348. * Gets or sets the bar graph amplitude
  63349. * @ignorenaming
  63350. */
  63351. this.BARGRAPHAMPLITUDE = 256;
  63352. /**
  63353. * Gets or sets the position of the debug canvas
  63354. * @ignorenaming
  63355. */
  63356. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  63357. /**
  63358. * Gets or sets the debug canvas size
  63359. * @ignorenaming
  63360. */
  63361. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  63362. this._scene = scene;
  63363. this._audioEngine = BABYLON.Engine.audioEngine;
  63364. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  63365. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  63366. this._webAudioAnalyser.minDecibels = -140;
  63367. this._webAudioAnalyser.maxDecibels = 0;
  63368. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63369. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63370. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  63371. }
  63372. }
  63373. /**
  63374. * Get the number of data values you will have to play with for the visualization
  63375. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63376. * @returns a number
  63377. */
  63378. Analyser.prototype.getFrequencyBinCount = function () {
  63379. if (this._audioEngine.canUseWebAudio) {
  63380. return this._webAudioAnalyser.frequencyBinCount;
  63381. }
  63382. else {
  63383. return 0;
  63384. }
  63385. };
  63386. /**
  63387. * Gets the current frequency data as a byte array
  63388. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63389. * @returns a Uint8Array
  63390. */
  63391. Analyser.prototype.getByteFrequencyData = function () {
  63392. if (this._audioEngine.canUseWebAudio) {
  63393. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63394. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63395. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63396. }
  63397. return this._byteFreqs;
  63398. };
  63399. /**
  63400. * Gets the current waveform as a byte array
  63401. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63402. * @returns a Uint8Array
  63403. */
  63404. Analyser.prototype.getByteTimeDomainData = function () {
  63405. if (this._audioEngine.canUseWebAudio) {
  63406. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63407. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63408. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63409. }
  63410. return this._byteTime;
  63411. };
  63412. /**
  63413. * Gets the current frequency data as a float array
  63414. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63415. * @returns a Float32Array
  63416. */
  63417. Analyser.prototype.getFloatFrequencyData = function () {
  63418. if (this._audioEngine.canUseWebAudio) {
  63419. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63420. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63421. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63422. }
  63423. return this._floatFreqs;
  63424. };
  63425. /**
  63426. * Renders the debug canvas
  63427. */
  63428. Analyser.prototype.drawDebugCanvas = function () {
  63429. var _this = this;
  63430. if (this._audioEngine.canUseWebAudio) {
  63431. if (!this._debugCanvas) {
  63432. this._debugCanvas = document.createElement("canvas");
  63433. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63434. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63435. this._debugCanvas.style.position = "absolute";
  63436. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63437. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63438. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63439. document.body.appendChild(this._debugCanvas);
  63440. this._registerFunc = function () {
  63441. _this.drawDebugCanvas();
  63442. };
  63443. this._scene.registerBeforeRender(this._registerFunc);
  63444. }
  63445. if (this._registerFunc && this._debugCanvasContext) {
  63446. var workingArray = this.getByteFrequencyData();
  63447. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63448. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63449. // Draw the frequency domain chart.
  63450. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63451. var value = workingArray[i];
  63452. var percent = value / this.BARGRAPHAMPLITUDE;
  63453. var height = this.DEBUGCANVASSIZE.height * percent;
  63454. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63455. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63456. var hue = i / this.getFrequencyBinCount() * 360;
  63457. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63458. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63459. }
  63460. }
  63461. }
  63462. };
  63463. /**
  63464. * Stops rendering the debug canvas and removes it
  63465. */
  63466. Analyser.prototype.stopDebugCanvas = function () {
  63467. if (this._debugCanvas) {
  63468. if (this._registerFunc) {
  63469. this._scene.unregisterBeforeRender(this._registerFunc);
  63470. this._registerFunc = null;
  63471. }
  63472. document.body.removeChild(this._debugCanvas);
  63473. this._debugCanvas = null;
  63474. this._debugCanvasContext = null;
  63475. }
  63476. };
  63477. /**
  63478. * Connects two audio nodes
  63479. * @param inputAudioNode defines first node to connect
  63480. * @param outputAudioNode defines second node to connect
  63481. */
  63482. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63483. if (this._audioEngine.canUseWebAudio) {
  63484. inputAudioNode.connect(this._webAudioAnalyser);
  63485. this._webAudioAnalyser.connect(outputAudioNode);
  63486. }
  63487. };
  63488. /**
  63489. * Releases all associated resources
  63490. */
  63491. Analyser.prototype.dispose = function () {
  63492. if (this._audioEngine.canUseWebAudio) {
  63493. this._webAudioAnalyser.disconnect();
  63494. }
  63495. };
  63496. return Analyser;
  63497. }());
  63498. BABYLON.Analyser = Analyser;
  63499. })(BABYLON || (BABYLON = {}));
  63500. //# sourceMappingURL=babylon.analyser.js.map
  63501. var BABYLON;
  63502. (function (BABYLON) {
  63503. var CubeTexture = /** @class */ (function (_super) {
  63504. __extends(CubeTexture, _super);
  63505. /**
  63506. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63507. * as prefiltered data.
  63508. * @param rootUrl defines the url of the texture or the root name of the six images
  63509. * @param scene defines the scene the texture is attached to
  63510. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63511. * @param noMipmap defines if mipmaps should be created or not
  63512. * @param files defines the six files to load for the different faces
  63513. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63514. * @param onError defines a callback triggered in case of error during load
  63515. * @param format defines the internal format to use for the texture once loaded
  63516. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63517. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63518. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63519. * @return the cube texture
  63520. */
  63521. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials) {
  63522. if (extensions === void 0) { extensions = null; }
  63523. if (noMipmap === void 0) { noMipmap = false; }
  63524. if (files === void 0) { files = null; }
  63525. if (onLoad === void 0) { onLoad = null; }
  63526. if (onError === void 0) { onError = null; }
  63527. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63528. if (prefiltered === void 0) { prefiltered = false; }
  63529. if (forcedExtension === void 0) { forcedExtension = null; }
  63530. if (createPolynomials === void 0) { createPolynomials = false; }
  63531. var _this = _super.call(this, scene) || this;
  63532. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63533. /**
  63534. * Gets or sets the center of the bounding box associated with the cube texture
  63535. * It must define where the camera used to render the texture was set
  63536. */
  63537. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63538. _this._rotationY = 0;
  63539. _this.name = rootUrl;
  63540. _this.url = rootUrl;
  63541. _this._noMipmap = noMipmap;
  63542. _this.hasAlpha = false;
  63543. _this._format = format;
  63544. _this._prefiltered = prefiltered;
  63545. _this.isCube = true;
  63546. _this._textureMatrix = BABYLON.Matrix.Identity();
  63547. _this._createPolynomials = createPolynomials;
  63548. if (prefiltered) {
  63549. _this.gammaSpace = false;
  63550. }
  63551. if (!rootUrl && !files) {
  63552. return _this;
  63553. }
  63554. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63555. var lastDot = rootUrl.lastIndexOf(".");
  63556. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63557. var isDDS = (extension === ".dds");
  63558. if (!files) {
  63559. if (!isDDS && !extensions) {
  63560. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63561. }
  63562. files = [];
  63563. if (extensions) {
  63564. for (var index = 0; index < extensions.length; index++) {
  63565. files.push(rootUrl + extensions[index]);
  63566. }
  63567. }
  63568. }
  63569. _this._files = files;
  63570. if (!_this._texture) {
  63571. if (!scene.useDelayedTextureLoading) {
  63572. if (prefiltered) {
  63573. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63574. }
  63575. else {
  63576. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  63577. }
  63578. }
  63579. else {
  63580. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63581. }
  63582. }
  63583. else if (onLoad) {
  63584. if (_this._texture.isReady) {
  63585. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63586. }
  63587. else {
  63588. _this._texture.onLoadedObservable.add(onLoad);
  63589. }
  63590. }
  63591. return _this;
  63592. }
  63593. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63594. get: function () {
  63595. return this._boundingBoxSize;
  63596. },
  63597. /**
  63598. * Gets or sets the size of the bounding box associated with the cube texture
  63599. * When defined, the cubemap will switch to local mode
  63600. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63601. * @example https://www.babylonjs-playground.com/#RNASML
  63602. */
  63603. set: function (value) {
  63604. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63605. return;
  63606. }
  63607. this._boundingBoxSize = value;
  63608. var scene = this.getScene();
  63609. if (scene) {
  63610. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63611. }
  63612. },
  63613. enumerable: true,
  63614. configurable: true
  63615. });
  63616. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63617. /**
  63618. * Gets texture matrix rotation angle around Y axis radians.
  63619. */
  63620. get: function () {
  63621. return this._rotationY;
  63622. },
  63623. /**
  63624. * Sets texture matrix rotation angle around Y axis in radians.
  63625. */
  63626. set: function (value) {
  63627. this._rotationY = value;
  63628. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63629. },
  63630. enumerable: true,
  63631. configurable: true
  63632. });
  63633. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63634. var rootUrlKey = "";
  63635. files.forEach(function (url) { return rootUrlKey += url; });
  63636. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63637. };
  63638. /**
  63639. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63640. * @param url defines the url of the prefiltered texture
  63641. * @param scene defines the scene the texture is attached to
  63642. * @param forcedExtension defines the extension of the file if different from the url
  63643. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63644. * @return the prefiltered texture
  63645. */
  63646. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63647. if (forcedExtension === void 0) { forcedExtension = null; }
  63648. if (createPolynomials === void 0) { createPolynomials = true; }
  63649. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63650. };
  63651. // Methods
  63652. CubeTexture.prototype.delayLoad = function () {
  63653. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63654. return;
  63655. }
  63656. var scene = this.getScene();
  63657. if (!scene) {
  63658. return;
  63659. }
  63660. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63661. this._texture = this._getFromCache(this.url, this._noMipmap);
  63662. if (!this._texture) {
  63663. if (this._prefiltered) {
  63664. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63665. }
  63666. else {
  63667. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63668. }
  63669. }
  63670. };
  63671. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63672. return this._textureMatrix;
  63673. };
  63674. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63675. this._textureMatrix = value;
  63676. };
  63677. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63678. var texture = BABYLON.SerializationHelper.Parse(function () {
  63679. var prefiltered = false;
  63680. if (parsedTexture.prefiltered) {
  63681. prefiltered = parsedTexture.prefiltered;
  63682. }
  63683. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63684. }, parsedTexture, scene);
  63685. // Local Cubemaps
  63686. if (parsedTexture.boundingBoxPosition) {
  63687. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63688. }
  63689. if (parsedTexture.boundingBoxSize) {
  63690. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63691. }
  63692. // Animations
  63693. if (parsedTexture.animations) {
  63694. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63695. var parsedAnimation = parsedTexture.animations[animationIndex];
  63696. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63697. }
  63698. }
  63699. return texture;
  63700. };
  63701. CubeTexture.prototype.clone = function () {
  63702. var _this = this;
  63703. return BABYLON.SerializationHelper.Clone(function () {
  63704. var scene = _this.getScene();
  63705. if (!scene) {
  63706. return _this;
  63707. }
  63708. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63709. }, this);
  63710. };
  63711. __decorate([
  63712. BABYLON.serialize("rotationY")
  63713. ], CubeTexture.prototype, "_rotationY", void 0);
  63714. return CubeTexture;
  63715. }(BABYLON.BaseTexture));
  63716. BABYLON.CubeTexture = CubeTexture;
  63717. })(BABYLON || (BABYLON = {}));
  63718. //# sourceMappingURL=babylon.cubeTexture.js.map
  63719. var BABYLON;
  63720. (function (BABYLON) {
  63721. var RenderTargetTexture = /** @class */ (function (_super) {
  63722. __extends(RenderTargetTexture, _super);
  63723. /**
  63724. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63725. * or used a shadow, depth texture...
  63726. * @param name The friendly name of the texture
  63727. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  63728. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63729. * @param generateMipMaps True if mip maps need to be generated after render.
  63730. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63731. * @param type The type of the buffer in the RTT (int, half float, float...)
  63732. * @param isCube True if a cube texture needs to be created
  63733. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63734. * @param generateDepthBuffer True to generate a depth buffer
  63735. * @param generateStencilBuffer True to generate a stencil buffer
  63736. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63737. */
  63738. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63739. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63740. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63741. if (isCube === void 0) { isCube = false; }
  63742. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63743. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63744. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63745. if (isMulti === void 0) { isMulti = false; }
  63746. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63747. _this.isCube = isCube;
  63748. /**
  63749. * Use this list to define the list of mesh you want to render.
  63750. */
  63751. _this.renderList = new Array();
  63752. _this.renderParticles = true;
  63753. _this.renderSprites = false;
  63754. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63755. _this.ignoreCameraViewport = false;
  63756. // Events
  63757. /**
  63758. * An event triggered when the texture is unbind.
  63759. */
  63760. _this.onBeforeBindObservable = new BABYLON.Observable();
  63761. /**
  63762. * An event triggered when the texture is unbind.
  63763. */
  63764. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63765. /**
  63766. * An event triggered before rendering the texture
  63767. */
  63768. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63769. /**
  63770. * An event triggered after rendering the texture
  63771. */
  63772. _this.onAfterRenderObservable = new BABYLON.Observable();
  63773. /**
  63774. * An event triggered after the texture clear
  63775. */
  63776. _this.onClearObservable = new BABYLON.Observable();
  63777. _this._currentRefreshId = -1;
  63778. _this._refreshRate = 1;
  63779. _this._samples = 1;
  63780. /**
  63781. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63782. * It must define where the camera used to render the texture is set
  63783. */
  63784. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63785. scene = _this.getScene();
  63786. if (!scene) {
  63787. return _this;
  63788. }
  63789. _this._engine = scene.getEngine();
  63790. _this.name = name;
  63791. _this.isRenderTarget = true;
  63792. _this._initialSizeParameter = size;
  63793. _this._processSizeParameter(size);
  63794. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63795. });
  63796. _this._generateMipMaps = generateMipMaps ? true : false;
  63797. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63798. // Rendering groups
  63799. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63800. if (isMulti) {
  63801. return _this;
  63802. }
  63803. _this._renderTargetOptions = {
  63804. generateMipMaps: generateMipMaps,
  63805. type: type,
  63806. samplingMode: samplingMode,
  63807. generateDepthBuffer: generateDepthBuffer,
  63808. generateStencilBuffer: generateStencilBuffer
  63809. };
  63810. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63811. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63812. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63813. }
  63814. if (isCube) {
  63815. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63816. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63817. _this._textureMatrix = BABYLON.Matrix.Identity();
  63818. }
  63819. else {
  63820. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63821. }
  63822. return _this;
  63823. }
  63824. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63825. get: function () {
  63826. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63827. },
  63828. enumerable: true,
  63829. configurable: true
  63830. });
  63831. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63832. get: function () {
  63833. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63834. },
  63835. enumerable: true,
  63836. configurable: true
  63837. });
  63838. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63839. get: function () {
  63840. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63841. },
  63842. enumerable: true,
  63843. configurable: true
  63844. });
  63845. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63846. set: function (callback) {
  63847. if (this._onAfterUnbindObserver) {
  63848. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63849. }
  63850. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63851. },
  63852. enumerable: true,
  63853. configurable: true
  63854. });
  63855. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63856. set: function (callback) {
  63857. if (this._onBeforeRenderObserver) {
  63858. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63859. }
  63860. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63861. },
  63862. enumerable: true,
  63863. configurable: true
  63864. });
  63865. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63866. set: function (callback) {
  63867. if (this._onAfterRenderObserver) {
  63868. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63869. }
  63870. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63871. },
  63872. enumerable: true,
  63873. configurable: true
  63874. });
  63875. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63876. set: function (callback) {
  63877. if (this._onClearObserver) {
  63878. this.onClearObservable.remove(this._onClearObserver);
  63879. }
  63880. this._onClearObserver = this.onClearObservable.add(callback);
  63881. },
  63882. enumerable: true,
  63883. configurable: true
  63884. });
  63885. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63886. get: function () {
  63887. return this._renderTargetOptions;
  63888. },
  63889. enumerable: true,
  63890. configurable: true
  63891. });
  63892. RenderTargetTexture.prototype._onRatioRescale = function () {
  63893. if (this._sizeRatio) {
  63894. this.resize(this._initialSizeParameter);
  63895. }
  63896. };
  63897. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63898. get: function () {
  63899. return this._boundingBoxSize;
  63900. },
  63901. /**
  63902. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63903. * When defined, the cubemap will switch to local mode
  63904. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63905. * @example https://www.babylonjs-playground.com/#RNASML
  63906. */
  63907. set: function (value) {
  63908. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63909. return;
  63910. }
  63911. this._boundingBoxSize = value;
  63912. var scene = this.getScene();
  63913. if (scene) {
  63914. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63915. }
  63916. },
  63917. enumerable: true,
  63918. configurable: true
  63919. });
  63920. /**
  63921. * Creates a depth stencil texture.
  63922. * This is only available in WebGL 2 or with the depth texture extension available.
  63923. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63924. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63925. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63926. */
  63927. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63928. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63929. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63930. if (generateStencil === void 0) { generateStencil = false; }
  63931. if (!this.getScene()) {
  63932. return;
  63933. }
  63934. var engine = this.getScene().getEngine();
  63935. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63936. bilinearFiltering: bilinearFiltering,
  63937. comparisonFunction: comparisonFunction,
  63938. generateStencil: generateStencil,
  63939. isCube: this.isCube
  63940. });
  63941. engine.setFrameBufferDepthStencilTexture(this);
  63942. };
  63943. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63944. if (size.ratio) {
  63945. this._sizeRatio = size.ratio;
  63946. this._size = {
  63947. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63948. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63949. };
  63950. }
  63951. else {
  63952. this._size = size;
  63953. }
  63954. };
  63955. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63956. get: function () {
  63957. return this._samples;
  63958. },
  63959. set: function (value) {
  63960. if (this._samples === value) {
  63961. return;
  63962. }
  63963. var scene = this.getScene();
  63964. if (!scene) {
  63965. return;
  63966. }
  63967. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63968. },
  63969. enumerable: true,
  63970. configurable: true
  63971. });
  63972. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63973. this._currentRefreshId = -1;
  63974. };
  63975. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63976. get: function () {
  63977. return this._refreshRate;
  63978. },
  63979. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63980. set: function (value) {
  63981. this._refreshRate = value;
  63982. this.resetRefreshCounter();
  63983. },
  63984. enumerable: true,
  63985. configurable: true
  63986. });
  63987. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63988. if (!this._postProcessManager) {
  63989. var scene = this.getScene();
  63990. if (!scene) {
  63991. return;
  63992. }
  63993. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63994. this._postProcesses = new Array();
  63995. }
  63996. this._postProcesses.push(postProcess);
  63997. this._postProcesses[0].autoClear = false;
  63998. };
  63999. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  64000. if (!this._postProcesses) {
  64001. return;
  64002. }
  64003. if (dispose) {
  64004. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  64005. var postProcess = _a[_i];
  64006. postProcess.dispose();
  64007. }
  64008. }
  64009. this._postProcesses = [];
  64010. };
  64011. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  64012. if (!this._postProcesses) {
  64013. return;
  64014. }
  64015. var index = this._postProcesses.indexOf(postProcess);
  64016. if (index === -1) {
  64017. return;
  64018. }
  64019. this._postProcesses.splice(index, 1);
  64020. if (this._postProcesses.length > 0) {
  64021. this._postProcesses[0].autoClear = false;
  64022. }
  64023. };
  64024. RenderTargetTexture.prototype._shouldRender = function () {
  64025. if (this._currentRefreshId === -1) { // At least render once
  64026. this._currentRefreshId = 1;
  64027. return true;
  64028. }
  64029. if (this.refreshRate === this._currentRefreshId) {
  64030. this._currentRefreshId = 1;
  64031. return true;
  64032. }
  64033. this._currentRefreshId++;
  64034. return false;
  64035. };
  64036. RenderTargetTexture.prototype.getRenderSize = function () {
  64037. if (this._size.width) {
  64038. return this._size.width;
  64039. }
  64040. return this._size;
  64041. };
  64042. RenderTargetTexture.prototype.getRenderWidth = function () {
  64043. if (this._size.width) {
  64044. return this._size.width;
  64045. }
  64046. return this._size;
  64047. };
  64048. RenderTargetTexture.prototype.getRenderHeight = function () {
  64049. if (this._size.width) {
  64050. return this._size.height;
  64051. }
  64052. return this._size;
  64053. };
  64054. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  64055. get: function () {
  64056. return true;
  64057. },
  64058. enumerable: true,
  64059. configurable: true
  64060. });
  64061. RenderTargetTexture.prototype.scale = function (ratio) {
  64062. var newSize = this.getRenderSize() * ratio;
  64063. this.resize(newSize);
  64064. };
  64065. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  64066. if (this.isCube) {
  64067. return this._textureMatrix;
  64068. }
  64069. return _super.prototype.getReflectionTextureMatrix.call(this);
  64070. };
  64071. RenderTargetTexture.prototype.resize = function (size) {
  64072. this.releaseInternalTexture();
  64073. var scene = this.getScene();
  64074. if (!scene) {
  64075. return;
  64076. }
  64077. this._processSizeParameter(size);
  64078. if (this.isCube) {
  64079. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  64080. }
  64081. else {
  64082. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  64083. }
  64084. };
  64085. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  64086. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  64087. if (dumpForDebug === void 0) { dumpForDebug = false; }
  64088. var scene = this.getScene();
  64089. if (!scene) {
  64090. return;
  64091. }
  64092. var engine = scene.getEngine();
  64093. if (this.useCameraPostProcesses !== undefined) {
  64094. useCameraPostProcess = this.useCameraPostProcesses;
  64095. }
  64096. if (this._waitingRenderList) {
  64097. this.renderList = [];
  64098. for (var index = 0; index < this._waitingRenderList.length; index++) {
  64099. var id = this._waitingRenderList[index];
  64100. var mesh_1 = scene.getMeshByID(id);
  64101. if (mesh_1) {
  64102. this.renderList.push(mesh_1);
  64103. }
  64104. }
  64105. delete this._waitingRenderList;
  64106. }
  64107. // Is predicate defined?
  64108. if (this.renderListPredicate) {
  64109. if (this.renderList) {
  64110. this.renderList.splice(0); // Clear previous renderList
  64111. }
  64112. else {
  64113. this.renderList = [];
  64114. }
  64115. var scene = this.getScene();
  64116. if (!scene) {
  64117. return;
  64118. }
  64119. var sceneMeshes = scene.meshes;
  64120. for (var index = 0; index < sceneMeshes.length; index++) {
  64121. var mesh = sceneMeshes[index];
  64122. if (this.renderListPredicate(mesh)) {
  64123. this.renderList.push(mesh);
  64124. }
  64125. }
  64126. }
  64127. this.onBeforeBindObservable.notifyObservers(this);
  64128. // Set custom projection.
  64129. // Needs to be before binding to prevent changing the aspect ratio.
  64130. var camera;
  64131. if (this.activeCamera) {
  64132. camera = this.activeCamera;
  64133. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64134. if (this.activeCamera !== scene.activeCamera) {
  64135. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  64136. }
  64137. }
  64138. else {
  64139. camera = scene.activeCamera;
  64140. if (camera) {
  64141. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64142. }
  64143. }
  64144. // Prepare renderingManager
  64145. this._renderingManager.reset();
  64146. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  64147. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  64148. var sceneRenderId = scene.getRenderId();
  64149. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  64150. var mesh = currentRenderList[meshIndex];
  64151. if (mesh) {
  64152. if (!mesh.isReady(this.refreshRate === 0)) {
  64153. this.resetRefreshCounter();
  64154. continue;
  64155. }
  64156. mesh._preActivateForIntermediateRendering(sceneRenderId);
  64157. var isMasked = void 0;
  64158. if (!this.renderList && camera) {
  64159. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  64160. }
  64161. else {
  64162. isMasked = false;
  64163. }
  64164. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  64165. mesh._activate(sceneRenderId);
  64166. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  64167. var subMesh = mesh.subMeshes[subIndex];
  64168. scene._activeIndices.addCount(subMesh.indexCount, false);
  64169. this._renderingManager.dispatch(subMesh, mesh);
  64170. }
  64171. }
  64172. }
  64173. }
  64174. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  64175. var particleSystem = scene.particleSystems[particleIndex];
  64176. var emitter = particleSystem.emitter;
  64177. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  64178. continue;
  64179. }
  64180. if (currentRenderList.indexOf(emitter) >= 0) {
  64181. this._renderingManager.dispatchParticles(particleSystem);
  64182. }
  64183. }
  64184. if (this.isCube) {
  64185. for (var face = 0; face < 6; face++) {
  64186. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64187. scene.incrementRenderId();
  64188. scene.resetCachedMaterial();
  64189. }
  64190. }
  64191. else {
  64192. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64193. }
  64194. this.onAfterUnbindObservable.notifyObservers(this);
  64195. if (scene.activeCamera) {
  64196. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  64197. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  64198. }
  64199. engine.setViewport(scene.activeCamera.viewport);
  64200. }
  64201. scene.resetCachedMaterial();
  64202. };
  64203. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  64204. var minimum = 128;
  64205. var x = renderDimension * scale;
  64206. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  64207. // Ensure we don't exceed the render dimension (while staying POT)
  64208. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  64209. };
  64210. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64211. var _this = this;
  64212. if (!this._texture) {
  64213. return;
  64214. }
  64215. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  64216. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64217. });
  64218. };
  64219. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  64220. var scene = this.getScene();
  64221. if (!scene) {
  64222. return;
  64223. }
  64224. var engine = scene.getEngine();
  64225. if (!this._texture) {
  64226. return;
  64227. }
  64228. // Bind
  64229. if (this._postProcessManager) {
  64230. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  64231. }
  64232. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  64233. if (this._texture) {
  64234. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  64235. }
  64236. }
  64237. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  64238. // Clear
  64239. if (this.onClearObservable.hasObservers()) {
  64240. this.onClearObservable.notifyObservers(engine);
  64241. }
  64242. else {
  64243. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  64244. }
  64245. if (!this._doNotChangeAspectRatio) {
  64246. scene.updateTransformMatrix(true);
  64247. }
  64248. // Render
  64249. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  64250. if (this._postProcessManager) {
  64251. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  64252. }
  64253. else if (useCameraPostProcess) {
  64254. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  64255. }
  64256. if (!this._doNotChangeAspectRatio) {
  64257. scene.updateTransformMatrix(true);
  64258. }
  64259. // Dump ?
  64260. if (dumpForDebug) {
  64261. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  64262. }
  64263. // Unbind
  64264. if (!this.isCube || faceIndex === 5) {
  64265. if (this.isCube) {
  64266. if (faceIndex === 5) {
  64267. engine.generateMipMapsForCubemap(this._texture);
  64268. }
  64269. }
  64270. this.unbindFrameBuffer(engine, faceIndex);
  64271. }
  64272. else {
  64273. this.onAfterRenderObservable.notifyObservers(faceIndex);
  64274. }
  64275. };
  64276. /**
  64277. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  64278. * This allowed control for front to back rendering or reversly depending of the special needs.
  64279. *
  64280. * @param renderingGroupId The rendering group id corresponding to its index
  64281. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  64282. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  64283. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  64284. */
  64285. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  64286. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  64287. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  64288. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  64289. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  64290. };
  64291. /**
  64292. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  64293. *
  64294. * @param renderingGroupId The rendering group id corresponding to its index
  64295. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  64296. */
  64297. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  64298. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  64299. };
  64300. RenderTargetTexture.prototype.clone = function () {
  64301. var textureSize = this.getSize();
  64302. var newTexture = new RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  64303. // Base texture
  64304. newTexture.hasAlpha = this.hasAlpha;
  64305. newTexture.level = this.level;
  64306. // RenderTarget Texture
  64307. newTexture.coordinatesMode = this.coordinatesMode;
  64308. if (this.renderList) {
  64309. newTexture.renderList = this.renderList.slice(0);
  64310. }
  64311. return newTexture;
  64312. };
  64313. RenderTargetTexture.prototype.serialize = function () {
  64314. if (!this.name) {
  64315. return null;
  64316. }
  64317. var serializationObject = _super.prototype.serialize.call(this);
  64318. serializationObject.renderTargetSize = this.getRenderSize();
  64319. serializationObject.renderList = [];
  64320. if (this.renderList) {
  64321. for (var index = 0; index < this.renderList.length; index++) {
  64322. serializationObject.renderList.push(this.renderList[index].id);
  64323. }
  64324. }
  64325. return serializationObject;
  64326. };
  64327. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  64328. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  64329. var objBuffer = this.getInternalTexture();
  64330. var scene = this.getScene();
  64331. if (objBuffer && scene) {
  64332. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  64333. }
  64334. };
  64335. RenderTargetTexture.prototype.dispose = function () {
  64336. if (this._postProcessManager) {
  64337. this._postProcessManager.dispose();
  64338. this._postProcessManager = null;
  64339. }
  64340. this.clearPostProcesses(true);
  64341. if (this._resizeObserver) {
  64342. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  64343. this._resizeObserver = null;
  64344. }
  64345. this.renderList = null;
  64346. // Remove from custom render targets
  64347. var scene = this.getScene();
  64348. if (!scene) {
  64349. return;
  64350. }
  64351. var index = scene.customRenderTargets.indexOf(this);
  64352. if (index >= 0) {
  64353. scene.customRenderTargets.splice(index, 1);
  64354. }
  64355. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  64356. var camera = _a[_i];
  64357. index = camera.customRenderTargets.indexOf(this);
  64358. if (index >= 0) {
  64359. camera.customRenderTargets.splice(index, 1);
  64360. }
  64361. }
  64362. _super.prototype.dispose.call(this);
  64363. };
  64364. RenderTargetTexture.prototype._rebuild = function () {
  64365. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64366. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64367. }
  64368. if (this._postProcessManager) {
  64369. this._postProcessManager._rebuild();
  64370. }
  64371. };
  64372. /**
  64373. * Clear the info related to rendering groups preventing retention point in material dispose.
  64374. */
  64375. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64376. if (this._renderingManager) {
  64377. this._renderingManager.freeRenderingGroups();
  64378. }
  64379. };
  64380. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64381. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64382. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64383. return RenderTargetTexture;
  64384. }(BABYLON.Texture));
  64385. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64386. })(BABYLON || (BABYLON = {}));
  64387. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64388. var BABYLON;
  64389. (function (BABYLON) {
  64390. ;
  64391. var MultiRenderTarget = /** @class */ (function (_super) {
  64392. __extends(MultiRenderTarget, _super);
  64393. function MultiRenderTarget(name, size, count, scene, options) {
  64394. var _this = this;
  64395. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64396. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64397. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64398. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64399. _this._engine = scene.getEngine();
  64400. if (!_this.isSupported) {
  64401. _this.dispose();
  64402. return;
  64403. }
  64404. var types = [];
  64405. var samplingModes = [];
  64406. for (var i = 0; i < count; i++) {
  64407. if (options && options.types && options.types[i] !== undefined) {
  64408. types.push(options.types[i]);
  64409. }
  64410. else {
  64411. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64412. }
  64413. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64414. samplingModes.push(options.samplingModes[i]);
  64415. }
  64416. else {
  64417. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64418. }
  64419. }
  64420. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64421. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64422. _this._size = size;
  64423. _this._multiRenderTargetOptions = {
  64424. samplingModes: samplingModes,
  64425. generateMipMaps: generateMipMaps,
  64426. generateDepthBuffer: generateDepthBuffer,
  64427. generateStencilBuffer: generateStencilBuffer,
  64428. generateDepthTexture: generateDepthTexture,
  64429. types: types,
  64430. textureCount: count
  64431. };
  64432. _this._createInternalTextures();
  64433. _this._createTextures();
  64434. return _this;
  64435. }
  64436. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64437. get: function () {
  64438. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64439. },
  64440. enumerable: true,
  64441. configurable: true
  64442. });
  64443. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64444. get: function () {
  64445. return this._textures;
  64446. },
  64447. enumerable: true,
  64448. configurable: true
  64449. });
  64450. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64451. get: function () {
  64452. return this._textures[this._textures.length - 1];
  64453. },
  64454. enumerable: true,
  64455. configurable: true
  64456. });
  64457. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64458. set: function (wrap) {
  64459. if (this._textures) {
  64460. for (var i = 0; i < this._textures.length; i++) {
  64461. this._textures[i].wrapU = wrap;
  64462. }
  64463. }
  64464. },
  64465. enumerable: true,
  64466. configurable: true
  64467. });
  64468. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64469. set: function (wrap) {
  64470. if (this._textures) {
  64471. for (var i = 0; i < this._textures.length; i++) {
  64472. this._textures[i].wrapV = wrap;
  64473. }
  64474. }
  64475. },
  64476. enumerable: true,
  64477. configurable: true
  64478. });
  64479. MultiRenderTarget.prototype._rebuild = function () {
  64480. this.releaseInternalTextures();
  64481. this._createInternalTextures();
  64482. for (var i = 0; i < this._internalTextures.length; i++) {
  64483. var texture = this._textures[i];
  64484. texture._texture = this._internalTextures[i];
  64485. }
  64486. // Keeps references to frame buffer and stencil/depth buffer
  64487. this._texture = this._internalTextures[0];
  64488. };
  64489. MultiRenderTarget.prototype._createInternalTextures = function () {
  64490. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64491. };
  64492. MultiRenderTarget.prototype._createTextures = function () {
  64493. this._textures = [];
  64494. for (var i = 0; i < this._internalTextures.length; i++) {
  64495. var texture = new BABYLON.Texture(null, this.getScene());
  64496. texture._texture = this._internalTextures[i];
  64497. this._textures.push(texture);
  64498. }
  64499. // Keeps references to frame buffer and stencil/depth buffer
  64500. this._texture = this._internalTextures[0];
  64501. };
  64502. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64503. get: function () {
  64504. return this._samples;
  64505. },
  64506. set: function (value) {
  64507. if (this._samples === value) {
  64508. return;
  64509. }
  64510. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64511. },
  64512. enumerable: true,
  64513. configurable: true
  64514. });
  64515. MultiRenderTarget.prototype.resize = function (size) {
  64516. this.releaseInternalTextures();
  64517. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64518. this._createInternalTextures();
  64519. };
  64520. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64521. var _this = this;
  64522. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64523. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64524. });
  64525. };
  64526. MultiRenderTarget.prototype.dispose = function () {
  64527. this.releaseInternalTextures();
  64528. _super.prototype.dispose.call(this);
  64529. };
  64530. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64531. if (!this._internalTextures) {
  64532. return;
  64533. }
  64534. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64535. if (this._internalTextures[i] !== undefined) {
  64536. this._internalTextures[i].dispose();
  64537. this._internalTextures.splice(i, 1);
  64538. }
  64539. }
  64540. };
  64541. return MultiRenderTarget;
  64542. }(BABYLON.RenderTargetTexture));
  64543. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64544. })(BABYLON || (BABYLON = {}));
  64545. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64546. var BABYLON;
  64547. (function (BABYLON) {
  64548. var MirrorTexture = /** @class */ (function (_super) {
  64549. __extends(MirrorTexture, _super);
  64550. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64551. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64552. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64553. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64554. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64555. _this.scene = scene;
  64556. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64557. _this._transformMatrix = BABYLON.Matrix.Zero();
  64558. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64559. _this._adaptiveBlurKernel = 0;
  64560. _this._blurKernelX = 0;
  64561. _this._blurKernelY = 0;
  64562. _this._blurRatio = 1.0;
  64563. _this.ignoreCameraViewport = true;
  64564. _this._updateGammaSpace();
  64565. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64566. _this._updateGammaSpace;
  64567. });
  64568. _this.onBeforeRenderObservable.add(function () {
  64569. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64570. _this._savedViewMatrix = scene.getViewMatrix();
  64571. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64572. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64573. scene.clipPlane = _this.mirrorPlane;
  64574. scene.getEngine().cullBackFaces = false;
  64575. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64576. });
  64577. _this.onAfterRenderObservable.add(function () {
  64578. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64579. scene.getEngine().cullBackFaces = true;
  64580. scene._mirroredCameraPosition = null;
  64581. delete scene.clipPlane;
  64582. });
  64583. return _this;
  64584. }
  64585. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64586. get: function () {
  64587. return this._blurRatio;
  64588. },
  64589. set: function (value) {
  64590. if (this._blurRatio === value) {
  64591. return;
  64592. }
  64593. this._blurRatio = value;
  64594. this._preparePostProcesses();
  64595. },
  64596. enumerable: true,
  64597. configurable: true
  64598. });
  64599. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64600. set: function (value) {
  64601. this._adaptiveBlurKernel = value;
  64602. this._autoComputeBlurKernel();
  64603. },
  64604. enumerable: true,
  64605. configurable: true
  64606. });
  64607. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64608. set: function (value) {
  64609. this.blurKernelX = value;
  64610. this.blurKernelY = value;
  64611. },
  64612. enumerable: true,
  64613. configurable: true
  64614. });
  64615. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64616. get: function () {
  64617. return this._blurKernelX;
  64618. },
  64619. set: function (value) {
  64620. if (this._blurKernelX === value) {
  64621. return;
  64622. }
  64623. this._blurKernelX = value;
  64624. this._preparePostProcesses();
  64625. },
  64626. enumerable: true,
  64627. configurable: true
  64628. });
  64629. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64630. get: function () {
  64631. return this._blurKernelY;
  64632. },
  64633. set: function (value) {
  64634. if (this._blurKernelY === value) {
  64635. return;
  64636. }
  64637. this._blurKernelY = value;
  64638. this._preparePostProcesses();
  64639. },
  64640. enumerable: true,
  64641. configurable: true
  64642. });
  64643. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64644. var engine = this.getScene().getEngine();
  64645. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64646. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64647. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64648. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64649. };
  64650. MirrorTexture.prototype._onRatioRescale = function () {
  64651. if (this._sizeRatio) {
  64652. this.resize(this._initialSizeParameter);
  64653. if (!this._adaptiveBlurKernel) {
  64654. this._preparePostProcesses();
  64655. }
  64656. }
  64657. if (this._adaptiveBlurKernel) {
  64658. this._autoComputeBlurKernel();
  64659. }
  64660. };
  64661. MirrorTexture.prototype._updateGammaSpace = function () {
  64662. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64663. };
  64664. MirrorTexture.prototype._preparePostProcesses = function () {
  64665. this.clearPostProcesses(true);
  64666. if (this._blurKernelX && this._blurKernelY) {
  64667. var engine = this.getScene().getEngine();
  64668. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64669. this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), this._blurKernelX, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);
  64670. this._blurX.autoClear = false;
  64671. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64672. this._blurX.inputTexture = this._texture;
  64673. }
  64674. else {
  64675. this._blurX.alwaysForcePOT = true;
  64676. }
  64677. this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), this._blurKernelY, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);
  64678. this._blurY.autoClear = false;
  64679. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64680. this.addPostProcess(this._blurX);
  64681. this.addPostProcess(this._blurY);
  64682. }
  64683. else {
  64684. if (this._blurY) {
  64685. this.removePostProcess(this._blurY);
  64686. this._blurY.dispose();
  64687. this._blurY = null;
  64688. }
  64689. if (this._blurX) {
  64690. this.removePostProcess(this._blurX);
  64691. this._blurX.dispose();
  64692. this._blurX = null;
  64693. }
  64694. }
  64695. };
  64696. MirrorTexture.prototype.clone = function () {
  64697. var scene = this.getScene();
  64698. if (!scene) {
  64699. return this;
  64700. }
  64701. var textureSize = this.getSize();
  64702. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64703. // Base texture
  64704. newTexture.hasAlpha = this.hasAlpha;
  64705. newTexture.level = this.level;
  64706. // Mirror Texture
  64707. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64708. if (this.renderList) {
  64709. newTexture.renderList = this.renderList.slice(0);
  64710. }
  64711. return newTexture;
  64712. };
  64713. MirrorTexture.prototype.serialize = function () {
  64714. if (!this.name) {
  64715. return null;
  64716. }
  64717. var serializationObject = _super.prototype.serialize.call(this);
  64718. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64719. return serializationObject;
  64720. };
  64721. MirrorTexture.prototype.dispose = function () {
  64722. _super.prototype.dispose.call(this);
  64723. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64724. };
  64725. return MirrorTexture;
  64726. }(BABYLON.RenderTargetTexture));
  64727. BABYLON.MirrorTexture = MirrorTexture;
  64728. })(BABYLON || (BABYLON = {}));
  64729. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64730. var BABYLON;
  64731. (function (BABYLON) {
  64732. /**
  64733. * Creates a refraction texture used by refraction channel of the standard material.
  64734. * @param name the texture name
  64735. * @param size size of the underlying texture
  64736. * @param scene root scene
  64737. */
  64738. var RefractionTexture = /** @class */ (function (_super) {
  64739. __extends(RefractionTexture, _super);
  64740. function RefractionTexture(name, size, scene, generateMipMaps) {
  64741. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64742. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64743. _this.depth = 2.0;
  64744. _this.onBeforeRenderObservable.add(function () {
  64745. scene.clipPlane = _this.refractionPlane;
  64746. });
  64747. _this.onAfterRenderObservable.add(function () {
  64748. delete scene.clipPlane;
  64749. });
  64750. return _this;
  64751. }
  64752. RefractionTexture.prototype.clone = function () {
  64753. var scene = this.getScene();
  64754. if (!scene) {
  64755. return this;
  64756. }
  64757. var textureSize = this.getSize();
  64758. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64759. // Base texture
  64760. newTexture.hasAlpha = this.hasAlpha;
  64761. newTexture.level = this.level;
  64762. // Refraction Texture
  64763. newTexture.refractionPlane = this.refractionPlane.clone();
  64764. if (this.renderList) {
  64765. newTexture.renderList = this.renderList.slice(0);
  64766. }
  64767. newTexture.depth = this.depth;
  64768. return newTexture;
  64769. };
  64770. RefractionTexture.prototype.serialize = function () {
  64771. if (!this.name) {
  64772. return null;
  64773. }
  64774. var serializationObject = _super.prototype.serialize.call(this);
  64775. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64776. serializationObject.depth = this.depth;
  64777. return serializationObject;
  64778. };
  64779. return RefractionTexture;
  64780. }(BABYLON.RenderTargetTexture));
  64781. BABYLON.RefractionTexture = RefractionTexture;
  64782. })(BABYLON || (BABYLON = {}));
  64783. //# sourceMappingURL=babylon.refractionTexture.js.map
  64784. var BABYLON;
  64785. (function (BABYLON) {
  64786. /**
  64787. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64788. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64789. */
  64790. var DynamicTexture = /** @class */ (function (_super) {
  64791. __extends(DynamicTexture, _super);
  64792. /**
  64793. * Creates a {BABYLON.DynamicTexture}
  64794. * @param name defines the name of the texture
  64795. * @param options provides 3 alternatives for width and height of texture, a canvas, object with width and height properties, number for both width and height
  64796. * @param scene defines the scene where you want the texture
  64797. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64798. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64799. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64800. */
  64801. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64802. if (scene === void 0) { scene = null; }
  64803. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64804. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64805. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64806. _this.name = name;
  64807. _this._engine = _this.getScene().getEngine();
  64808. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64809. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64810. _this._generateMipMaps = generateMipMaps;
  64811. if (options.getContext) {
  64812. _this._canvas = options;
  64813. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64814. }
  64815. else {
  64816. _this._canvas = document.createElement("canvas");
  64817. if (options.width || options.width === 0) {
  64818. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64819. }
  64820. else {
  64821. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64822. }
  64823. }
  64824. var textureSize = _this.getSize();
  64825. _this._canvas.width = textureSize.width;
  64826. _this._canvas.height = textureSize.height;
  64827. _this._context = _this._canvas.getContext("2d");
  64828. return _this;
  64829. }
  64830. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64831. /**
  64832. * Gets the current state of canRescale
  64833. */
  64834. get: function () {
  64835. return true;
  64836. },
  64837. enumerable: true,
  64838. configurable: true
  64839. });
  64840. DynamicTexture.prototype._recreate = function (textureSize) {
  64841. this._canvas.width = textureSize.width;
  64842. this._canvas.height = textureSize.height;
  64843. this.releaseInternalTexture();
  64844. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64845. };
  64846. /**
  64847. * Scales the texture
  64848. * @param ratio the scale factor to apply to both width and height
  64849. */
  64850. DynamicTexture.prototype.scale = function (ratio) {
  64851. var textureSize = this.getSize();
  64852. textureSize.width *= ratio;
  64853. textureSize.height *= ratio;
  64854. this._recreate(textureSize);
  64855. };
  64856. /**
  64857. * Resizes the texture
  64858. * @param width the new width
  64859. * @param height the new height
  64860. */
  64861. DynamicTexture.prototype.scaleTo = function (width, height) {
  64862. var textureSize = this.getSize();
  64863. textureSize.width = width;
  64864. textureSize.height = height;
  64865. this._recreate(textureSize);
  64866. };
  64867. /**
  64868. * Gets the context of the canvas used by the texture
  64869. * @returns the canvas context of the dynamic texture
  64870. */
  64871. DynamicTexture.prototype.getContext = function () {
  64872. return this._context;
  64873. };
  64874. /**
  64875. * Clears the texture
  64876. */
  64877. DynamicTexture.prototype.clear = function () {
  64878. var size = this.getSize();
  64879. this._context.fillRect(0, 0, size.width, size.height);
  64880. };
  64881. /**
  64882. * Updates the texture
  64883. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64884. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  64885. */
  64886. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  64887. if (premulAlpha === void 0) { premulAlpha = false; }
  64888. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  64889. };
  64890. /**
  64891. * Draws text onto the texture
  64892. * @param text defines the text to be drawn
  64893. * @param x defines the placement of the text from the left
  64894. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64895. * @param font defines the font to be used with font-style, font-size, font-name
  64896. * @param color defines the color used for the text
  64897. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64898. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64899. * @param update defines whether texture is immediately update (default is true)
  64900. */
  64901. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64902. if (update === void 0) { update = true; }
  64903. var size = this.getSize();
  64904. if (clearColor) {
  64905. this._context.fillStyle = clearColor;
  64906. this._context.fillRect(0, 0, size.width, size.height);
  64907. }
  64908. this._context.font = font;
  64909. if (x === null || x === undefined) {
  64910. var textSize = this._context.measureText(text);
  64911. x = (size.width - textSize.width) / 2;
  64912. }
  64913. if (y === null || y === undefined) {
  64914. var fontSize = parseInt((font.replace(/\D/g, '')));
  64915. y = (size.height / 2) + (fontSize / 3.65);
  64916. }
  64917. this._context.fillStyle = color;
  64918. this._context.fillText(text, x, y);
  64919. if (update) {
  64920. this.update(invertY);
  64921. }
  64922. };
  64923. /**
  64924. * Clones the texture
  64925. * @returns the clone of the texture.
  64926. */
  64927. DynamicTexture.prototype.clone = function () {
  64928. var scene = this.getScene();
  64929. if (!scene) {
  64930. return this;
  64931. }
  64932. var textureSize = this.getSize();
  64933. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64934. // Base texture
  64935. newTexture.hasAlpha = this.hasAlpha;
  64936. newTexture.level = this.level;
  64937. // Dynamic Texture
  64938. newTexture.wrapU = this.wrapU;
  64939. newTexture.wrapV = this.wrapV;
  64940. return newTexture;
  64941. };
  64942. /** @hidden */
  64943. DynamicTexture.prototype._rebuild = function () {
  64944. this.update();
  64945. };
  64946. return DynamicTexture;
  64947. }(BABYLON.Texture));
  64948. BABYLON.DynamicTexture = DynamicTexture;
  64949. })(BABYLON || (BABYLON = {}));
  64950. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64951. var BABYLON;
  64952. (function (BABYLON) {
  64953. var VideoTexture = /** @class */ (function (_super) {
  64954. __extends(VideoTexture, _super);
  64955. /**
  64956. * Creates a video texture.
  64957. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64958. * @param {string | null} name optional name, will detect from video source, if not defined
  64959. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64960. * @param {BABYLON.Scene} scene is obviously the current scene.
  64961. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64962. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64963. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64964. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64965. */
  64966. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64967. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64968. if (invertY === void 0) { invertY = false; }
  64969. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64970. if (settings === void 0) { settings = {
  64971. autoPlay: true,
  64972. loop: true,
  64973. autoUpdateTexture: true,
  64974. }; }
  64975. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64976. _this._stillImageCaptured = false;
  64977. _this._createInternalTexture = function () {
  64978. if (_this._texture != null) {
  64979. return;
  64980. }
  64981. if (!_this._engine.needPOTTextures ||
  64982. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64983. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64984. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64985. }
  64986. else {
  64987. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64988. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64989. _this._generateMipMaps = false;
  64990. }
  64991. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64992. if (!_this.video.autoplay) {
  64993. var oldHandler_1 = _this.video.onplaying;
  64994. _this.video.onplaying = function () {
  64995. _this.video.onplaying = oldHandler_1;
  64996. _this._texture.isReady = true;
  64997. _this._updateInternalTexture();
  64998. _this.video.pause();
  64999. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65000. _this.onLoadObservable.notifyObservers(_this);
  65001. }
  65002. };
  65003. _this.video.play();
  65004. }
  65005. else {
  65006. _this._texture.isReady = true;
  65007. _this._updateInternalTexture();
  65008. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65009. _this.onLoadObservable.notifyObservers(_this);
  65010. }
  65011. }
  65012. };
  65013. _this.reset = function () {
  65014. if (_this._texture == null) {
  65015. return;
  65016. }
  65017. _this._texture.dispose();
  65018. _this._texture = null;
  65019. };
  65020. _this._updateInternalTexture = function (e) {
  65021. if (_this._texture == null || !_this._texture.isReady) {
  65022. return;
  65023. }
  65024. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  65025. return;
  65026. }
  65027. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  65028. };
  65029. _this._engine = _this.getScene().getEngine();
  65030. _this._generateMipMaps = generateMipMaps;
  65031. _this._samplingMode = samplingMode;
  65032. _this.autoUpdateTexture = settings.autoUpdateTexture;
  65033. _this.name = name || _this._getName(src);
  65034. _this.video = _this._getVideo(src);
  65035. if (settings.autoPlay !== undefined) {
  65036. _this.video.autoplay = settings.autoPlay;
  65037. }
  65038. if (settings.loop !== undefined) {
  65039. _this.video.loop = settings.loop;
  65040. }
  65041. _this.video.addEventListener("canplay", _this._createInternalTexture);
  65042. _this.video.addEventListener("paused", _this._updateInternalTexture);
  65043. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  65044. _this.video.addEventListener("emptied", _this.reset);
  65045. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  65046. _this._createInternalTexture();
  65047. }
  65048. return _this;
  65049. }
  65050. VideoTexture.prototype._getName = function (src) {
  65051. if (src instanceof HTMLVideoElement) {
  65052. return src.currentSrc;
  65053. }
  65054. if (typeof src === "object") {
  65055. return src.toString();
  65056. }
  65057. return src;
  65058. };
  65059. ;
  65060. VideoTexture.prototype._getVideo = function (src) {
  65061. if (src instanceof HTMLVideoElement) {
  65062. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  65063. return src;
  65064. }
  65065. var video = document.createElement("video");
  65066. if (typeof src === "string") {
  65067. BABYLON.Tools.SetCorsBehavior(src, video);
  65068. video.src = src;
  65069. }
  65070. else {
  65071. BABYLON.Tools.SetCorsBehavior(src[0], video);
  65072. src.forEach(function (url) {
  65073. var source = document.createElement("source");
  65074. source.src = url;
  65075. video.appendChild(source);
  65076. });
  65077. }
  65078. return video;
  65079. };
  65080. ;
  65081. /**
  65082. * Internal method to initiate `update`.
  65083. */
  65084. VideoTexture.prototype._rebuild = function () {
  65085. this.update();
  65086. };
  65087. /**
  65088. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  65089. */
  65090. VideoTexture.prototype.update = function () {
  65091. if (!this.autoUpdateTexture) {
  65092. // Expecting user to call `updateTexture` manually
  65093. return;
  65094. }
  65095. this.updateTexture(true);
  65096. };
  65097. /**
  65098. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  65099. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  65100. */
  65101. VideoTexture.prototype.updateTexture = function (isVisible) {
  65102. if (!isVisible) {
  65103. return;
  65104. }
  65105. if (this.video.paused && this._stillImageCaptured) {
  65106. return;
  65107. }
  65108. this._stillImageCaptured = true;
  65109. this._updateInternalTexture();
  65110. };
  65111. /**
  65112. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  65113. * @param url New url.
  65114. */
  65115. VideoTexture.prototype.updateURL = function (url) {
  65116. this.video.src = url;
  65117. };
  65118. VideoTexture.prototype.dispose = function () {
  65119. _super.prototype.dispose.call(this);
  65120. this.video.removeEventListener("canplay", this._createInternalTexture);
  65121. this.video.removeEventListener("paused", this._updateInternalTexture);
  65122. this.video.removeEventListener("seeked", this._updateInternalTexture);
  65123. this.video.removeEventListener("emptied", this.reset);
  65124. this.video.pause();
  65125. };
  65126. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  65127. var video = document.createElement("video");
  65128. var constraintsDeviceId;
  65129. if (constraints && constraints.deviceId) {
  65130. constraintsDeviceId = {
  65131. exact: constraints.deviceId,
  65132. };
  65133. }
  65134. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  65135. if (navigator.mediaDevices) {
  65136. navigator.mediaDevices.getUserMedia({ video: constraints })
  65137. .then(function (stream) {
  65138. if (video.mozSrcObject !== undefined) {
  65139. // hack for Firefox < 19
  65140. video.mozSrcObject = stream;
  65141. }
  65142. else {
  65143. video.srcObject = stream;
  65144. }
  65145. var onPlaying = function () {
  65146. if (onReady) {
  65147. onReady(new VideoTexture("video", video, scene, true, true));
  65148. }
  65149. video.removeEventListener("playing", onPlaying);
  65150. };
  65151. video.addEventListener("playing", onPlaying);
  65152. video.play();
  65153. })
  65154. .catch(function (err) {
  65155. BABYLON.Tools.Error(err.name);
  65156. });
  65157. }
  65158. else {
  65159. navigator.getUserMedia =
  65160. navigator.getUserMedia ||
  65161. navigator.webkitGetUserMedia ||
  65162. navigator.mozGetUserMedia ||
  65163. navigator.msGetUserMedia;
  65164. if (navigator.getUserMedia) {
  65165. navigator.getUserMedia({
  65166. video: {
  65167. deviceId: constraintsDeviceId,
  65168. width: {
  65169. min: (constraints && constraints.minWidth) || 256,
  65170. max: (constraints && constraints.maxWidth) || 640,
  65171. },
  65172. height: {
  65173. min: (constraints && constraints.minHeight) || 256,
  65174. max: (constraints && constraints.maxHeight) || 480,
  65175. },
  65176. },
  65177. }, function (stream) {
  65178. if (video.mozSrcObject !== undefined) {
  65179. // hack for Firefox < 19
  65180. video.mozSrcObject = stream;
  65181. }
  65182. else {
  65183. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  65184. }
  65185. video.play();
  65186. if (onReady) {
  65187. onReady(new VideoTexture("video", video, scene, true, true));
  65188. }
  65189. }, function (e) {
  65190. BABYLON.Tools.Error(e.name);
  65191. });
  65192. }
  65193. }
  65194. };
  65195. return VideoTexture;
  65196. }(BABYLON.Texture));
  65197. BABYLON.VideoTexture = VideoTexture;
  65198. })(BABYLON || (BABYLON = {}));
  65199. //# sourceMappingURL=babylon.videoTexture.js.map
  65200. var BABYLON;
  65201. (function (BABYLON) {
  65202. var RawTexture = /** @class */ (function (_super) {
  65203. __extends(RawTexture, _super);
  65204. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  65205. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65206. if (invertY === void 0) { invertY = false; }
  65207. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65208. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65209. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65210. _this.format = format;
  65211. _this._engine = scene.getEngine();
  65212. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  65213. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65214. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65215. return _this;
  65216. }
  65217. RawTexture.prototype.update = function (data) {
  65218. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65219. };
  65220. // Statics
  65221. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65222. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65223. if (invertY === void 0) { invertY = false; }
  65224. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65225. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  65226. };
  65227. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65228. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65229. if (invertY === void 0) { invertY = false; }
  65230. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65231. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65232. };
  65233. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65234. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65235. if (invertY === void 0) { invertY = false; }
  65236. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65237. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65238. };
  65239. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65240. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65241. if (invertY === void 0) { invertY = false; }
  65242. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65243. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65244. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  65245. };
  65246. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65247. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65248. if (invertY === void 0) { invertY = false; }
  65249. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65250. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65251. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  65252. };
  65253. return RawTexture;
  65254. }(BABYLON.Texture));
  65255. BABYLON.RawTexture = RawTexture;
  65256. })(BABYLON || (BABYLON = {}));
  65257. //# sourceMappingURL=babylon.rawTexture.js.map
  65258. var BABYLON;
  65259. (function (BABYLON) {
  65260. /**
  65261. * Class used to store 3D textures containing user data
  65262. */
  65263. var RawTexture3D = /** @class */ (function (_super) {
  65264. __extends(RawTexture3D, _super);
  65265. /**
  65266. * Create a new RawTexture3D
  65267. * @param data defines the data of the texture
  65268. * @param width defines the width of the texture
  65269. * @param height defines the height of the texture
  65270. * @param depth defines the depth of the texture
  65271. * @param format defines the texture format to use
  65272. * @param scene defines the hosting scene
  65273. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  65274. * @param invertY defines if texture must be stored with Y axis inverted
  65275. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  65276. */
  65277. function RawTexture3D(data, width, height, depth,
  65278. /** Gets or sets the texture format to use*/
  65279. format, scene, generateMipMaps, invertY, samplingMode) {
  65280. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65281. if (invertY === void 0) { invertY = false; }
  65282. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65283. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65284. _this.format = format;
  65285. _this._engine = scene.getEngine();
  65286. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  65287. _this.is3D = true;
  65288. return _this;
  65289. }
  65290. /**
  65291. * Update the texture with new data
  65292. * @param data defines the data to store in the texture
  65293. */
  65294. RawTexture3D.prototype.update = function (data) {
  65295. if (!this._texture) {
  65296. return;
  65297. }
  65298. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  65299. };
  65300. return RawTexture3D;
  65301. }(BABYLON.Texture));
  65302. BABYLON.RawTexture3D = RawTexture3D;
  65303. })(BABYLON || (BABYLON = {}));
  65304. //# sourceMappingURL=babylon.rawTexture3D.js.map
  65305. var BABYLON;
  65306. (function (BABYLON) {
  65307. /**
  65308. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65309. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65310. */
  65311. var PostProcess = /** @class */ (function () {
  65312. /**
  65313. * Creates a new instance PostProcess
  65314. * @param name The name of the PostProcess.
  65315. * @param fragmentUrl The url of the fragment shader to be used.
  65316. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65317. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65318. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65319. * @param camera The camera to apply the render pass to.
  65320. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65321. * @param engine The engine which the post process will be applied. (default: current engine)
  65322. * @param reusable If the post process can be reused on the same frame. (default: false)
  65323. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65324. * @param textureType Type of textures used when performing the post process. (default: 0)
  65325. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65326. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  65327. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65328. */
  65329. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65330. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65331. if (defines === void 0) { defines = null; }
  65332. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65333. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65334. if (blockCompilation === void 0) { blockCompilation = false; }
  65335. this.name = name;
  65336. /**
  65337. * Width of the texture to apply the post process on
  65338. */
  65339. this.width = -1;
  65340. /**
  65341. * Height of the texture to apply the post process on
  65342. */
  65343. this.height = -1;
  65344. /**
  65345. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65346. */
  65347. this._outputTexture = null;
  65348. /**
  65349. * If the buffer needs to be cleared before applying the post process. (default: true)
  65350. * Should be set to false if shader will overwrite all previous pixels.
  65351. */
  65352. this.autoClear = true;
  65353. /**
  65354. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65355. */
  65356. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65357. /**
  65358. * Animations to be used for the post processing
  65359. */
  65360. this.animations = new Array();
  65361. /**
  65362. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65363. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65364. */
  65365. this.enablePixelPerfectMode = false;
  65366. /**
  65367. * Force the postprocess to be applied without taking in account viewport
  65368. */
  65369. this.forceFullscreenViewport = true;
  65370. /**
  65371. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65372. */
  65373. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65374. /**
  65375. * Force textures to be a power of two (default: false)
  65376. */
  65377. this.alwaysForcePOT = false;
  65378. /**
  65379. * Number of sample textures (default: 1)
  65380. */
  65381. this.samples = 1;
  65382. /**
  65383. * Modify the scale of the post process to be the same as the viewport (default: false)
  65384. */
  65385. this.adaptScaleToCurrentViewport = false;
  65386. this._reusable = false;
  65387. /**
  65388. * Smart array of input and output textures for the post process.
  65389. */
  65390. this._textures = new BABYLON.SmartArray(2);
  65391. /**
  65392. * The index in _textures that corresponds to the output texture.
  65393. */
  65394. this._currentRenderTextureInd = 0;
  65395. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65396. this._texelSize = BABYLON.Vector2.Zero();
  65397. // Events
  65398. /**
  65399. * An event triggered when the postprocess is activated.
  65400. */
  65401. this.onActivateObservable = new BABYLON.Observable();
  65402. /**
  65403. * An event triggered when the postprocess changes its size.
  65404. */
  65405. this.onSizeChangedObservable = new BABYLON.Observable();
  65406. /**
  65407. * An event triggered when the postprocess applies its effect.
  65408. */
  65409. this.onApplyObservable = new BABYLON.Observable();
  65410. /**
  65411. * An event triggered before rendering the postprocess
  65412. */
  65413. this.onBeforeRenderObservable = new BABYLON.Observable();
  65414. /**
  65415. * An event triggered after rendering the postprocess
  65416. */
  65417. this.onAfterRenderObservable = new BABYLON.Observable();
  65418. if (camera != null) {
  65419. this._camera = camera;
  65420. this._scene = camera.getScene();
  65421. camera.attachPostProcess(this);
  65422. this._engine = this._scene.getEngine();
  65423. this._scene.postProcesses.push(this);
  65424. }
  65425. else if (engine) {
  65426. this._engine = engine;
  65427. this._engine.postProcesses.push(this);
  65428. }
  65429. this._options = options;
  65430. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65431. this._reusable = reusable || false;
  65432. this._textureType = textureType;
  65433. this._samplers = samplers || [];
  65434. this._samplers.push("textureSampler");
  65435. this._fragmentUrl = fragmentUrl;
  65436. this._vertexUrl = vertexUrl;
  65437. this._parameters = parameters || [];
  65438. this._parameters.push("scale");
  65439. this._indexParameters = indexParameters;
  65440. if (!blockCompilation) {
  65441. this.updateEffect(defines);
  65442. }
  65443. }
  65444. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65445. /**
  65446. * A function that is added to the onActivateObservable
  65447. */
  65448. set: function (callback) {
  65449. if (this._onActivateObserver) {
  65450. this.onActivateObservable.remove(this._onActivateObserver);
  65451. }
  65452. if (callback) {
  65453. this._onActivateObserver = this.onActivateObservable.add(callback);
  65454. }
  65455. },
  65456. enumerable: true,
  65457. configurable: true
  65458. });
  65459. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65460. /**
  65461. * A function that is added to the onSizeChangedObservable
  65462. */
  65463. set: function (callback) {
  65464. if (this._onSizeChangedObserver) {
  65465. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65466. }
  65467. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65468. },
  65469. enumerable: true,
  65470. configurable: true
  65471. });
  65472. Object.defineProperty(PostProcess.prototype, "onApply", {
  65473. /**
  65474. * A function that is added to the onApplyObservable
  65475. */
  65476. set: function (callback) {
  65477. if (this._onApplyObserver) {
  65478. this.onApplyObservable.remove(this._onApplyObserver);
  65479. }
  65480. this._onApplyObserver = this.onApplyObservable.add(callback);
  65481. },
  65482. enumerable: true,
  65483. configurable: true
  65484. });
  65485. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65486. /**
  65487. * A function that is added to the onBeforeRenderObservable
  65488. */
  65489. set: function (callback) {
  65490. if (this._onBeforeRenderObserver) {
  65491. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65492. }
  65493. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65494. },
  65495. enumerable: true,
  65496. configurable: true
  65497. });
  65498. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65499. /**
  65500. * A function that is added to the onAfterRenderObservable
  65501. */
  65502. set: function (callback) {
  65503. if (this._onAfterRenderObserver) {
  65504. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65505. }
  65506. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65507. },
  65508. enumerable: true,
  65509. configurable: true
  65510. });
  65511. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65512. /**
  65513. * The input texture for this post process and the output texture of the previous post process. When added to a pipeline the previous post process will
  65514. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65515. */
  65516. get: function () {
  65517. return this._textures.data[this._currentRenderTextureInd];
  65518. },
  65519. set: function (value) {
  65520. this._forcedOutputTexture = value;
  65521. },
  65522. enumerable: true,
  65523. configurable: true
  65524. });
  65525. /**
  65526. * Gets the camera which post process is applied to.
  65527. * @returns The camera the post process is applied to.
  65528. */
  65529. PostProcess.prototype.getCamera = function () {
  65530. return this._camera;
  65531. };
  65532. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65533. /**
  65534. * Gets the texel size of the postprocess.
  65535. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65536. */
  65537. get: function () {
  65538. if (this._shareOutputWithPostProcess) {
  65539. return this._shareOutputWithPostProcess.texelSize;
  65540. }
  65541. if (this._forcedOutputTexture) {
  65542. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65543. }
  65544. return this._texelSize;
  65545. },
  65546. enumerable: true,
  65547. configurable: true
  65548. });
  65549. /**
  65550. * Gets the engine which this post process belongs to.
  65551. * @returns The engine the post process was enabled with.
  65552. */
  65553. PostProcess.prototype.getEngine = function () {
  65554. return this._engine;
  65555. };
  65556. /**
  65557. * The effect that is created when initializing the post process.
  65558. * @returns The created effect corrisponding the the postprocess.
  65559. */
  65560. PostProcess.prototype.getEffect = function () {
  65561. return this._effect;
  65562. };
  65563. /**
  65564. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65565. * @param postProcess The post process to share the output with.
  65566. * @returns This post process.
  65567. */
  65568. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65569. this._disposeTextures();
  65570. this._shareOutputWithPostProcess = postProcess;
  65571. return this;
  65572. };
  65573. /**
  65574. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65575. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65576. */
  65577. PostProcess.prototype.useOwnOutput = function () {
  65578. if (this._textures.length == 0) {
  65579. this._textures = new BABYLON.SmartArray(2);
  65580. }
  65581. this._shareOutputWithPostProcess = null;
  65582. };
  65583. /**
  65584. * Updates the effect with the current post process compile time values and recompiles the shader.
  65585. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65586. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65587. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65588. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  65589. * @param onCompiled Called when the shader has been compiled.
  65590. * @param onError Called if there is an error when compiling a shader.
  65591. */
  65592. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65593. if (defines === void 0) { defines = null; }
  65594. if (uniforms === void 0) { uniforms = null; }
  65595. if (samplers === void 0) { samplers = null; }
  65596. this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl }, ["position"], uniforms || this._parameters, samplers || this._samplers, defines !== null ? defines : "", undefined, onCompiled, onError, indexParameters || this._indexParameters);
  65597. };
  65598. /**
  65599. * The post process is reusable if it can be used multiple times within one frame.
  65600. * @returns If the post process is reusable
  65601. */
  65602. PostProcess.prototype.isReusable = function () {
  65603. return this._reusable;
  65604. };
  65605. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65606. PostProcess.prototype.markTextureDirty = function () {
  65607. this.width = -1;
  65608. };
  65609. /**
  65610. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65611. * When this post process is used in a pipeline, this is call will bind the input texture of this post process to the output of the previous.
  65612. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65613. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65614. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65615. * @returns The target texture that was bound to be written to.
  65616. */
  65617. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65618. var _this = this;
  65619. if (sourceTexture === void 0) { sourceTexture = null; }
  65620. camera = camera || this._camera;
  65621. var scene = camera.getScene();
  65622. var engine = scene.getEngine();
  65623. var maxSize = engine.getCaps().maxTextureSize;
  65624. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65625. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65626. // If rendering to a webvr camera's left or right eye only half the width should be used to avoid resize when rendered to screen
  65627. var webVRCamera = camera.parent;
  65628. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65629. requiredWidth /= 2;
  65630. }
  65631. var desiredWidth = (this._options.width || requiredWidth);
  65632. var desiredHeight = this._options.height || requiredHeight;
  65633. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65634. if (this.adaptScaleToCurrentViewport) {
  65635. var currentViewport = engine.currentViewport;
  65636. if (currentViewport) {
  65637. desiredWidth *= currentViewport.width;
  65638. desiredHeight *= currentViewport.height;
  65639. }
  65640. }
  65641. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65642. if (!this._options.width) {
  65643. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65644. }
  65645. if (!this._options.height) {
  65646. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65647. }
  65648. }
  65649. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65650. if (this._textures.length > 0) {
  65651. for (var i = 0; i < this._textures.length; i++) {
  65652. this._engine._releaseTexture(this._textures.data[i]);
  65653. }
  65654. this._textures.reset();
  65655. }
  65656. this.width = desiredWidth;
  65657. this.height = desiredHeight;
  65658. var textureSize = { width: this.width, height: this.height };
  65659. var textureOptions = {
  65660. generateMipMaps: false,
  65661. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65662. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65663. samplingMode: this.renderTargetSamplingMode,
  65664. type: this._textureType
  65665. };
  65666. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65667. if (this._reusable) {
  65668. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65669. }
  65670. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65671. this.onSizeChangedObservable.notifyObservers(this);
  65672. }
  65673. this._textures.forEach(function (texture) {
  65674. if (texture.samples !== _this.samples) {
  65675. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65676. }
  65677. });
  65678. }
  65679. var target;
  65680. if (this._shareOutputWithPostProcess) {
  65681. target = this._shareOutputWithPostProcess.inputTexture;
  65682. }
  65683. else if (this._forcedOutputTexture) {
  65684. target = this._forcedOutputTexture;
  65685. this.width = this._forcedOutputTexture.width;
  65686. this.height = this._forcedOutputTexture.height;
  65687. }
  65688. else {
  65689. target = this.inputTexture;
  65690. }
  65691. // Bind the input of this post process to be used as the output of the previous post process.
  65692. if (this.enablePixelPerfectMode) {
  65693. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65694. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65695. }
  65696. else {
  65697. this._scaleRatio.copyFromFloats(1, 1);
  65698. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65699. }
  65700. this.onActivateObservable.notifyObservers(camera);
  65701. // Clear
  65702. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65703. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65704. }
  65705. if (this._reusable) {
  65706. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65707. }
  65708. return target;
  65709. };
  65710. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65711. /**
  65712. * If the post process is supported.
  65713. */
  65714. get: function () {
  65715. return this._effect.isSupported;
  65716. },
  65717. enumerable: true,
  65718. configurable: true
  65719. });
  65720. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65721. /**
  65722. * The aspect ratio of the output texture.
  65723. */
  65724. get: function () {
  65725. if (this._shareOutputWithPostProcess) {
  65726. return this._shareOutputWithPostProcess.aspectRatio;
  65727. }
  65728. if (this._forcedOutputTexture) {
  65729. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65730. }
  65731. return this.width / this.height;
  65732. },
  65733. enumerable: true,
  65734. configurable: true
  65735. });
  65736. /**
  65737. * Get a value indicating if the post-process is ready to be used
  65738. * @returns true if the post-process is ready (shader is compiled)
  65739. */
  65740. PostProcess.prototype.isReady = function () {
  65741. return this._effect && this._effect.isReady();
  65742. };
  65743. /**
  65744. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65745. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65746. */
  65747. PostProcess.prototype.apply = function () {
  65748. // Check
  65749. if (!this._effect || !this._effect.isReady())
  65750. return null;
  65751. // States
  65752. this._engine.enableEffect(this._effect);
  65753. this._engine.setState(false);
  65754. this._engine.setDepthBuffer(false);
  65755. this._engine.setDepthWrite(false);
  65756. // Alpha
  65757. this._engine.setAlphaMode(this.alphaMode);
  65758. if (this.alphaConstants) {
  65759. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65760. }
  65761. // Bind the output texture of the preivous post process as the input to this post process.
  65762. var source;
  65763. if (this._shareOutputWithPostProcess) {
  65764. source = this._shareOutputWithPostProcess.inputTexture;
  65765. }
  65766. else if (this._forcedOutputTexture) {
  65767. source = this._forcedOutputTexture;
  65768. }
  65769. else {
  65770. source = this.inputTexture;
  65771. }
  65772. this._effect._bindTexture("textureSampler", source);
  65773. // Parameters
  65774. this._effect.setVector2("scale", this._scaleRatio);
  65775. this.onApplyObservable.notifyObservers(this._effect);
  65776. return this._effect;
  65777. };
  65778. PostProcess.prototype._disposeTextures = function () {
  65779. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65780. return;
  65781. }
  65782. if (this._textures.length > 0) {
  65783. for (var i = 0; i < this._textures.length; i++) {
  65784. this._engine._releaseTexture(this._textures.data[i]);
  65785. }
  65786. }
  65787. this._textures.dispose();
  65788. };
  65789. /**
  65790. * Disposes the post process.
  65791. * @param camera The camera to dispose the post process on.
  65792. */
  65793. PostProcess.prototype.dispose = function (camera) {
  65794. camera = camera || this._camera;
  65795. this._disposeTextures();
  65796. if (this._scene) {
  65797. var index_1 = this._scene.postProcesses.indexOf(this);
  65798. if (index_1 !== -1) {
  65799. this._scene.postProcesses.splice(index_1, 1);
  65800. }
  65801. }
  65802. else {
  65803. var index_2 = this._engine.postProcesses.indexOf(this);
  65804. if (index_2 !== -1) {
  65805. this._engine.postProcesses.splice(index_2, 1);
  65806. }
  65807. }
  65808. if (!camera) {
  65809. return;
  65810. }
  65811. camera.detachPostProcess(this);
  65812. var index = camera._postProcesses.indexOf(this);
  65813. if (index === 0 && camera._postProcesses.length > 0) {
  65814. var firstPostProcess = this._camera._getFirstPostProcess();
  65815. if (firstPostProcess) {
  65816. firstPostProcess.markTextureDirty();
  65817. }
  65818. }
  65819. this.onActivateObservable.clear();
  65820. this.onAfterRenderObservable.clear();
  65821. this.onApplyObservable.clear();
  65822. this.onBeforeRenderObservable.clear();
  65823. this.onSizeChangedObservable.clear();
  65824. };
  65825. return PostProcess;
  65826. }());
  65827. BABYLON.PostProcess = PostProcess;
  65828. })(BABYLON || (BABYLON = {}));
  65829. //# sourceMappingURL=babylon.postProcess.js.map
  65830. var BABYLON;
  65831. (function (BABYLON) {
  65832. var PassPostProcess = /** @class */ (function (_super) {
  65833. __extends(PassPostProcess, _super);
  65834. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65835. if (camera === void 0) { camera = null; }
  65836. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65837. if (blockCompilation === void 0) { blockCompilation = false; }
  65838. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65839. }
  65840. return PassPostProcess;
  65841. }(BABYLON.PostProcess));
  65842. BABYLON.PassPostProcess = PassPostProcess;
  65843. })(BABYLON || (BABYLON = {}));
  65844. //# sourceMappingURL=babylon.passPostProcess.js.map
  65845. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65846. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65847. s = arguments[i];
  65848. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65849. t[p] = s[p];
  65850. }
  65851. return t;
  65852. };
  65853. var BABYLON;
  65854. (function (BABYLON) {
  65855. /**
  65856. * Default implementation IShadowGenerator.
  65857. * This is the main object responsible of generating shadows in the framework.
  65858. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65859. */
  65860. var ShadowGenerator = /** @class */ (function () {
  65861. /**
  65862. * Creates a ShadowGenerator object.
  65863. * A ShadowGenerator is the required tool to use the shadows.
  65864. * Each light casting shadows needs to use its own ShadowGenerator.
  65865. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65866. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65867. * @param light The light object generating the shadows.
  65868. * @param useFullFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.
  65869. */
  65870. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65871. this._bias = 0.00005;
  65872. this._normalBias = 0;
  65873. this._blurBoxOffset = 1;
  65874. this._blurScale = 2;
  65875. this._blurKernel = 1;
  65876. this._useKernelBlur = false;
  65877. this._filter = ShadowGenerator.FILTER_NONE;
  65878. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65879. this._contactHardeningLightSizeUVRatio = 0.1;
  65880. this._darkness = 0;
  65881. this._transparencyShadow = false;
  65882. /**
  65883. * Controls the extent to which the shadows fade out at the edge of the frustum
  65884. * Used only by directionals and spots
  65885. */
  65886. this.frustumEdgeFalloff = 0;
  65887. /**
  65888. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65889. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65890. * It might on the other hand introduce peter panning.
  65891. */
  65892. this.forceBackFacesOnly = false;
  65893. this._lightDirection = BABYLON.Vector3.Zero();
  65894. this._viewMatrix = BABYLON.Matrix.Zero();
  65895. this._projectionMatrix = BABYLON.Matrix.Zero();
  65896. this._transformMatrix = BABYLON.Matrix.Zero();
  65897. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65898. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65899. this._currentFaceIndex = 0;
  65900. this._currentFaceIndexCache = 0;
  65901. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65902. this._mapSize = mapSize;
  65903. this._light = light;
  65904. this._scene = light.getScene();
  65905. light._shadowGenerator = this;
  65906. // Texture type fallback from float to int if not supported.
  65907. var caps = this._scene.getEngine().getCaps();
  65908. if (!useFullFloatFirst) {
  65909. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65910. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65911. }
  65912. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65913. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65914. }
  65915. else {
  65916. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65917. }
  65918. }
  65919. else {
  65920. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65921. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65922. }
  65923. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65924. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65925. }
  65926. else {
  65927. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65928. }
  65929. }
  65930. this._initializeGenerator();
  65931. this._applyFilterValues();
  65932. }
  65933. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65934. /**
  65935. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65936. */
  65937. get: function () {
  65938. return this._bias;
  65939. },
  65940. /**
  65941. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65942. */
  65943. set: function (bias) {
  65944. this._bias = bias;
  65945. },
  65946. enumerable: true,
  65947. configurable: true
  65948. });
  65949. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65950. /**
  65951. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65952. */
  65953. get: function () {
  65954. return this._normalBias;
  65955. },
  65956. /**
  65957. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65958. */
  65959. set: function (normalBias) {
  65960. this._normalBias = normalBias;
  65961. },
  65962. enumerable: true,
  65963. configurable: true
  65964. });
  65965. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65966. /**
  65967. * Gets the blur box offset: offset applied during the blur pass.
  65968. * Only usefull if useKernelBlur = false
  65969. */
  65970. get: function () {
  65971. return this._blurBoxOffset;
  65972. },
  65973. /**
  65974. * Sets the blur box offset: offset applied during the blur pass.
  65975. * Only usefull if useKernelBlur = false
  65976. */
  65977. set: function (value) {
  65978. if (this._blurBoxOffset === value) {
  65979. return;
  65980. }
  65981. this._blurBoxOffset = value;
  65982. this._disposeBlurPostProcesses();
  65983. },
  65984. enumerable: true,
  65985. configurable: true
  65986. });
  65987. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65988. /**
  65989. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65990. * 2 means half of the size.
  65991. */
  65992. get: function () {
  65993. return this._blurScale;
  65994. },
  65995. /**
  65996. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65997. * 2 means half of the size.
  65998. */
  65999. set: function (value) {
  66000. if (this._blurScale === value) {
  66001. return;
  66002. }
  66003. this._blurScale = value;
  66004. this._disposeBlurPostProcesses();
  66005. },
  66006. enumerable: true,
  66007. configurable: true
  66008. });
  66009. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  66010. /**
  66011. * Gets the blur kernel: kernel size of the blur pass.
  66012. * Only usefull if useKernelBlur = true
  66013. */
  66014. get: function () {
  66015. return this._blurKernel;
  66016. },
  66017. /**
  66018. * Sets the blur kernel: kernel size of the blur pass.
  66019. * Only usefull if useKernelBlur = true
  66020. */
  66021. set: function (value) {
  66022. if (this._blurKernel === value) {
  66023. return;
  66024. }
  66025. this._blurKernel = value;
  66026. this._disposeBlurPostProcesses();
  66027. },
  66028. enumerable: true,
  66029. configurable: true
  66030. });
  66031. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  66032. /**
  66033. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  66034. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66035. */
  66036. get: function () {
  66037. return this._useKernelBlur;
  66038. },
  66039. /**
  66040. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  66041. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66042. */
  66043. set: function (value) {
  66044. if (this._useKernelBlur === value) {
  66045. return;
  66046. }
  66047. this._useKernelBlur = value;
  66048. this._disposeBlurPostProcesses();
  66049. },
  66050. enumerable: true,
  66051. configurable: true
  66052. });
  66053. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  66054. /**
  66055. * Gets the depth scale used in ESM mode.
  66056. */
  66057. get: function () {
  66058. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  66059. },
  66060. /**
  66061. * Sets the depth scale used in ESM mode.
  66062. * This can override the scale stored on the light.
  66063. */
  66064. set: function (value) {
  66065. this._depthScale = value;
  66066. },
  66067. enumerable: true,
  66068. configurable: true
  66069. });
  66070. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  66071. /**
  66072. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  66073. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66074. */
  66075. get: function () {
  66076. return this._filter;
  66077. },
  66078. /**
  66079. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  66080. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66081. */
  66082. set: function (value) {
  66083. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  66084. if (this._light.needCube()) {
  66085. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66086. this.useExponentialShadowMap = true;
  66087. return;
  66088. }
  66089. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66090. this.useCloseExponentialShadowMap = true;
  66091. return;
  66092. }
  66093. // PCF on cubemap would also be expensive
  66094. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66095. this.usePoissonSampling = true;
  66096. return;
  66097. }
  66098. }
  66099. // Weblg1 fallback for PCF.
  66100. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66101. if (this._scene.getEngine().webGLVersion === 1) {
  66102. this.usePoissonSampling = true;
  66103. return;
  66104. }
  66105. }
  66106. if (this._filter === value) {
  66107. return;
  66108. }
  66109. this._filter = value;
  66110. this._disposeBlurPostProcesses();
  66111. this._applyFilterValues();
  66112. this._light._markMeshesAsLightDirty();
  66113. },
  66114. enumerable: true,
  66115. configurable: true
  66116. });
  66117. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  66118. /**
  66119. * Gets if the current filter is set to Poisson Sampling.
  66120. */
  66121. get: function () {
  66122. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  66123. },
  66124. /**
  66125. * Sets the current filter to Poisson Sampling.
  66126. */
  66127. set: function (value) {
  66128. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  66129. return;
  66130. }
  66131. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  66132. },
  66133. enumerable: true,
  66134. configurable: true
  66135. });
  66136. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  66137. /**
  66138. * Gets if the current filter is set to VSM.
  66139. * DEPRECATED. Should use useExponentialShadowMap instead.
  66140. */
  66141. get: function () {
  66142. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66143. return this.useExponentialShadowMap;
  66144. },
  66145. /**
  66146. * Sets the current filter is to VSM.
  66147. * DEPRECATED. Should use useExponentialShadowMap instead.
  66148. */
  66149. set: function (value) {
  66150. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66151. this.useExponentialShadowMap = value;
  66152. },
  66153. enumerable: true,
  66154. configurable: true
  66155. });
  66156. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  66157. /**
  66158. * Gets if the current filter is set to blurred VSM.
  66159. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66160. */
  66161. get: function () {
  66162. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66163. return this.useBlurExponentialShadowMap;
  66164. },
  66165. /**
  66166. * Sets the current filter is to blurred VSM.
  66167. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66168. */
  66169. set: function (value) {
  66170. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66171. this.useBlurExponentialShadowMap = value;
  66172. },
  66173. enumerable: true,
  66174. configurable: true
  66175. });
  66176. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  66177. /**
  66178. * Gets if the current filter is set to ESM.
  66179. */
  66180. get: function () {
  66181. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  66182. },
  66183. /**
  66184. * Sets the current filter is to ESM.
  66185. */
  66186. set: function (value) {
  66187. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  66188. return;
  66189. }
  66190. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66191. },
  66192. enumerable: true,
  66193. configurable: true
  66194. });
  66195. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  66196. /**
  66197. * Gets if the current filter is set to filtered ESM.
  66198. */
  66199. get: function () {
  66200. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  66201. },
  66202. /**
  66203. * Gets if the current filter is set to filtered ESM.
  66204. */
  66205. set: function (value) {
  66206. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66207. return;
  66208. }
  66209. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66210. },
  66211. enumerable: true,
  66212. configurable: true
  66213. });
  66214. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  66215. /**
  66216. * Gets if the current filter is set to "close ESM" (using the inverse of the
  66217. * exponential to prevent steep falloff artifacts).
  66218. */
  66219. get: function () {
  66220. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  66221. },
  66222. /**
  66223. * Sets the current filter to "close ESM" (using the inverse of the
  66224. * exponential to prevent steep falloff artifacts).
  66225. */
  66226. set: function (value) {
  66227. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  66228. return;
  66229. }
  66230. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66231. },
  66232. enumerable: true,
  66233. configurable: true
  66234. });
  66235. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  66236. /**
  66237. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  66238. * exponential to prevent steep falloff artifacts).
  66239. */
  66240. get: function () {
  66241. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  66242. },
  66243. /**
  66244. * Sets the current filter to filtered "close ESM" (using the inverse of the
  66245. * exponential to prevent steep falloff artifacts).
  66246. */
  66247. set: function (value) {
  66248. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66249. return;
  66250. }
  66251. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66252. },
  66253. enumerable: true,
  66254. configurable: true
  66255. });
  66256. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  66257. /**
  66258. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  66259. */
  66260. get: function () {
  66261. return this.filter === ShadowGenerator.FILTER_PCF;
  66262. },
  66263. /**
  66264. * Sets the current filter to "PCF" (percentage closer filtering).
  66265. */
  66266. set: function (value) {
  66267. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  66268. return;
  66269. }
  66270. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66271. },
  66272. enumerable: true,
  66273. configurable: true
  66274. });
  66275. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66276. /**
  66277. * Gets the PCF or PCSS Quality.
  66278. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66279. */
  66280. get: function () {
  66281. return this._filteringQuality;
  66282. },
  66283. /**
  66284. * Sets the PCF or PCSS Quality.
  66285. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66286. */
  66287. set: function (filteringQuality) {
  66288. this._filteringQuality = filteringQuality;
  66289. },
  66290. enumerable: true,
  66291. configurable: true
  66292. });
  66293. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66294. /**
  66295. * Gets if the current filter is set to "PCSS" (contact hardening).
  66296. */
  66297. get: function () {
  66298. return this.filter === ShadowGenerator.FILTER_PCSS;
  66299. },
  66300. /**
  66301. * Sets the current filter to "PCSS" (contact hardening).
  66302. */
  66303. set: function (value) {
  66304. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66305. return;
  66306. }
  66307. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66308. },
  66309. enumerable: true,
  66310. configurable: true
  66311. });
  66312. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66313. /**
  66314. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66315. * Using a ratio helps keeping shape stability independently of the map size.
  66316. *
  66317. * It does not account for the light projection as it was having too much
  66318. * instability during the light setup or during light position changes.
  66319. *
  66320. * Only valid if useContactHardeningShadow is true.
  66321. */
  66322. get: function () {
  66323. return this._contactHardeningLightSizeUVRatio;
  66324. },
  66325. /**
  66326. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66327. * Using a ratio helps keeping shape stability independently of the map size.
  66328. *
  66329. * It does not account for the light projection as it was having too much
  66330. * instability during the light setup or during light position changes.
  66331. *
  66332. * Only valid if useContactHardeningShadow is true.
  66333. */
  66334. set: function (contactHardeningLightSizeUVRatio) {
  66335. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66336. },
  66337. enumerable: true,
  66338. configurable: true
  66339. });
  66340. /**
  66341. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66342. * 0 means strongest and 1 would means no shadow.
  66343. * @returns the darkness.
  66344. */
  66345. ShadowGenerator.prototype.getDarkness = function () {
  66346. return this._darkness;
  66347. };
  66348. /**
  66349. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66350. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66351. * @returns the shadow generator allowing fluent coding.
  66352. */
  66353. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66354. if (darkness >= 1.0)
  66355. this._darkness = 1.0;
  66356. else if (darkness <= 0.0)
  66357. this._darkness = 0.0;
  66358. else
  66359. this._darkness = darkness;
  66360. return this;
  66361. };
  66362. /**
  66363. * Sets the ability to have transparent shadow (boolean).
  66364. * @param transparent True if transparent else False
  66365. * @returns the shadow generator allowing fluent coding
  66366. */
  66367. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66368. this._transparencyShadow = transparent;
  66369. return this;
  66370. };
  66371. /**
  66372. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66373. * @returns The render target texture if present otherwise, null
  66374. */
  66375. ShadowGenerator.prototype.getShadowMap = function () {
  66376. return this._shadowMap;
  66377. };
  66378. /**
  66379. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66380. * @returns The render target texture if the shadow map is present otherwise, null
  66381. */
  66382. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66383. if (this._shadowMap2) {
  66384. return this._shadowMap2;
  66385. }
  66386. return this._shadowMap;
  66387. };
  66388. /**
  66389. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66390. * @param mesh Mesh to add
  66391. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66392. * @returns the Shadow Generator itself
  66393. */
  66394. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66395. if (includeDescendants === void 0) { includeDescendants = true; }
  66396. if (!this._shadowMap) {
  66397. return this;
  66398. }
  66399. if (!this._shadowMap.renderList) {
  66400. this._shadowMap.renderList = [];
  66401. }
  66402. this._shadowMap.renderList.push(mesh);
  66403. if (includeDescendants) {
  66404. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66405. }
  66406. return this;
  66407. var _a;
  66408. };
  66409. /**
  66410. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66411. * @param mesh Mesh to remove
  66412. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66413. * @returns the Shadow Generator itself
  66414. */
  66415. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66416. if (includeDescendants === void 0) { includeDescendants = true; }
  66417. if (!this._shadowMap || !this._shadowMap.renderList) {
  66418. return this;
  66419. }
  66420. var index = this._shadowMap.renderList.indexOf(mesh);
  66421. if (index !== -1) {
  66422. this._shadowMap.renderList.splice(index, 1);
  66423. }
  66424. if (includeDescendants) {
  66425. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66426. var child = _a[_i];
  66427. this.removeShadowCaster(child);
  66428. }
  66429. }
  66430. return this;
  66431. };
  66432. /**
  66433. * Returns the associated light object.
  66434. * @returns the light generating the shadow
  66435. */
  66436. ShadowGenerator.prototype.getLight = function () {
  66437. return this._light;
  66438. };
  66439. ShadowGenerator.prototype._initializeGenerator = function () {
  66440. this._light._markMeshesAsLightDirty();
  66441. this._initializeShadowMap();
  66442. };
  66443. ShadowGenerator.prototype._initializeShadowMap = function () {
  66444. var _this = this;
  66445. // Render target
  66446. var engine = this._scene.getEngine();
  66447. if (engine.webGLVersion > 1) {
  66448. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66449. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66450. }
  66451. else {
  66452. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66453. }
  66454. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66455. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66456. this._shadowMap.anisotropicFilteringLevel = 1;
  66457. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66458. this._shadowMap.renderParticles = false;
  66459. this._shadowMap.ignoreCameraViewport = true;
  66460. // Record Face Index before render.
  66461. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66462. _this._currentFaceIndex = faceIndex;
  66463. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66464. engine.setColorWrite(false);
  66465. }
  66466. });
  66467. // Custom render function.
  66468. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66469. // Blur if required afer render.
  66470. this._shadowMap.onAfterUnbindObservable.add(function () {
  66471. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66472. engine.setColorWrite(true);
  66473. }
  66474. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66475. return;
  66476. }
  66477. var shadowMap = _this.getShadowMapForRendering();
  66478. if (shadowMap) {
  66479. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66480. }
  66481. });
  66482. // Clear according to the chosen filter.
  66483. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66484. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66485. this._shadowMap.onClearObservable.add(function (engine) {
  66486. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66487. engine.clear(clearOne, false, true, false);
  66488. }
  66489. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66490. engine.clear(clearZero, true, true, false);
  66491. }
  66492. else {
  66493. engine.clear(clearOne, true, true, false);
  66494. }
  66495. });
  66496. };
  66497. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66498. var _this = this;
  66499. var engine = this._scene.getEngine();
  66500. var targetSize = this._mapSize / this.blurScale;
  66501. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66502. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66503. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66504. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66505. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66506. }
  66507. if (this.useKernelBlur) {
  66508. this._kernelBlurXPostprocess = new BABYLON.BlurPostProcess(this._light.name + "KernelBlurX", new BABYLON.Vector2(1, 0), this.blurKernel, 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
  66509. this._kernelBlurXPostprocess.width = targetSize;
  66510. this._kernelBlurXPostprocess.height = targetSize;
  66511. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66512. effect.setTexture("textureSampler", _this._shadowMap);
  66513. });
  66514. this._kernelBlurYPostprocess = new BABYLON.BlurPostProcess(this._light.name + "KernelBlurY", new BABYLON.Vector2(0, 1), this.blurKernel, 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
  66515. this._kernelBlurXPostprocess.autoClear = false;
  66516. this._kernelBlurYPostprocess.autoClear = false;
  66517. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66518. this._kernelBlurXPostprocess.packedFloat = true;
  66519. this._kernelBlurYPostprocess.packedFloat = true;
  66520. }
  66521. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66522. }
  66523. else {
  66524. this._boxBlurPostprocess = new BABYLON.PostProcess(this._light.name + "DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, "#define OFFSET " + this._blurBoxOffset, this._textureType);
  66525. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66526. effect.setFloat2("screenSize", targetSize, targetSize);
  66527. effect.setTexture("textureSampler", _this._shadowMap);
  66528. });
  66529. this._boxBlurPostprocess.autoClear = false;
  66530. this._blurPostProcesses = [this._boxBlurPostprocess];
  66531. }
  66532. };
  66533. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66534. var index;
  66535. var engine = this._scene.getEngine();
  66536. if (depthOnlySubMeshes.length) {
  66537. engine.setColorWrite(false);
  66538. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66539. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66540. }
  66541. engine.setColorWrite(true);
  66542. }
  66543. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66544. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66545. }
  66546. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66547. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66548. }
  66549. if (this._transparencyShadow) {
  66550. for (index = 0; index < transparentSubMeshes.length; index++) {
  66551. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66552. }
  66553. }
  66554. };
  66555. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66556. var _this = this;
  66557. var mesh = subMesh.getRenderingMesh();
  66558. var scene = this._scene;
  66559. var engine = scene.getEngine();
  66560. var material = subMesh.getMaterial();
  66561. if (!material) {
  66562. return;
  66563. }
  66564. // Culling
  66565. engine.setState(material.backFaceCulling);
  66566. // Managing instances
  66567. var batch = mesh._getInstancesRenderList(subMesh._id);
  66568. if (batch.mustReturn) {
  66569. return;
  66570. }
  66571. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66572. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66573. engine.enableEffect(this._effect);
  66574. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66575. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66576. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66577. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66578. this._effect.setVector3("lightData", this._cachedDirection);
  66579. }
  66580. else {
  66581. this._effect.setVector3("lightData", this._cachedPosition);
  66582. }
  66583. if (scene.activeCamera) {
  66584. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66585. }
  66586. // Alpha test
  66587. if (material && material.needAlphaTesting()) {
  66588. var alphaTexture = material.getAlphaTestTexture();
  66589. if (alphaTexture) {
  66590. this._effect.setTexture("diffuseSampler", alphaTexture);
  66591. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66592. }
  66593. }
  66594. // Bones
  66595. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66596. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66597. }
  66598. // Morph targets
  66599. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66600. if (this.forceBackFacesOnly) {
  66601. engine.setState(true, 0, false, true);
  66602. }
  66603. // Draw
  66604. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66605. if (this.forceBackFacesOnly) {
  66606. engine.setState(true, 0, false, false);
  66607. }
  66608. }
  66609. else {
  66610. // Need to reset refresh rate of the shadowMap
  66611. if (this._shadowMap) {
  66612. this._shadowMap.resetRefreshCounter();
  66613. }
  66614. }
  66615. };
  66616. ShadowGenerator.prototype._applyFilterValues = function () {
  66617. if (!this._shadowMap) {
  66618. return;
  66619. }
  66620. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66621. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66622. }
  66623. else {
  66624. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66625. }
  66626. };
  66627. /**
  66628. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66629. * @param onCompiled Callback triggered at the and of the effects compilation
  66630. * @param options Sets of optional options forcing the compilation with different modes
  66631. */
  66632. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66633. var _this = this;
  66634. var localOptions = __assign({ useInstances: false }, options);
  66635. var shadowMap = this.getShadowMap();
  66636. if (!shadowMap) {
  66637. if (onCompiled) {
  66638. onCompiled(this);
  66639. }
  66640. return;
  66641. }
  66642. var renderList = shadowMap.renderList;
  66643. if (!renderList) {
  66644. if (onCompiled) {
  66645. onCompiled(this);
  66646. }
  66647. return;
  66648. }
  66649. var subMeshes = new Array();
  66650. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66651. var mesh = renderList_1[_i];
  66652. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66653. }
  66654. if (subMeshes.length === 0) {
  66655. if (onCompiled) {
  66656. onCompiled(this);
  66657. }
  66658. return;
  66659. }
  66660. var currentIndex = 0;
  66661. var checkReady = function () {
  66662. if (!_this._scene || !_this._scene.getEngine()) {
  66663. return;
  66664. }
  66665. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66666. currentIndex++;
  66667. if (currentIndex >= subMeshes.length) {
  66668. if (onCompiled) {
  66669. onCompiled(_this);
  66670. }
  66671. return;
  66672. }
  66673. }
  66674. setTimeout(checkReady, 16);
  66675. };
  66676. checkReady();
  66677. };
  66678. /**
  66679. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66680. * @param options Sets of optional options forcing the compilation with different modes
  66681. * @returns A promise that resolves when the compilation completes
  66682. */
  66683. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66684. var _this = this;
  66685. return new Promise(function (resolve) {
  66686. _this.forceCompilation(function () {
  66687. resolve();
  66688. }, options);
  66689. });
  66690. };
  66691. /**
  66692. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66693. * @param subMesh The submesh we want to render in the shadow map
  66694. * @param useInstances Defines wether will draw in the map using instances
  66695. * @returns true if ready otherwise, false
  66696. */
  66697. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66698. var defines = [];
  66699. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66700. defines.push("#define FLOAT");
  66701. }
  66702. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66703. defines.push("#define ESM");
  66704. }
  66705. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66706. defines.push("#define DEPTHTEXTURE");
  66707. }
  66708. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66709. var mesh = subMesh.getMesh();
  66710. var material = subMesh.getMaterial();
  66711. // Normal bias.
  66712. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66713. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66714. defines.push("#define NORMAL");
  66715. if (mesh.nonUniformScaling) {
  66716. defines.push("#define NONUNIFORMSCALING");
  66717. }
  66718. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66719. defines.push("#define DIRECTIONINLIGHTDATA");
  66720. }
  66721. }
  66722. // Alpha test
  66723. if (material && material.needAlphaTesting()) {
  66724. var alphaTexture = material.getAlphaTestTexture();
  66725. if (alphaTexture) {
  66726. defines.push("#define ALPHATEST");
  66727. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66728. attribs.push(BABYLON.VertexBuffer.UVKind);
  66729. defines.push("#define UV1");
  66730. }
  66731. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66732. if (alphaTexture.coordinatesIndex === 1) {
  66733. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66734. defines.push("#define UV2");
  66735. }
  66736. }
  66737. }
  66738. }
  66739. // Bones
  66740. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66741. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66742. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66743. if (mesh.numBoneInfluencers > 4) {
  66744. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66745. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66746. }
  66747. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66748. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66749. }
  66750. else {
  66751. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66752. }
  66753. // Morph targets
  66754. var manager = mesh.morphTargetManager;
  66755. var morphInfluencers = 0;
  66756. if (manager) {
  66757. if (manager.numInfluencers > 0) {
  66758. defines.push("#define MORPHTARGETS");
  66759. morphInfluencers = manager.numInfluencers;
  66760. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66761. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66762. }
  66763. }
  66764. // Instances
  66765. if (useInstances) {
  66766. defines.push("#define INSTANCES");
  66767. attribs.push("world0");
  66768. attribs.push("world1");
  66769. attribs.push("world2");
  66770. attribs.push("world3");
  66771. }
  66772. // Get correct effect
  66773. var join = defines.join("\n");
  66774. if (this._cachedDefines !== join) {
  66775. this._cachedDefines = join;
  66776. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66777. }
  66778. if (!this._effect.isReady()) {
  66779. return false;
  66780. }
  66781. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66782. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66783. this._initializeBlurRTTAndPostProcesses();
  66784. }
  66785. }
  66786. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66787. return false;
  66788. }
  66789. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66790. return false;
  66791. }
  66792. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66793. return false;
  66794. }
  66795. return true;
  66796. };
  66797. /**
  66798. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66799. * @param defines Defines of the material we want to update
  66800. * @param lightIndex Index of the light in the enabled light list of the material
  66801. */
  66802. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66803. var scene = this._scene;
  66804. var light = this._light;
  66805. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66806. return;
  66807. }
  66808. defines["SHADOW" + lightIndex] = true;
  66809. if (this.useContactHardeningShadow) {
  66810. defines["SHADOWPCSS" + lightIndex] = true;
  66811. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66812. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66813. }
  66814. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66815. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66816. }
  66817. // else default to high.
  66818. }
  66819. if (this.usePercentageCloserFiltering) {
  66820. defines["SHADOWPCF" + lightIndex] = true;
  66821. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66822. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66823. }
  66824. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66825. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66826. }
  66827. // else default to high.
  66828. }
  66829. else if (this.usePoissonSampling) {
  66830. defines["SHADOWPOISSON" + lightIndex] = true;
  66831. }
  66832. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66833. defines["SHADOWESM" + lightIndex] = true;
  66834. }
  66835. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66836. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66837. }
  66838. if (light.needCube()) {
  66839. defines["SHADOWCUBE" + lightIndex] = true;
  66840. }
  66841. };
  66842. /**
  66843. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66844. * defined in the generator but impacting the effect).
  66845. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66846. * @param effect The effect we are binfing the information for
  66847. */
  66848. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66849. var light = this._light;
  66850. var scene = this._scene;
  66851. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66852. return;
  66853. }
  66854. var camera = scene.activeCamera;
  66855. if (!camera) {
  66856. return;
  66857. }
  66858. var shadowMap = this.getShadowMap();
  66859. if (!shadowMap) {
  66860. return;
  66861. }
  66862. if (!light.needCube()) {
  66863. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66864. }
  66865. // Only PCF uses depth stencil texture.
  66866. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66867. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66868. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66869. }
  66870. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66871. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66872. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66873. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66874. }
  66875. else {
  66876. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66877. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66878. }
  66879. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66880. };
  66881. /**
  66882. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66883. * (eq to shadow prjection matrix * light transform matrix)
  66884. * @returns The transform matrix used to create the shadow map
  66885. */
  66886. ShadowGenerator.prototype.getTransformMatrix = function () {
  66887. var scene = this._scene;
  66888. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66889. return this._transformMatrix;
  66890. }
  66891. this._currentRenderID = scene.getRenderId();
  66892. this._currentFaceIndexCache = this._currentFaceIndex;
  66893. var lightPosition = this._light.position;
  66894. if (this._light.computeTransformedInformation()) {
  66895. lightPosition = this._light.transformedPosition;
  66896. }
  66897. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66898. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66899. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66900. }
  66901. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66902. this._cachedPosition.copyFrom(lightPosition);
  66903. this._cachedDirection.copyFrom(this._lightDirection);
  66904. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66905. var shadowMap = this.getShadowMap();
  66906. if (shadowMap) {
  66907. var renderList = shadowMap.renderList;
  66908. if (renderList) {
  66909. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66910. }
  66911. }
  66912. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66913. }
  66914. return this._transformMatrix;
  66915. };
  66916. /**
  66917. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66918. * Cube and 2D textures for instance.
  66919. */
  66920. ShadowGenerator.prototype.recreateShadowMap = function () {
  66921. var shadowMap = this._shadowMap;
  66922. if (!shadowMap) {
  66923. return;
  66924. }
  66925. // Track render list.
  66926. var renderList = shadowMap.renderList;
  66927. // Clean up existing data.
  66928. this._disposeRTTandPostProcesses();
  66929. // Reinitializes.
  66930. this._initializeGenerator();
  66931. // Reaffect the filter to ensure a correct fallback if necessary.
  66932. this.filter = this.filter;
  66933. // Reaffect the filter.
  66934. this._applyFilterValues();
  66935. // Reaffect Render List.
  66936. this._shadowMap.renderList = renderList;
  66937. };
  66938. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66939. if (this._shadowMap2) {
  66940. this._shadowMap2.dispose();
  66941. this._shadowMap2 = null;
  66942. }
  66943. if (this._boxBlurPostprocess) {
  66944. this._boxBlurPostprocess.dispose();
  66945. this._boxBlurPostprocess = null;
  66946. }
  66947. if (this._kernelBlurXPostprocess) {
  66948. this._kernelBlurXPostprocess.dispose();
  66949. this._kernelBlurXPostprocess = null;
  66950. }
  66951. if (this._kernelBlurYPostprocess) {
  66952. this._kernelBlurYPostprocess.dispose();
  66953. this._kernelBlurYPostprocess = null;
  66954. }
  66955. this._blurPostProcesses = [];
  66956. };
  66957. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66958. if (this._shadowMap) {
  66959. this._shadowMap.dispose();
  66960. this._shadowMap = null;
  66961. }
  66962. this._disposeBlurPostProcesses();
  66963. };
  66964. /**
  66965. * Disposes the ShadowGenerator.
  66966. * Returns nothing.
  66967. */
  66968. ShadowGenerator.prototype.dispose = function () {
  66969. this._disposeRTTandPostProcesses();
  66970. if (this._light) {
  66971. this._light._shadowGenerator = null;
  66972. this._light._markMeshesAsLightDirty();
  66973. }
  66974. };
  66975. /**
  66976. * Serializes the shadow generator setup to a json object.
  66977. * @returns The serialized JSON object
  66978. */
  66979. ShadowGenerator.prototype.serialize = function () {
  66980. var serializationObject = {};
  66981. var shadowMap = this.getShadowMap();
  66982. if (!shadowMap) {
  66983. return serializationObject;
  66984. }
  66985. serializationObject.lightId = this._light.id;
  66986. serializationObject.mapSize = shadowMap.getRenderSize();
  66987. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66988. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66989. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66990. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66991. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66992. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66993. serializationObject.depthScale = this.depthScale;
  66994. serializationObject.darkness = this.getDarkness();
  66995. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66996. serializationObject.blurKernel = this.blurKernel;
  66997. serializationObject.blurScale = this.blurScale;
  66998. serializationObject.useKernelBlur = this.useKernelBlur;
  66999. serializationObject.transparencyShadow = this._transparencyShadow;
  67000. serializationObject.bias = this.bias;
  67001. serializationObject.normalBias = this.normalBias;
  67002. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  67003. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  67004. serializationObject.filteringQuality = this.filteringQuality;
  67005. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  67006. serializationObject.renderList = [];
  67007. if (shadowMap.renderList) {
  67008. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  67009. var mesh = shadowMap.renderList[meshIndex];
  67010. serializationObject.renderList.push(mesh.id);
  67011. }
  67012. }
  67013. return serializationObject;
  67014. };
  67015. /**
  67016. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  67017. * @param parsedShadowGenerator The JSON object to parse
  67018. * @param scene The scene to create the shadow map for
  67019. * @returns The parsed shadow generator
  67020. */
  67021. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  67022. //casting to point light, as light is missing the position attr and typescript complains.
  67023. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  67024. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  67025. var shadowMap = shadowGenerator.getShadowMap();
  67026. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  67027. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  67028. meshes.forEach(function (mesh) {
  67029. if (!shadowMap) {
  67030. return;
  67031. }
  67032. if (!shadowMap.renderList) {
  67033. shadowMap.renderList = [];
  67034. }
  67035. shadowMap.renderList.push(mesh);
  67036. });
  67037. }
  67038. if (parsedShadowGenerator.usePoissonSampling) {
  67039. shadowGenerator.usePoissonSampling = true;
  67040. }
  67041. else if (parsedShadowGenerator.useExponentialShadowMap) {
  67042. shadowGenerator.useExponentialShadowMap = true;
  67043. }
  67044. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  67045. shadowGenerator.useBlurExponentialShadowMap = true;
  67046. }
  67047. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  67048. shadowGenerator.useCloseExponentialShadowMap = true;
  67049. }
  67050. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  67051. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  67052. }
  67053. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  67054. shadowGenerator.usePercentageCloserFiltering = true;
  67055. }
  67056. else if (parsedShadowGenerator.useContactHardeningShadow) {
  67057. shadowGenerator.useContactHardeningShadow = true;
  67058. }
  67059. if (parsedShadowGenerator.filteringQuality) {
  67060. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  67061. }
  67062. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  67063. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  67064. }
  67065. // Backward compat
  67066. else if (parsedShadowGenerator.useVarianceShadowMap) {
  67067. shadowGenerator.useExponentialShadowMap = true;
  67068. }
  67069. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  67070. shadowGenerator.useBlurExponentialShadowMap = true;
  67071. }
  67072. if (parsedShadowGenerator.depthScale) {
  67073. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  67074. }
  67075. if (parsedShadowGenerator.blurScale) {
  67076. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  67077. }
  67078. if (parsedShadowGenerator.blurBoxOffset) {
  67079. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  67080. }
  67081. if (parsedShadowGenerator.useKernelBlur) {
  67082. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  67083. }
  67084. if (parsedShadowGenerator.blurKernel) {
  67085. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  67086. }
  67087. if (parsedShadowGenerator.bias !== undefined) {
  67088. shadowGenerator.bias = parsedShadowGenerator.bias;
  67089. }
  67090. if (parsedShadowGenerator.normalBias !== undefined) {
  67091. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  67092. }
  67093. if (parsedShadowGenerator.darkness) {
  67094. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  67095. }
  67096. if (parsedShadowGenerator.transparencyShadow) {
  67097. shadowGenerator.setTransparencyShadow(true);
  67098. }
  67099. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  67100. return shadowGenerator;
  67101. };
  67102. /**
  67103. * Shadow generator mode None: no filtering applied.
  67104. */
  67105. ShadowGenerator.FILTER_NONE = 0;
  67106. /**
  67107. * Shadow generator mode ESM: Exponential Shadow Mapping.
  67108. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67109. */
  67110. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  67111. /**
  67112. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  67113. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  67114. */
  67115. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  67116. /**
  67117. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  67118. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67119. */
  67120. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  67121. /**
  67122. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  67123. * edge artifacts on steep falloff.
  67124. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67125. */
  67126. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  67127. /**
  67128. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  67129. * edge artifacts on steep falloff.
  67130. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67131. */
  67132. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  67133. /**
  67134. * Shadow generator mode PCF: Percentage Closer Filtering
  67135. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67136. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  67137. */
  67138. ShadowGenerator.FILTER_PCF = 6;
  67139. /**
  67140. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  67141. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67142. * Contact Hardening
  67143. */
  67144. ShadowGenerator.FILTER_PCSS = 7;
  67145. /**
  67146. * Reserved for PCF and PCSS
  67147. * Highest Quality.
  67148. *
  67149. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  67150. *
  67151. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  67152. */
  67153. ShadowGenerator.QUALITY_HIGH = 0;
  67154. /**
  67155. * Reserved for PCF and PCSS
  67156. * Good tradeoff for quality/perf cross devices
  67157. *
  67158. * Execute PCF on a 3*3 kernel.
  67159. *
  67160. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  67161. */
  67162. ShadowGenerator.QUALITY_MEDIUM = 1;
  67163. /**
  67164. * Reserved for PCF and PCSS
  67165. * The lowest quality but the fastest.
  67166. *
  67167. * Execute PCF on a 1*1 kernel.
  67168. *
  67169. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  67170. */
  67171. ShadowGenerator.QUALITY_LOW = 2;
  67172. return ShadowGenerator;
  67173. }());
  67174. BABYLON.ShadowGenerator = ShadowGenerator;
  67175. })(BABYLON || (BABYLON = {}));
  67176. //# sourceMappingURL=babylon.shadowGenerator.js.map
  67177. var BABYLON;
  67178. (function (BABYLON) {
  67179. var DefaultLoadingScreen = /** @class */ (function () {
  67180. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  67181. if (_loadingText === void 0) { _loadingText = ""; }
  67182. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  67183. var _this = this;
  67184. this._renderingCanvas = _renderingCanvas;
  67185. this._loadingText = _loadingText;
  67186. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  67187. // Resize
  67188. this._resizeLoadingUI = function () {
  67189. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  67190. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  67191. if (!_this._loadingDiv) {
  67192. return;
  67193. }
  67194. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  67195. _this._loadingDiv.style.left = canvasRect.left + "px";
  67196. _this._loadingDiv.style.top = canvasRect.top + "px";
  67197. _this._loadingDiv.style.width = canvasRect.width + "px";
  67198. _this._loadingDiv.style.height = canvasRect.height + "px";
  67199. };
  67200. }
  67201. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  67202. if (this._loadingDiv) {
  67203. // Do not add a loading screen if there is already one
  67204. return;
  67205. }
  67206. this._loadingDiv = document.createElement("div");
  67207. this._loadingDiv.id = "babylonjsLoadingDiv";
  67208. this._loadingDiv.style.opacity = "0";
  67209. this._loadingDiv.style.transition = "opacity 1.5s ease";
  67210. this._loadingDiv.style.pointerEvents = "none";
  67211. // Loading text
  67212. this._loadingTextDiv = document.createElement("div");
  67213. this._loadingTextDiv.style.position = "absolute";
  67214. this._loadingTextDiv.style.left = "0";
  67215. this._loadingTextDiv.style.top = "50%";
  67216. this._loadingTextDiv.style.marginTop = "80px";
  67217. this._loadingTextDiv.style.width = "100%";
  67218. this._loadingTextDiv.style.height = "20px";
  67219. this._loadingTextDiv.style.fontFamily = "Arial";
  67220. this._loadingTextDiv.style.fontSize = "14px";
  67221. this._loadingTextDiv.style.color = "white";
  67222. this._loadingTextDiv.style.textAlign = "center";
  67223. this._loadingTextDiv.innerHTML = "Loading";
  67224. this._loadingDiv.appendChild(this._loadingTextDiv);
  67225. //set the predefined text
  67226. this._loadingTextDiv.innerHTML = this._loadingText;
  67227. // Generating keyframes
  67228. var style = document.createElement('style');
  67229. style.type = 'text/css';
  67230. var keyFrames = "@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\n 100% { -webkit-transform: rotate(360deg);}\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\n 100% { transform: rotate(360deg);}\n }";
  67231. style.innerHTML = keyFrames;
  67232. document.getElementsByTagName('head')[0].appendChild(style);
  67233. // Loading img
  67234. var imgBack = new Image();
  67235. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAYq0lEQVR4Xu2dCZRcVZnHScAJUZSwjSOIbAJmEAZwQCCMoAInYRGIg8AwegQx7AFzUBBmzAFlE4EAwxz2GRk2w7AnAURZBiEOZgyEQDAQAjmEJqTpNd3V1V3Vmd+/6utKV7/1vnpVXd2p/zn3vOV+27vfu/fd/W3QQAPrBZqbm7fJZrN79vf3T+/r67uf4wO9vb37WXQDIwWtra0Tenp6voQTv5XP56/BkfcR3iLk1g6B7hEeI+zP5V+ZiAbqBZ2dnZ8lV+6Gg87CobfhpOc4byf0FjwYE9DneBkWcXrM2tmzNzTxDdQKJPyETCazI46YgiMuI9zJuXJltuChFIHsP/PSfIfTjU19A2mira1tcxy3ey6XO5vEnkV4kes11XBmENDVj97XOT2O03FmWgMuoNLzGRJva8IUnPkzjjcT/kLoKCZzfQB7XiX8M2G8md7AUJgzJ+Z6e88gZ1xGuj3HsY17PcVkrG9gp7CUF/F8PUvxqdZDrFq1ahNVfKjwTCYxZuDE2wjKlc2WViMePM+HPNsFPOdf22OPblD5OZQHvphnV65cjTMzxaQY3eA5V9OO/hmnm1lSjE7woFsQbiXki4++foHnXkW4mLC1JUl947333tsMY3emqfB9jtPJlXN5U0+bOXPmWCPxgOccSy4+AfqPio+9/oFnbyatbqVE28GSZfjQ1NT0KQzaHMcdyPfyaNoE12HcvdxT29K3Fkv8A2vWrPmcifAFZNtD91yRY+SBZ+9UsMtEgD+jTpeenp6JXI6xpKkuUDqRcA6Kr0Wpens+InQTnIpV6Fdi+BQT64ulS5eOIzefD62na7CeoGcnLCM8ykt5OWlzcPv772/BS/w3nP+K+xU11+DvQe5dcrQlTfWAwbNMb8XA8AyGX80xtLlA6TAJuteMbVhhia1v5VMcr+LWMeoZ4xiYw7q6urbhHbgG+paCkIRQehHu4pO3O5fVydEomF5Ulx548JfVD2wqfKE2I3R3ob/f2GoC1DWhdz7HG3i5j2pvb9+Z24m6HvVZQtYsZFWcowlzePEP4jJdR/OQhxTVpAs9NMXxmZxuZKo8IG4s+v8R2tUFphSBTBWzH+OAFwn/gS3TuN55xYoVqfc6dXd3fwHZ1xFaTX0iyGbwjJqXXAammxP00EXx6UMGEx7ram7+vKnzBZ/87Xiwp40tEdDTgYwlHG/CmadSjO7L+XiialOZAej7POFG2VK0Khngl6Pn8/LL0YEtlFh4n8oDAqvaAYH8tzH2iNDm1IIFn8Ax50G7xtgCAU07CfAG4RHOz+vLZL7e0dGxlYlKHaj8BHo25xgrsfV5wrYH4KmouxV+ZZDnCUdwmXxMGgFvFUVWD+jQuOot6rI0tb4gcfaG9v+MrcAn+wj38gL8C7cObmlp2ZRjOkWYD6ypuAf6zjFHLSJ0c/6YQ813DM/yZXgehreiVgP8cvSfsOeExYsXuzs6n8v9j8mqBRZQmdjXVPuira1NHSpn8UDf4Xu0vd2uCtDzacJOlDDf5ng94X8JTWarB8R1EK7ju7udiYgEz/v3pLFKm4oHUHhh3iZdfshpaEYpA4pvKLLXBujLYKRq71XLhUHg27z12rW9B6L/QhLrWWxRH7nzeDK8awi/5HRTEx0K6MZQ694LHk0DqrgfADkreIYz1q5c+UlTEQzesIuMryrggYQWjNL3RGO7p2tuFMeqjaOidgzyCz1yJMTJ6L6d66WEVCcHIO/dQkI75Chs2g97Hoc3jRz9Lge1ED5l4r0gckqRPB0gTw34t1B+h3IqxZkmrn2SULUa7ezZszdE5xfR9130Xsm5ilrnHrmkQOcKvrkncxqrIiY6wlewbw7BOUfDo/b84zzvj9C7J7eCS0NrUiRKCPjUE7ScMBdlF/B2HqBi0ERXBcuXL99YnQz9fX2ah3Up4UnsWGEmDRuUhoTn+Z5PfvbZZ2N/fuCZRJgnfhNVBu73EZoIKt7l0L2UBsYeDZg016nb5EUCWuXQewinUtTuyq2aTStF14a8SD+VDQVj6hDYxjuXf4Hjl83sSMCmTp8j4FtoMuRQ5dAZcii3kk/0s2bBhxIcBxjxUlib1hWInEDO/6qKV+y4geO5HAMntEE/pq+nZyo0ywsG1SmwL4Orf+0yqGCfmvR73LAn9lAeBjQTEhkA+1h49a08iRflcq4H5iuXFU9cz4lqihC/LXS/NZa6Bc+pz5gql5ub6VXD2tZWTSPeyS7XgeLhXrMnEhj6MSHSwaIhFGZH8oA/JzzFeexvJbRN2HW03moT6cEChx6w4QY2rurn85JWrxsiCy0FwjcIqos8w7GZNPulkawDEbFHlaBtjzODEDrVztuKXMmADPWA3RaljyJeNdKq98ilAez8iJdyGqfO31V4NoV/EvyaCqR54V2EshE5Lqcb+TrkstkTLD4WKB4PNNZQ8P05HAelMXNSPWChC8JsYvwthJo0jSoF6fIqjjqe08Aat+LIkd+AVjn09zxbZFqK3tjXAUbXUaWDjTUSyN4J45YZX2Igo4cEOVfFson2ALIxSjR0jog5YNgpfNHM90BxIjDyWIB8Z2NfB01HISJ20wPaw4w1FlavXq1v8aPGXhFw9JNRFTDItifU/RwwpfmKxYsDK180kU4x0lhAXvOSJUs+bezlIDL2N4xi4GpjK4MGCuzUA+SPxzn3m4iKgKyV2DCV08DeMWg0B+zHHOt2DpjS3Mz1BfFOM25C5ZH4LxldJBB0g7GVARkaXgv8VsKqZtIMPpN9RUnJgRzU5Wfp22vifcG3+2vQvmdsdQXsX2pm+oKX+GYjjQXkPWqsXshpRhcJ0RpbGShSHiSuheP37ZYHsGusVHOrU1lMxkO9od4eE+8LlSzQqfetpnPAooBN/2Um+gISp89MkF8K4G3RrMJYoOhbYGxlQEGhSOGogfoLwipExGtUZVVBYIVAluaAaUpuWA+YujlPF22Ra/iBLYEOsV6tV4w0FiitfmLsXiBMU0NiAVrfsp77Zd8MHPgbDoHtva6uLs1jiv1piAKy5tCG+4KJ9wVO/p6RDzvy+b5rzSwP9Okh/WKPERiCWzfk4K8bUSTiOljAyCdx5DZG4gE8W5Dov+NYUfsV/j50fUC4dmXIQDh0qQ6PVgJsOcLM8oA410Ggvo6Ojr81di+g2TKuQOiyJOKWxlpCJpM5zUjKAL3awTsamQfEbYhjtDGKa5tPsyn/wAuiURftlBO56h6aunEwCMxxvV1d+2Fr7Jce2vAu5LUtLeoGi/19gtbToCaR97BoD6BvUs+WkXqgbw6OuhC6wH5l4rRGaCFOvYnjYbyxnpcsCvDVhYOxo6+zszNwSNHVTtJEmSiwzlMAQmNPwIPW42Dds2hfEK/5WJo0Fth+5VNxFHSlkoTzFRh/N3wnq0OGWxXtdoO8enFwaI4jsyidYgNZTxhrMEjEJ4w+En65ESWRXZ7Q4K/COqDAPlhka87WedB8KawmngTIHREOJs5pMiRp+p/GGgxL1FiA9hxjK6G1tVVdhJGAV15+cPXq1f7dahVC20Wg4miCp0uTe3Xh4Hwu93rY1B7SR/t7xQbP5R1FGgpy8IlKe+MJhZ9Aa7u5jPm+pGLX2BMDOZ+hDXgQiXIJ5xoXHZg96anEEFcvOTi0SMUXS4w0FijSTzTWYEA3hkTSEtDI2qw6RoytDLA6jctCvzKqJ8oPFOO7kAhnYe9cZGiWiZ/N9ezguWaSL4h3TUfvKJIfoN0I4sjigYSdZyxlcDVMgEczEY41ER6oZFBOh2Yqegf2zYoziFC3DuZZrjSTPLDtMlxaNPmPP/54W2OPxksrVozP5fLPGr8vEOpbxJCr3jQSJyDvGRNRhv7iHh8vE5LMpKznHBz4zSTOaXwe+mXGGh9tbWvVQf+iyfCAON/ZlTj4v43ECfB94Le4CuMrWVpTtw7O9fZOM5M8oD7xVSOLBdLuNWN1g7bgJUF8+4qpBjf7Te9M6hD4tBDc0289Wh2MHbuaSR7gsHOMLBaQ9W/G6o5MJrNDPu9dcYdQ33Yc95I6OFV5hnp2cGCliDingX5KU+9MShd0dmqta/k8J4zwnV2JsuuNxAnI83VwNpO52kiSoC4djA255cuXBzYPycGzjTQWkPdNY00OfRcQVLafRnd39ySLLsG1i20AyPZ3cDb7AyNJgnp1cOhUHUhcFiL045v9jTUa8Gjlm29fsQQhb3DzJLUEhC+oiK7EISPOwapoEh+7JQJti5YfGXs0YNC62ouC1h9lsrlToClsjc/RM7uSe0kd3EmlzTO/Kqk8Q106mM/Yw2aOB9jnOg6sWTHxJ9FraSJMy6nGz7RbZUDYmN7e3BnQ5Gisez7u3J9c0JwA6Pb0aCFvNObgwKk6NoU59uJwaJ8y1viAT4vCtEFXYO8SFQGtCZpllyXQtNqL+4lmZ/BN/5qJKQFZozEHe9JtAGSaw4wsFnie4JmUQcjleh8yZq0Fnmq3y0D02IzPMgnonYqYIfA4pC+TcXrgIahLB+PEb5s5HrjaR0b7kbHGB0pK7TDO1/T39x1lUZGAPlUH0xTbz+KSoC4dDDx2DQCHzTCaWOB5zjbW+KCSpW0IS0BIJmy6zWCk7WDuxZ4r5oO6dHB7e/sBZo4H2OfUsYOv9jHW+ECJdkAtA/c6MpmMd+XaEKj7km9M4F5TEfBzSKovDLKG1cHobw+b6EDa3WOksYBPAhevBUJMxl8GJTRhFyMLBKSJFn5ls9nvmogS0DfaHOzb3h8AcUuNNBLQNiWa0gRv4MwMMyBwCqxAfCIH82JdYSJKQN+ocjA5NHD2I/e1aj/23iPyhbG6A+bAgXsZoUEII/UAkkQORu71JqIE7o22HBw4VaelpWU74mPPDc/39d1trO5Qb4vJ8QXxbwat06WofcTInMCzeToAtN4VXUn/l1AXDkan9tDSfmL6C81BZooHxDkN9CMveLFZFFAWWZtDwVta3G0sJcAbe3bmYEiniShBXabcL+wflQDD5mD0yKlvk0b/Tk33AG5F7idG+/ibRe54oEl1nLG6A+ZYe1jyAIuG/u2LB3MazxwAfL5vJFGJinxQUwcju6c/n3+FNPm5JhJyy2k/sQTp5nm+2HBJCGi1X1WpwzuBoQXAN+IcjDz8mdePKi/WhH1uxd7GcCjIVBcWpUYDfZ0VbclEJSr2akMBhVrdX6j+Jx3DpSh7vKB8CIiqKwcrcXGqdr05k3RKbU9ryTQVkUB3aHMrEshw7kGCXiv8xxG0h6Uzent6Fpn6MhA17A6GT/3yTxNO1coJbgWur3JFf1fXNuTes5AZe18xXobFHJKv04JZc3O7CtIcgGL9KW03u3QCfL4D4b292dhrpoYgsYOhEz4kaOuHqXKqiagYiN9QnUlyKgX84JUYsQFP9GKzMFRSe8XJb9upE9Dn62CK/KQT75wdTLz+NXgPNdrDuYzeUd0ByN4Wp07n+EdCRZuTY1/ymZQDwIjQye9pA32xdw6IiUgHc639mN8kzCLRjkxzQRzitUpkZ8LZBP1CILUd55EVvdgsCrzJl5i8mgCja+Zgjst4Pq3DUnMmtSWqyNIuQruRU3+CbO08n+pvBAZAjf1IU5kcGJc0YRMBfVV3MPd2RN4+YbvYukI/3sSpe+LUmbw0ryG/6ts1oSLeYrMw6C0xeaFAGc+Wq3hbfeRk582b55lrzf3UHJwWkD0Wp+6BQ3+BfXEXw6UCdHX4TVB0BoJi9Y1Cp59XbUWN8HW7lRjLli3zbINE+1hNiCRI1cGakIhT99ani/A6z1z1nDoUqNQfbO40kyqDfrCBwMg3E5rsCy+8sFlHR8dEnFzRTq/I8hQ9NFFOtGhXVOxgFeUqfknUK7Ctpjl1ANKJ/vmUkvrdwRZmWjpA4J9MTyja2toKY8TQa/ufxP/Whdd5c5cQJHIwfBsTvkKiaqd6/fRyOHKqavdL0H+V2sxmWvrQCAeKItfmQlNyDG/8SVwnetMHyxmA7lm0K2I7GFrlVBW/V6FPP9GqeU4V0Kt2+O2yhctUN6AJBEWD9ngMnessJxh5AfCoQe+8q+xQOYLuWbQrQh2MXP1XYh8S9DKC2sI1z6kCatW3/RCZ6Vj9fNPMqx2wQVNJQlcNEl/mGG5pv48bi7HxMVSOoHsW7QqPg5GlvnJtk6/B9+HMqYUfaXE6rampqWy4dVhgi8FfLprnBXEex+i/wCSkNiSNDSpUxxt7Ccj2nQQYAwUHc9yE3HEotuifDklnfFYMdGNC/lWCxotDf4PvB/jHZTs71c+f2n+ryqCPPcb5/pKdGrTvbH2MUjH4ByOLBDpON9YSFi5cuI1FOwFbbyTox5T6y+iwFL8CqvWvwVtolWgSv/N4sXbl5ZP3r8hRLT50d56KgYJDCYXVhYOhtqqReKDdZuGJtSQSOk8f67x581SspvH3lpoBe9Vefbg/lzveaXmnAf6tEDMNGRp3LnV3ch29o10lQIf+bOKZc+XnmMGARF2EK4vUwQiSw33n7ZlqDWwcaK9Ob29vd26vwj+OT8m3kKFxdd9tlILSJ1Wo8Y8RZT/YiKOY4le5P3SGZJAc7telg7FroL16Jc/n/a1cBBCxsSblwT8LOfofcCh4AQ4x1uoCXZtgVKnYDXLMUECnPSQD29VBcrhfVw7GHrVXb6WylGg0SvUZcrr+YPYuwWVfaE9ltmpA2Q6EQq2UY+yigzf2oqCH4v4MIysD94fdwdig9uqDnB4T5/d+gwHPGNVFcOopyJiPLOfmGTwa0Ek8qS8RKDKORLFWH95utwbDd94SRqqN/Cv4PDXbTFfXfUZWBvRUPJCRBJiIqfnnccy0Dz74wHkWoypY2D4ZGU8gK+kKjQKQ8RcTW1uQI2fmc7nH7LIMFEW+sw6xdyN4CgvNByNIDjp+ZyRVhzlV7dVLaZc7t1cRoW0w9of/No6ptbuRdZupqC3QPZY33HchMkbJiRPssgyaHkN82XaJXPtOJuN+JRuixQI6Cu1VXiZtJehcFGpeNPyXI6cqPWTIvsxU1R7o912akevre4OHfTHot3fEfRbD3y8+Qu0djO5Ce5UXNGl7dTt4z0RGqnOuhgLZgmcPk2FHrrd3jgwkAVQ58e1ioxjcHeMLPWQcq+5gZKm9+hJHjXo5z4xQBQsxxyDjEfir+nNq5GfQo/nYh6f9e4NUgGEFx3DEzvw1nPrOhSJ+kh6GUBUHw6//Kmls96dJ2qv6FxNF9z8g405kVLVXDfkaiFAd4JIkttYUGFpyDOf91Ch/YVEe8DA/gORpuywDfLNMjBOQt4qEupbTPTX4YeJig+/qrnoxkfMeIdH2UHGBfP0H6kFepElc1rY5lBQYXZbzuO7BWYH7b3V3d/+TX1FEG/JSExEJdOi7qsnrx3DuNM8Zdg2NqnN/BjK0EXlVhxORr56wP6Lv/DT+X1FzYLynaOWe2s1TjCQW4An9t6Jk4hBVdH6YpB9YNXoS+SRk/JaQZHd5J2CnesLuyGaze3KZ2hTemoNcpO+uB3pAQuzvC7SeJSfc0258Wo97aX9PT+TmMEMB73jsO0wJzXnVx4llL7pe5kWaFtSqGHHgu6rpPr5jsdx+hyI59G+hA4C25GDO1V69mbf/77h0+lZpzZX44B+Ye1X1cWKz92pKrYlcjtzc6gfN+ufhApd/ErcwTvuTRNI0m4c4Tg77u6gfbCHdTuQcrRFaRKiFU7Xl1O/RqX9RObevRxR43gmEBYUn9wEJIMeF/jk0yVKTta2tE0jg43kx1OatWifEYKDrHYKGDnfkMrU1xHUPaoh7k8i+030EvoV3c6i4aTCoc/9+9NVkFgh6BmZFaig08he3oxYkwBEkQGCzg7gfG6kzaDvuSyLfgIyqt1cF6SAspoS4iJf3c9xaf3JrGEgUzZcOGgvO4agzjTQUkI9V5z4851MuLhBvUUp1gR7tjXEHL+shXFZnduNIBomi6T73FVLLByQePu4N3CxMbVxyzfeQUTYZrdpA3yvoPVf/1jdTGggC6aXx0ieLSecFcWoj72vkhU4IcswU7gVORksb6FHnufbouJ4Xbv+gf1g0EADav9uSeO9YenpA3IfURFVZ0gqEms1rRg0qCzM4TuYy1T061jt0dXXpX0xJ96FMDXIqQXtJ3tSfze6OaY0KU1ogfTUgUJMK0lBIL06dS/F/LJeRe0k2kAAk7BgSWN2GVW/aCOjRuPCbBHVGBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC";
  67236. imgBack.style.position = "absolute";
  67237. imgBack.style.left = "50%";
  67238. imgBack.style.top = "50%";
  67239. imgBack.style.marginLeft = "-60px";
  67240. imgBack.style.marginTop = "-60px";
  67241. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  67242. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  67243. imgBack.style.transformOrigin = "50% 50%";
  67244. imgBack.style.webkitTransformOrigin = "50% 50%";
  67245. this._loadingDiv.appendChild(imgBack);
  67246. this._resizeLoadingUI();
  67247. window.addEventListener("resize", this._resizeLoadingUI);
  67248. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67249. document.body.appendChild(this._loadingDiv);
  67250. this._loadingDiv.style.opacity = "1";
  67251. };
  67252. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  67253. var _this = this;
  67254. if (!this._loadingDiv) {
  67255. return;
  67256. }
  67257. var onTransitionEnd = function () {
  67258. if (!_this._loadingDiv) {
  67259. return;
  67260. }
  67261. document.body.removeChild(_this._loadingDiv);
  67262. window.removeEventListener("resize", _this._resizeLoadingUI);
  67263. _this._loadingDiv = null;
  67264. };
  67265. this._loadingDiv.style.opacity = "0";
  67266. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67267. };
  67268. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67269. set: function (text) {
  67270. this._loadingText = text;
  67271. if (this._loadingTextDiv) {
  67272. this._loadingTextDiv.innerHTML = this._loadingText;
  67273. }
  67274. },
  67275. enumerable: true,
  67276. configurable: true
  67277. });
  67278. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67279. get: function () {
  67280. return this._loadingDivBackgroundColor;
  67281. },
  67282. set: function (color) {
  67283. this._loadingDivBackgroundColor = color;
  67284. if (!this._loadingDiv) {
  67285. return;
  67286. }
  67287. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67288. },
  67289. enumerable: true,
  67290. configurable: true
  67291. });
  67292. return DefaultLoadingScreen;
  67293. }());
  67294. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67295. })(BABYLON || (BABYLON = {}));
  67296. //# sourceMappingURL=babylon.loadingScreen.js.map
  67297. var BABYLON;
  67298. (function (BABYLON) {
  67299. var SceneLoaderProgressEvent = /** @class */ (function () {
  67300. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67301. this.lengthComputable = lengthComputable;
  67302. this.loaded = loaded;
  67303. this.total = total;
  67304. }
  67305. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67306. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67307. };
  67308. return SceneLoaderProgressEvent;
  67309. }());
  67310. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67311. var SceneLoader = /** @class */ (function () {
  67312. function SceneLoader() {
  67313. }
  67314. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67315. get: function () {
  67316. return 0;
  67317. },
  67318. enumerable: true,
  67319. configurable: true
  67320. });
  67321. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67322. get: function () {
  67323. return 1;
  67324. },
  67325. enumerable: true,
  67326. configurable: true
  67327. });
  67328. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67329. get: function () {
  67330. return 2;
  67331. },
  67332. enumerable: true,
  67333. configurable: true
  67334. });
  67335. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67336. get: function () {
  67337. return 3;
  67338. },
  67339. enumerable: true,
  67340. configurable: true
  67341. });
  67342. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67343. get: function () {
  67344. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67345. },
  67346. set: function (value) {
  67347. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67348. },
  67349. enumerable: true,
  67350. configurable: true
  67351. });
  67352. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67353. get: function () {
  67354. return SceneLoader._ShowLoadingScreen;
  67355. },
  67356. set: function (value) {
  67357. SceneLoader._ShowLoadingScreen = value;
  67358. },
  67359. enumerable: true,
  67360. configurable: true
  67361. });
  67362. Object.defineProperty(SceneLoader, "loggingLevel", {
  67363. get: function () {
  67364. return SceneLoader._loggingLevel;
  67365. },
  67366. set: function (value) {
  67367. SceneLoader._loggingLevel = value;
  67368. },
  67369. enumerable: true,
  67370. configurable: true
  67371. });
  67372. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67373. get: function () {
  67374. return SceneLoader._CleanBoneMatrixWeights;
  67375. },
  67376. set: function (value) {
  67377. SceneLoader._CleanBoneMatrixWeights = value;
  67378. },
  67379. enumerable: true,
  67380. configurable: true
  67381. });
  67382. SceneLoader._getDefaultPlugin = function () {
  67383. return SceneLoader._registeredPlugins[".babylon"];
  67384. };
  67385. SceneLoader._getPluginForExtension = function (extension) {
  67386. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67387. if (registeredPlugin) {
  67388. return registeredPlugin;
  67389. }
  67390. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type");
  67391. return SceneLoader._getDefaultPlugin();
  67392. };
  67393. SceneLoader._getPluginForDirectLoad = function (data) {
  67394. for (var extension in SceneLoader._registeredPlugins) {
  67395. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67396. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67397. return SceneLoader._registeredPlugins[extension];
  67398. }
  67399. }
  67400. return SceneLoader._getDefaultPlugin();
  67401. };
  67402. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67403. if (sceneFilename.name) {
  67404. sceneFilename = sceneFilename.name;
  67405. }
  67406. var queryStringPosition = sceneFilename.indexOf("?");
  67407. if (queryStringPosition !== -1) {
  67408. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67409. }
  67410. var dotPosition = sceneFilename.lastIndexOf(".");
  67411. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67412. return SceneLoader._getPluginForExtension(extension);
  67413. };
  67414. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67415. SceneLoader._getDirectLoad = function (sceneFilename) {
  67416. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67417. return sceneFilename.substr(5);
  67418. }
  67419. return null;
  67420. };
  67421. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67422. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67423. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67424. var plugin;
  67425. if (registeredPlugin.plugin.createPlugin) {
  67426. plugin = registeredPlugin.plugin.createPlugin();
  67427. }
  67428. else {
  67429. plugin = registeredPlugin.plugin;
  67430. }
  67431. var useArrayBuffer = registeredPlugin.isBinary;
  67432. var database;
  67433. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67434. var dataCallback = function (data, responseURL) {
  67435. if (scene.isDisposed) {
  67436. onError("Scene has been disposed");
  67437. return;
  67438. }
  67439. scene.database = database;
  67440. onSuccess(plugin, data, responseURL);
  67441. };
  67442. var request = null;
  67443. var pluginDisposed = false;
  67444. var onDisposeObservable = plugin.onDisposeObservable;
  67445. if (onDisposeObservable) {
  67446. onDisposeObservable.add(function () {
  67447. pluginDisposed = true;
  67448. if (request) {
  67449. request.abort();
  67450. request = null;
  67451. }
  67452. onDispose();
  67453. });
  67454. }
  67455. var manifestChecked = function () {
  67456. if (pluginDisposed) {
  67457. return;
  67458. }
  67459. var url = rootUrl + sceneFilename;
  67460. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67461. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67462. } : undefined, database, useArrayBuffer, function (request, exception) {
  67463. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67464. });
  67465. };
  67466. if (directLoad) {
  67467. dataCallback(directLoad);
  67468. return plugin;
  67469. }
  67470. if (rootUrl.indexOf("file:") === -1) {
  67471. var engine = scene.getEngine();
  67472. var canUseOfflineSupport = engine.enableOfflineSupport;
  67473. if (canUseOfflineSupport) {
  67474. // Also check for exceptions
  67475. var exceptionFound = false;
  67476. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67477. var regex = _a[_i];
  67478. if (regex.test(rootUrl + sceneFilename)) {
  67479. exceptionFound = true;
  67480. break;
  67481. }
  67482. }
  67483. canUseOfflineSupport = !exceptionFound;
  67484. }
  67485. if (canUseOfflineSupport) {
  67486. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67487. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67488. }
  67489. else {
  67490. manifestChecked();
  67491. }
  67492. }
  67493. // Loading file from disk via input file or drag'n'drop
  67494. else {
  67495. var fileOrString = sceneFilename;
  67496. if (fileOrString.name) { // File
  67497. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67498. }
  67499. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67500. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67501. }
  67502. else {
  67503. onError("Unable to find file named " + sceneFilename);
  67504. }
  67505. }
  67506. return plugin;
  67507. };
  67508. // Public functions
  67509. SceneLoader.GetPluginForExtension = function (extension) {
  67510. return SceneLoader._getPluginForExtension(extension).plugin;
  67511. };
  67512. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67513. return !!SceneLoader._registeredPlugins[extension];
  67514. };
  67515. SceneLoader.RegisterPlugin = function (plugin) {
  67516. if (typeof plugin.extensions === "string") {
  67517. var extension = plugin.extensions;
  67518. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67519. plugin: plugin,
  67520. isBinary: false
  67521. };
  67522. }
  67523. else {
  67524. var extensions = plugin.extensions;
  67525. Object.keys(extensions).forEach(function (extension) {
  67526. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67527. plugin: plugin,
  67528. isBinary: extensions[extension].isBinary
  67529. };
  67530. });
  67531. }
  67532. };
  67533. /**
  67534. * Import meshes into a scene
  67535. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67536. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67537. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67538. * @param scene the instance of BABYLON.Scene to append to
  67539. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67540. * @param onProgress a callback with a progress event for each file being loaded
  67541. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67542. * @param pluginExtension the extension used to determine the plugin
  67543. * @returns The loaded plugin
  67544. */
  67545. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67546. if (sceneFilename === void 0) { sceneFilename = ""; }
  67547. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67548. if (onSuccess === void 0) { onSuccess = null; }
  67549. if (onProgress === void 0) { onProgress = null; }
  67550. if (onError === void 0) { onError = null; }
  67551. if (pluginExtension === void 0) { pluginExtension = null; }
  67552. if (!scene) {
  67553. BABYLON.Tools.Error("No scene available to import mesh to");
  67554. return null;
  67555. }
  67556. if (!sceneFilename) {
  67557. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67558. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67559. }
  67560. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67561. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67562. return null;
  67563. }
  67564. var loadingToken = {};
  67565. scene._addPendingData(loadingToken);
  67566. var disposeHandler = function () {
  67567. scene._removePendingData(loadingToken);
  67568. };
  67569. var errorHandler = function (message, exception) {
  67570. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67571. if (onError) {
  67572. onError(scene, errorMessage, exception);
  67573. }
  67574. else {
  67575. BABYLON.Tools.Error(errorMessage);
  67576. // should the exception be thrown?
  67577. }
  67578. disposeHandler();
  67579. };
  67580. var progressHandler = onProgress ? function (event) {
  67581. try {
  67582. onProgress(event);
  67583. }
  67584. catch (e) {
  67585. errorHandler("Error in onProgress callback", e);
  67586. }
  67587. } : undefined;
  67588. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67589. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67590. if (onSuccess) {
  67591. try {
  67592. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67593. }
  67594. catch (e) {
  67595. errorHandler("Error in onSuccess callback", e);
  67596. }
  67597. }
  67598. scene._removePendingData(loadingToken);
  67599. };
  67600. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67601. if (plugin.rewriteRootURL) {
  67602. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67603. }
  67604. if (sceneFilename === "") {
  67605. if (sceneFilename === "") {
  67606. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67607. }
  67608. }
  67609. if (plugin.importMesh) {
  67610. var syncedPlugin = plugin;
  67611. var meshes = new Array();
  67612. var particleSystems = new Array();
  67613. var skeletons = new Array();
  67614. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67615. return;
  67616. }
  67617. scene.loadingPluginName = plugin.name;
  67618. successHandler(meshes, particleSystems, skeletons, []);
  67619. }
  67620. else {
  67621. var asyncedPlugin = plugin;
  67622. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67623. scene.loadingPluginName = plugin.name;
  67624. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67625. }).catch(function (error) {
  67626. errorHandler(error.message, error);
  67627. });
  67628. }
  67629. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67630. };
  67631. /**
  67632. * Import meshes into a scene
  67633. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67634. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67635. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67636. * @param scene the instance of BABYLON.Scene to append to
  67637. * @param onProgress a callback with a progress event for each file being loaded
  67638. * @param pluginExtension the extension used to determine the plugin
  67639. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67640. */
  67641. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67642. if (sceneFilename === void 0) { sceneFilename = ""; }
  67643. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67644. if (onProgress === void 0) { onProgress = null; }
  67645. if (pluginExtension === void 0) { pluginExtension = null; }
  67646. return new Promise(function (resolve, reject) {
  67647. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67648. resolve({
  67649. meshes: meshes,
  67650. particleSystems: particleSystems,
  67651. skeletons: skeletons,
  67652. animationGroups: animationGroups
  67653. });
  67654. }, onProgress, function (scene, message, exception) {
  67655. reject(exception || new Error(message));
  67656. }, pluginExtension);
  67657. });
  67658. };
  67659. /**
  67660. * Load a scene
  67661. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67662. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67663. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67664. * @param onSuccess a callback with the scene when import succeeds
  67665. * @param onProgress a callback with a progress event for each file being loaded
  67666. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67667. * @param pluginExtension the extension used to determine the plugin
  67668. * @returns The loaded plugin
  67669. */
  67670. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67671. if (onSuccess === void 0) { onSuccess = null; }
  67672. if (onProgress === void 0) { onProgress = null; }
  67673. if (onError === void 0) { onError = null; }
  67674. if (pluginExtension === void 0) { pluginExtension = null; }
  67675. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67676. };
  67677. /**
  67678. * Load a scene
  67679. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67680. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67681. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67682. * @param onProgress a callback with a progress event for each file being loaded
  67683. * @param pluginExtension the extension used to determine the plugin
  67684. * @returns The loaded scene
  67685. */
  67686. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67687. if (onProgress === void 0) { onProgress = null; }
  67688. if (pluginExtension === void 0) { pluginExtension = null; }
  67689. return new Promise(function (resolve, reject) {
  67690. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67691. resolve(scene);
  67692. }, onProgress, function (scene, message, exception) {
  67693. reject(exception || new Error(message));
  67694. }, pluginExtension);
  67695. });
  67696. };
  67697. /**
  67698. * Append a scene
  67699. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67700. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67701. * @param scene is the instance of BABYLON.Scene to append to
  67702. * @param onSuccess a callback with the scene when import succeeds
  67703. * @param onProgress a callback with a progress event for each file being loaded
  67704. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67705. * @param pluginExtension the extension used to determine the plugin
  67706. * @returns The loaded plugin
  67707. */
  67708. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67709. if (sceneFilename === void 0) { sceneFilename = ""; }
  67710. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67711. if (onSuccess === void 0) { onSuccess = null; }
  67712. if (onProgress === void 0) { onProgress = null; }
  67713. if (onError === void 0) { onError = null; }
  67714. if (pluginExtension === void 0) { pluginExtension = null; }
  67715. if (!scene) {
  67716. BABYLON.Tools.Error("No scene available to append to");
  67717. return null;
  67718. }
  67719. if (!sceneFilename) {
  67720. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67721. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67722. }
  67723. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67724. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67725. return null;
  67726. }
  67727. if (SceneLoader.ShowLoadingScreen) {
  67728. scene.getEngine().displayLoadingUI();
  67729. }
  67730. var loadingToken = {};
  67731. scene._addPendingData(loadingToken);
  67732. var disposeHandler = function () {
  67733. scene._removePendingData(loadingToken);
  67734. scene.getEngine().hideLoadingUI();
  67735. };
  67736. var errorHandler = function (message, exception) {
  67737. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67738. if (onError) {
  67739. onError(scene, errorMessage, exception);
  67740. }
  67741. else {
  67742. BABYLON.Tools.Error(errorMessage);
  67743. // should the exception be thrown?
  67744. }
  67745. disposeHandler();
  67746. };
  67747. var progressHandler = onProgress ? function (event) {
  67748. try {
  67749. onProgress(event);
  67750. }
  67751. catch (e) {
  67752. errorHandler("Error in onProgress callback", e);
  67753. }
  67754. } : undefined;
  67755. var successHandler = function () {
  67756. if (onSuccess) {
  67757. try {
  67758. onSuccess(scene);
  67759. }
  67760. catch (e) {
  67761. errorHandler("Error in onSuccess callback", e);
  67762. }
  67763. }
  67764. scene._removePendingData(loadingToken);
  67765. };
  67766. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67767. if (sceneFilename === "") {
  67768. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67769. }
  67770. if (plugin.load) {
  67771. var syncedPlugin = plugin;
  67772. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67773. return;
  67774. }
  67775. scene.loadingPluginName = plugin.name;
  67776. successHandler();
  67777. }
  67778. else {
  67779. var asyncedPlugin = plugin;
  67780. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67781. scene.loadingPluginName = plugin.name;
  67782. successHandler();
  67783. }).catch(function (error) {
  67784. errorHandler(error.message, error);
  67785. });
  67786. }
  67787. if (SceneLoader.ShowLoadingScreen) {
  67788. scene.executeWhenReady(function () {
  67789. scene.getEngine().hideLoadingUI();
  67790. });
  67791. }
  67792. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67793. };
  67794. /**
  67795. * Append a scene
  67796. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67797. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67798. * @param scene is the instance of BABYLON.Scene to append to
  67799. * @param onProgress a callback with a progress event for each file being loaded
  67800. * @param pluginExtension the extension used to determine the plugin
  67801. * @returns The given scene
  67802. */
  67803. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67804. if (sceneFilename === void 0) { sceneFilename = ""; }
  67805. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67806. if (onProgress === void 0) { onProgress = null; }
  67807. if (pluginExtension === void 0) { pluginExtension = null; }
  67808. return new Promise(function (resolve, reject) {
  67809. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67810. resolve(scene);
  67811. }, onProgress, function (scene, message, exception) {
  67812. reject(exception || new Error(message));
  67813. }, pluginExtension);
  67814. });
  67815. };
  67816. /**
  67817. * Load a scene into an asset container
  67818. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67819. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67820. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  67821. * @param onSuccess a callback with the scene when import succeeds
  67822. * @param onProgress a callback with a progress event for each file being loaded
  67823. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67824. * @param pluginExtension the extension used to determine the plugin
  67825. * @returns The loaded plugin
  67826. */
  67827. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67828. if (sceneFilename === void 0) { sceneFilename = ""; }
  67829. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67830. if (onSuccess === void 0) { onSuccess = null; }
  67831. if (onProgress === void 0) { onProgress = null; }
  67832. if (onError === void 0) { onError = null; }
  67833. if (pluginExtension === void 0) { pluginExtension = null; }
  67834. if (!scene) {
  67835. BABYLON.Tools.Error("No scene available to load asset container to");
  67836. return null;
  67837. }
  67838. if (!sceneFilename) {
  67839. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67840. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67841. }
  67842. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67843. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67844. return null;
  67845. }
  67846. var loadingToken = {};
  67847. scene._addPendingData(loadingToken);
  67848. var disposeHandler = function () {
  67849. scene._removePendingData(loadingToken);
  67850. };
  67851. var errorHandler = function (message, exception) {
  67852. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67853. if (onError) {
  67854. onError(scene, errorMessage, exception);
  67855. }
  67856. else {
  67857. BABYLON.Tools.Error(errorMessage);
  67858. // should the exception be thrown?
  67859. }
  67860. disposeHandler();
  67861. };
  67862. var progressHandler = onProgress ? function (event) {
  67863. try {
  67864. onProgress(event);
  67865. }
  67866. catch (e) {
  67867. errorHandler("Error in onProgress callback", e);
  67868. }
  67869. } : undefined;
  67870. var successHandler = function (assets) {
  67871. if (onSuccess) {
  67872. try {
  67873. onSuccess(assets);
  67874. }
  67875. catch (e) {
  67876. errorHandler("Error in onSuccess callback", e);
  67877. }
  67878. }
  67879. scene._removePendingData(loadingToken);
  67880. };
  67881. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67882. if (plugin.loadAssetContainer) {
  67883. var syncedPlugin = plugin;
  67884. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67885. if (!assetContainer) {
  67886. return;
  67887. }
  67888. scene.loadingPluginName = plugin.name;
  67889. successHandler(assetContainer);
  67890. }
  67891. else if (plugin.loadAssetContainerAsync) {
  67892. var asyncedPlugin = plugin;
  67893. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67894. scene.loadingPluginName = plugin.name;
  67895. successHandler(assetContainer);
  67896. }).catch(function (error) {
  67897. errorHandler(error.message, error);
  67898. });
  67899. }
  67900. else {
  67901. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67902. }
  67903. if (SceneLoader.ShowLoadingScreen) {
  67904. scene.executeWhenReady(function () {
  67905. scene.getEngine().hideLoadingUI();
  67906. });
  67907. }
  67908. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67909. };
  67910. /**
  67911. * Load a scene into an asset container
  67912. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67913. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67914. * @param scene is the instance of BABYLON.Scene to append to
  67915. * @param onProgress a callback with a progress event for each file being loaded
  67916. * @param pluginExtension the extension used to determine the plugin
  67917. * @returns The loaded asset container
  67918. */
  67919. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67920. if (sceneFilename === void 0) { sceneFilename = ""; }
  67921. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67922. if (onProgress === void 0) { onProgress = null; }
  67923. if (pluginExtension === void 0) { pluginExtension = null; }
  67924. return new Promise(function (resolve, reject) {
  67925. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67926. resolve(assetContainer);
  67927. }, onProgress, function (scene, message, exception) {
  67928. reject(exception || new Error(message));
  67929. }, pluginExtension);
  67930. });
  67931. };
  67932. // Flags
  67933. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67934. SceneLoader._ShowLoadingScreen = true;
  67935. SceneLoader._CleanBoneMatrixWeights = false;
  67936. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67937. // Members
  67938. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67939. SceneLoader._registeredPlugins = {};
  67940. return SceneLoader;
  67941. }());
  67942. BABYLON.SceneLoader = SceneLoader;
  67943. ;
  67944. })(BABYLON || (BABYLON = {}));
  67945. //# sourceMappingURL=babylon.sceneLoader.js.map
  67946. var BABYLON;
  67947. (function (BABYLON) {
  67948. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67949. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67950. var parsedMaterial = parsedData.materials[index];
  67951. if (parsedMaterial.id === id) {
  67952. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67953. }
  67954. }
  67955. return null;
  67956. };
  67957. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67958. for (var i in names) {
  67959. if (mesh.name === names[i]) {
  67960. hierarchyIds.push(mesh.id);
  67961. return true;
  67962. }
  67963. }
  67964. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67965. hierarchyIds.push(mesh.id);
  67966. return true;
  67967. }
  67968. return false;
  67969. };
  67970. var logOperation = function (operation, producer) {
  67971. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67972. };
  67973. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67974. if (addToScene === void 0) { addToScene = false; }
  67975. var container = new BABYLON.AssetContainer(scene);
  67976. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67977. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67978. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67979. // and avoid problems with multiple concurrent .babylon loads.
  67980. var log = "importScene has failed JSON parse";
  67981. try {
  67982. var parsedData = JSON.parse(data);
  67983. log = "";
  67984. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67985. var index;
  67986. var cache;
  67987. // Lights
  67988. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67989. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67990. var parsedLight = parsedData.lights[index];
  67991. var light = BABYLON.Light.Parse(parsedLight, scene);
  67992. if (light) {
  67993. container.lights.push(light);
  67994. log += (index === 0 ? "\n\tLights:" : "");
  67995. log += "\n\t\t" + light.toString(fullDetails);
  67996. }
  67997. }
  67998. }
  67999. // Animations
  68000. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  68001. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  68002. var parsedAnimation = parsedData.animations[index];
  68003. var animation = BABYLON.Animation.Parse(parsedAnimation);
  68004. scene.animations.push(animation);
  68005. container.animations.push(animation);
  68006. log += (index === 0 ? "\n\tAnimations:" : "");
  68007. log += "\n\t\t" + animation.toString(fullDetails);
  68008. }
  68009. }
  68010. // Materials
  68011. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  68012. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68013. var parsedMaterial = parsedData.materials[index];
  68014. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68015. container.materials.push(mat);
  68016. log += (index === 0 ? "\n\tMaterials:" : "");
  68017. log += "\n\t\t" + mat.toString(fullDetails);
  68018. }
  68019. }
  68020. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68021. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  68022. var parsedMultiMaterial = parsedData.multiMaterials[index];
  68023. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68024. container.multiMaterials.push(mmat);
  68025. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  68026. log += "\n\t\t" + mmat.toString(fullDetails);
  68027. }
  68028. }
  68029. // Morph targets
  68030. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68031. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68032. var managerData = _a[_i];
  68033. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  68034. }
  68035. }
  68036. // Skeletons
  68037. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68038. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  68039. var parsedSkeleton = parsedData.skeletons[index];
  68040. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68041. container.skeletons.push(skeleton);
  68042. log += (index === 0 ? "\n\tSkeletons:" : "");
  68043. log += "\n\t\t" + skeleton.toString(fullDetails);
  68044. }
  68045. }
  68046. // Geometries
  68047. var geometries = parsedData.geometries;
  68048. if (geometries !== undefined && geometries !== null) {
  68049. var addedGeometry = new Array();
  68050. // Boxes
  68051. var boxes = geometries.boxes;
  68052. if (boxes !== undefined && boxes !== null) {
  68053. for (index = 0, cache = boxes.length; index < cache; index++) {
  68054. var parsedBox = boxes[index];
  68055. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  68056. }
  68057. }
  68058. // Spheres
  68059. var spheres = geometries.spheres;
  68060. if (spheres !== undefined && spheres !== null) {
  68061. for (index = 0, cache = spheres.length; index < cache; index++) {
  68062. var parsedSphere = spheres[index];
  68063. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  68064. }
  68065. }
  68066. // Cylinders
  68067. var cylinders = geometries.cylinders;
  68068. if (cylinders !== undefined && cylinders !== null) {
  68069. for (index = 0, cache = cylinders.length; index < cache; index++) {
  68070. var parsedCylinder = cylinders[index];
  68071. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  68072. }
  68073. }
  68074. // Toruses
  68075. var toruses = geometries.toruses;
  68076. if (toruses !== undefined && toruses !== null) {
  68077. for (index = 0, cache = toruses.length; index < cache; index++) {
  68078. var parsedTorus = toruses[index];
  68079. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  68080. }
  68081. }
  68082. // Grounds
  68083. var grounds = geometries.grounds;
  68084. if (grounds !== undefined && grounds !== null) {
  68085. for (index = 0, cache = grounds.length; index < cache; index++) {
  68086. var parsedGround = grounds[index];
  68087. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  68088. }
  68089. }
  68090. // Planes
  68091. var planes = geometries.planes;
  68092. if (planes !== undefined && planes !== null) {
  68093. for (index = 0, cache = planes.length; index < cache; index++) {
  68094. var parsedPlane = planes[index];
  68095. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  68096. }
  68097. }
  68098. // TorusKnots
  68099. var torusKnots = geometries.torusKnots;
  68100. if (torusKnots !== undefined && torusKnots !== null) {
  68101. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  68102. var parsedTorusKnot = torusKnots[index];
  68103. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  68104. }
  68105. }
  68106. // VertexData
  68107. var vertexData = geometries.vertexData;
  68108. if (vertexData !== undefined && vertexData !== null) {
  68109. for (index = 0, cache = vertexData.length; index < cache; index++) {
  68110. var parsedVertexData = vertexData[index];
  68111. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  68112. }
  68113. }
  68114. addedGeometry.forEach(function (g) {
  68115. if (g) {
  68116. container.geometries.push(g);
  68117. }
  68118. });
  68119. }
  68120. // Transform nodes
  68121. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  68122. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  68123. var parsedTransformNode = parsedData.transformNodes[index];
  68124. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  68125. container.transformNodes.push(node);
  68126. }
  68127. }
  68128. // Meshes
  68129. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68130. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68131. var parsedMesh = parsedData.meshes[index];
  68132. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68133. container.meshes.push(mesh);
  68134. log += (index === 0 ? "\n\tMeshes:" : "");
  68135. log += "\n\t\t" + mesh.toString(fullDetails);
  68136. }
  68137. }
  68138. // Cameras
  68139. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  68140. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  68141. var parsedCamera = parsedData.cameras[index];
  68142. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  68143. container.cameras.push(camera);
  68144. log += (index === 0 ? "\n\tCameras:" : "");
  68145. log += "\n\t\t" + camera.toString(fullDetails);
  68146. }
  68147. }
  68148. // Browsing all the graph to connect the dots
  68149. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  68150. var camera = scene.cameras[index];
  68151. if (camera._waitingParentId) {
  68152. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  68153. camera._waitingParentId = null;
  68154. }
  68155. }
  68156. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68157. var light_1 = scene.lights[index];
  68158. if (light_1 && light_1._waitingParentId) {
  68159. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  68160. light_1._waitingParentId = null;
  68161. }
  68162. }
  68163. // Sounds
  68164. // TODO: add sound
  68165. var loadedSounds = [];
  68166. var loadedSound;
  68167. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68168. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68169. var parsedSound = parsedData.sounds[index];
  68170. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68171. if (!parsedSound.url)
  68172. parsedSound.url = parsedSound.name;
  68173. if (!loadedSounds[parsedSound.url]) {
  68174. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68175. loadedSounds[parsedSound.url] = loadedSound;
  68176. container.sounds.push(loadedSound);
  68177. }
  68178. else {
  68179. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68180. }
  68181. }
  68182. else {
  68183. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68184. }
  68185. }
  68186. }
  68187. loadedSounds = [];
  68188. // Connect parents & children and parse actions
  68189. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  68190. var transformNode = scene.transformNodes[index];
  68191. if (transformNode._waitingParentId) {
  68192. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  68193. transformNode._waitingParentId = null;
  68194. }
  68195. }
  68196. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68197. var mesh = scene.meshes[index];
  68198. if (mesh._waitingParentId) {
  68199. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  68200. mesh._waitingParentId = null;
  68201. }
  68202. if (mesh._waitingActions) {
  68203. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  68204. mesh._waitingActions = null;
  68205. }
  68206. }
  68207. // freeze world matrix application
  68208. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68209. var currentMesh = scene.meshes[index];
  68210. if (currentMesh._waitingFreezeWorldMatrix) {
  68211. currentMesh.freezeWorldMatrix();
  68212. currentMesh._waitingFreezeWorldMatrix = null;
  68213. }
  68214. else {
  68215. currentMesh.computeWorldMatrix(true);
  68216. }
  68217. }
  68218. // Particles Systems
  68219. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68220. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68221. var parsedParticleSystem = parsedData.particleSystems[index];
  68222. if (parsedParticleSystem.activeParticleCount) {
  68223. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68224. container.particleSystems.push(ps);
  68225. }
  68226. else {
  68227. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68228. container.particleSystems.push(ps);
  68229. }
  68230. }
  68231. }
  68232. // Lens flares
  68233. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  68234. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  68235. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  68236. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  68237. container.lensFlareSystems.push(lf);
  68238. }
  68239. }
  68240. // Shadows
  68241. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  68242. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  68243. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  68244. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  68245. container.shadowGenerators.push(sg);
  68246. }
  68247. }
  68248. // Lights exclusions / inclusions
  68249. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68250. var light_2 = scene.lights[index];
  68251. // Excluded check
  68252. if (light_2._excludedMeshesIds.length > 0) {
  68253. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  68254. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  68255. if (excludedMesh) {
  68256. light_2.excludedMeshes.push(excludedMesh);
  68257. }
  68258. }
  68259. light_2._excludedMeshesIds = [];
  68260. }
  68261. // Included check
  68262. if (light_2._includedOnlyMeshesIds.length > 0) {
  68263. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  68264. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  68265. if (includedOnlyMesh) {
  68266. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68267. }
  68268. }
  68269. light_2._includedOnlyMeshesIds = [];
  68270. }
  68271. }
  68272. // Effect layers
  68273. if (parsedData.effectLayers) {
  68274. for (index = 0; index < parsedData.effectLayers.length; index++) {
  68275. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  68276. container.effectLayers.push(effectLayer);
  68277. }
  68278. }
  68279. // Actions (scene)
  68280. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68281. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68282. }
  68283. if (!addToScene) {
  68284. container.removeAllFromScene();
  68285. }
  68286. }
  68287. catch (err) {
  68288. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68289. if (onError) {
  68290. onError(msg, err);
  68291. }
  68292. else {
  68293. BABYLON.Tools.Log(msg);
  68294. throw err;
  68295. }
  68296. }
  68297. finally {
  68298. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68299. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68300. }
  68301. }
  68302. return container;
  68303. };
  68304. BABYLON.SceneLoader.RegisterPlugin({
  68305. name: "babylon.js",
  68306. extensions: ".babylon",
  68307. canDirectLoad: function (data) {
  68308. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68309. return true;
  68310. }
  68311. return false;
  68312. },
  68313. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68314. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68315. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68316. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68317. // and avoid problems with multiple concurrent .babylon loads.
  68318. var log = "importMesh has failed JSON parse";
  68319. try {
  68320. var parsedData = JSON.parse(data);
  68321. log = "";
  68322. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68323. if (!meshesNames) {
  68324. meshesNames = null;
  68325. }
  68326. else if (!Array.isArray(meshesNames)) {
  68327. meshesNames = [meshesNames];
  68328. }
  68329. var hierarchyIds = new Array();
  68330. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68331. var loadedSkeletonsIds = [];
  68332. var loadedMaterialsIds = [];
  68333. var index;
  68334. var cache;
  68335. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68336. var parsedMesh = parsedData.meshes[index];
  68337. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68338. if (meshesNames !== null) {
  68339. // Remove found mesh name from list.
  68340. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68341. }
  68342. //Geometry?
  68343. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68344. //does the file contain geometries?
  68345. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68346. //find the correct geometry and add it to the scene
  68347. var found = false;
  68348. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68349. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68350. return;
  68351. }
  68352. else {
  68353. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68354. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68355. switch (geometryType) {
  68356. case "boxes":
  68357. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68358. break;
  68359. case "spheres":
  68360. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68361. break;
  68362. case "cylinders":
  68363. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68364. break;
  68365. case "toruses":
  68366. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68367. break;
  68368. case "grounds":
  68369. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68370. break;
  68371. case "planes":
  68372. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68373. break;
  68374. case "torusKnots":
  68375. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68376. break;
  68377. case "vertexData":
  68378. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68379. break;
  68380. }
  68381. found = true;
  68382. }
  68383. });
  68384. }
  68385. });
  68386. if (found === false) {
  68387. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68388. }
  68389. }
  68390. }
  68391. // Material ?
  68392. if (parsedMesh.materialId) {
  68393. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68394. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68395. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68396. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68397. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68398. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68399. var subMatId = parsedMultiMaterial.materials[matIndex];
  68400. loadedMaterialsIds.push(subMatId);
  68401. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68402. if (mat) {
  68403. log += "\n\tMaterial " + mat.toString(fullDetails);
  68404. }
  68405. }
  68406. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68407. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68408. if (mmat) {
  68409. materialFound = true;
  68410. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68411. }
  68412. break;
  68413. }
  68414. }
  68415. }
  68416. if (materialFound === false) {
  68417. loadedMaterialsIds.push(parsedMesh.materialId);
  68418. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68419. if (!mat) {
  68420. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68421. }
  68422. else {
  68423. log += "\n\tMaterial " + mat.toString(fullDetails);
  68424. }
  68425. }
  68426. }
  68427. // Skeleton ?
  68428. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68429. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68430. if (skeletonAlreadyLoaded === false) {
  68431. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68432. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68433. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68434. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68435. skeletons.push(skeleton);
  68436. loadedSkeletonsIds.push(parsedSkeleton.id);
  68437. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68438. }
  68439. }
  68440. }
  68441. }
  68442. // Morph targets ?
  68443. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68444. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68445. var managerData = _a[_i];
  68446. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68447. }
  68448. }
  68449. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68450. meshes.push(mesh);
  68451. log += "\n\tMesh " + mesh.toString(fullDetails);
  68452. }
  68453. }
  68454. // Connecting parents
  68455. var currentMesh;
  68456. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68457. currentMesh = scene.meshes[index];
  68458. if (currentMesh._waitingParentId) {
  68459. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68460. currentMesh._waitingParentId = null;
  68461. }
  68462. }
  68463. // freeze and compute world matrix application
  68464. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68465. currentMesh = scene.meshes[index];
  68466. if (currentMesh._waitingFreezeWorldMatrix) {
  68467. currentMesh.freezeWorldMatrix();
  68468. currentMesh._waitingFreezeWorldMatrix = null;
  68469. }
  68470. else {
  68471. currentMesh.computeWorldMatrix(true);
  68472. }
  68473. }
  68474. }
  68475. // Particles
  68476. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68477. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68478. var parsedParticleSystem = parsedData.particleSystems[index];
  68479. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68480. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68481. }
  68482. }
  68483. }
  68484. return true;
  68485. }
  68486. catch (err) {
  68487. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68488. if (onError) {
  68489. onError(msg, err);
  68490. }
  68491. else {
  68492. BABYLON.Tools.Log(msg);
  68493. throw err;
  68494. }
  68495. }
  68496. finally {
  68497. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68498. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68499. }
  68500. }
  68501. return false;
  68502. },
  68503. load: function (scene, data, rootUrl, onError) {
  68504. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68505. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68506. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68507. // and avoid problems with multiple concurrent .babylon loads.
  68508. var log = "importScene has failed JSON parse";
  68509. try {
  68510. var parsedData = JSON.parse(data);
  68511. log = "";
  68512. // Scene
  68513. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68514. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68515. }
  68516. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68517. scene.autoClear = parsedData.autoClear;
  68518. }
  68519. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68520. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68521. }
  68522. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68523. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68524. }
  68525. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68526. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68527. }
  68528. // Fog
  68529. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68530. scene.fogMode = parsedData.fogMode;
  68531. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68532. scene.fogStart = parsedData.fogStart;
  68533. scene.fogEnd = parsedData.fogEnd;
  68534. scene.fogDensity = parsedData.fogDensity;
  68535. log += "\tFog mode for scene: ";
  68536. switch (scene.fogMode) {
  68537. // getters not compiling, so using hardcoded
  68538. case 1:
  68539. log += "exp\n";
  68540. break;
  68541. case 2:
  68542. log += "exp2\n";
  68543. break;
  68544. case 3:
  68545. log += "linear\n";
  68546. break;
  68547. }
  68548. }
  68549. //Physics
  68550. if (parsedData.physicsEnabled) {
  68551. var physicsPlugin;
  68552. if (parsedData.physicsEngine === "cannon") {
  68553. physicsPlugin = new BABYLON.CannonJSPlugin();
  68554. }
  68555. else if (parsedData.physicsEngine === "oimo") {
  68556. physicsPlugin = new BABYLON.OimoJSPlugin();
  68557. }
  68558. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68559. //else - default engine, which is currently oimo
  68560. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68561. scene.enablePhysics(physicsGravity, physicsPlugin);
  68562. }
  68563. // Metadata
  68564. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68565. scene.metadata = parsedData.metadata;
  68566. }
  68567. //collisions, if defined. otherwise, default is true
  68568. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68569. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68570. }
  68571. scene.workerCollisions = !!parsedData.workerCollisions;
  68572. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68573. if (!container) {
  68574. return false;
  68575. }
  68576. if (parsedData.autoAnimate) {
  68577. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68578. }
  68579. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68580. scene.setActiveCameraByID(parsedData.activeCameraID);
  68581. }
  68582. // Environment texture
  68583. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68584. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68585. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68586. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68587. if (parsedData.environmentTextureRotationY) {
  68588. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68589. }
  68590. scene.environmentTexture = hdrTexture;
  68591. }
  68592. else {
  68593. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68594. if (parsedData.environmentTextureRotationY) {
  68595. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68596. }
  68597. scene.environmentTexture = cubeTexture;
  68598. }
  68599. if (parsedData.createDefaultSkybox === true) {
  68600. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68601. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68602. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68603. }
  68604. }
  68605. // Finish
  68606. return true;
  68607. }
  68608. catch (err) {
  68609. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68610. if (onError) {
  68611. onError(msg, err);
  68612. }
  68613. else {
  68614. BABYLON.Tools.Log(msg);
  68615. throw err;
  68616. }
  68617. }
  68618. finally {
  68619. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68620. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68621. }
  68622. }
  68623. return false;
  68624. },
  68625. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68626. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68627. return container;
  68628. }
  68629. });
  68630. })(BABYLON || (BABYLON = {}));
  68631. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68632. var BABYLON;
  68633. (function (BABYLON) {
  68634. var FilesInput = /** @class */ (function () {
  68635. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68636. this.onProcessFileCallback = function () { return true; };
  68637. this._engine = engine;
  68638. this._currentScene = scene;
  68639. this._sceneLoadedCallback = sceneLoadedCallback;
  68640. this._progressCallback = progressCallback;
  68641. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68642. this._textureLoadingCallback = textureLoadingCallback;
  68643. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68644. this._onReloadCallback = onReloadCallback;
  68645. this._errorCallback = errorCallback;
  68646. }
  68647. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68648. var _this = this;
  68649. if (elementToMonitor) {
  68650. this._elementToMonitor = elementToMonitor;
  68651. this._dragEnterHandler = function (e) { _this.drag(e); };
  68652. this._dragOverHandler = function (e) { _this.drag(e); };
  68653. this._dropHandler = function (e) { _this.drop(e); };
  68654. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68655. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68656. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68657. }
  68658. };
  68659. FilesInput.prototype.dispose = function () {
  68660. if (!this._elementToMonitor) {
  68661. return;
  68662. }
  68663. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68664. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68665. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68666. };
  68667. FilesInput.prototype.renderFunction = function () {
  68668. if (this._additionalRenderLoopLogicCallback) {
  68669. this._additionalRenderLoopLogicCallback();
  68670. }
  68671. if (this._currentScene) {
  68672. if (this._textureLoadingCallback) {
  68673. var remaining = this._currentScene.getWaitingItemsCount();
  68674. if (remaining > 0) {
  68675. this._textureLoadingCallback(remaining);
  68676. }
  68677. }
  68678. this._currentScene.render();
  68679. }
  68680. };
  68681. FilesInput.prototype.drag = function (e) {
  68682. e.stopPropagation();
  68683. e.preventDefault();
  68684. };
  68685. FilesInput.prototype.drop = function (eventDrop) {
  68686. eventDrop.stopPropagation();
  68687. eventDrop.preventDefault();
  68688. this.loadFiles(eventDrop);
  68689. };
  68690. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68691. var _this = this;
  68692. var reader = folder.createReader();
  68693. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68694. reader.readEntries(function (entries) {
  68695. remaining.count += entries.length;
  68696. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68697. var entry = entries_1[_i];
  68698. if (entry.isFile) {
  68699. entry.file(function (file) {
  68700. file.correctName = relativePath + file.name;
  68701. files.push(file);
  68702. if (--remaining.count === 0) {
  68703. callback();
  68704. }
  68705. });
  68706. }
  68707. else if (entry.isDirectory) {
  68708. _this._traverseFolder(entry, files, remaining, callback);
  68709. }
  68710. }
  68711. if (--remaining.count) {
  68712. callback();
  68713. }
  68714. });
  68715. };
  68716. FilesInput.prototype._processFiles = function (files) {
  68717. for (var i = 0; i < files.length; i++) {
  68718. var name = files[i].correctName.toLowerCase();
  68719. var extension = name.split('.').pop();
  68720. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68721. continue;
  68722. }
  68723. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68724. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68725. this._sceneFileToLoad = files[i];
  68726. }
  68727. else {
  68728. FilesInput.FilesToLoad[name] = files[i];
  68729. }
  68730. }
  68731. };
  68732. FilesInput.prototype.loadFiles = function (event) {
  68733. var _this = this;
  68734. if (this._startingProcessingFilesCallback)
  68735. this._startingProcessingFilesCallback();
  68736. // Handling data transfer via drag'n'drop
  68737. if (event && event.dataTransfer && event.dataTransfer.files) {
  68738. this._filesToLoad = event.dataTransfer.files;
  68739. }
  68740. // Handling files from input files
  68741. if (event && event.target && event.target.files) {
  68742. this._filesToLoad = event.target.files;
  68743. }
  68744. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68745. var files_1 = new Array();
  68746. var folders = [];
  68747. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68748. for (var i = 0; i < this._filesToLoad.length; i++) {
  68749. var fileToLoad = this._filesToLoad[i];
  68750. var name_1 = fileToLoad.name.toLowerCase();
  68751. var entry = void 0;
  68752. fileToLoad.correctName = name_1;
  68753. if (items) {
  68754. var item = items[i];
  68755. if (item.getAsEntry) {
  68756. entry = item.getAsEntry();
  68757. }
  68758. else if (item.webkitGetAsEntry) {
  68759. entry = item.webkitGetAsEntry();
  68760. }
  68761. }
  68762. if (!entry) {
  68763. files_1.push(fileToLoad);
  68764. }
  68765. else {
  68766. if (entry.isDirectory) {
  68767. folders.push(entry);
  68768. }
  68769. else {
  68770. files_1.push(fileToLoad);
  68771. }
  68772. }
  68773. }
  68774. if (folders.length === 0) {
  68775. this._processFiles(files_1);
  68776. this._processReload();
  68777. }
  68778. else {
  68779. var remaining = { count: folders.length };
  68780. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68781. var folder = folders_1[_i];
  68782. this._traverseFolder(folder, files_1, remaining, function () {
  68783. _this._processFiles(files_1);
  68784. if (remaining.count === 0) {
  68785. _this._processReload();
  68786. }
  68787. });
  68788. }
  68789. }
  68790. }
  68791. };
  68792. FilesInput.prototype._processReload = function () {
  68793. if (this._onReloadCallback) {
  68794. this._onReloadCallback(this._sceneFileToLoad);
  68795. }
  68796. else {
  68797. this.reload();
  68798. }
  68799. };
  68800. FilesInput.prototype.reload = function () {
  68801. var _this = this;
  68802. // If a scene file has been provided
  68803. if (this._sceneFileToLoad) {
  68804. if (this._currentScene) {
  68805. if (BABYLON.Tools.errorsCount > 0) {
  68806. BABYLON.Tools.ClearLogCache();
  68807. }
  68808. this._engine.stopRenderLoop();
  68809. }
  68810. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68811. if (_this._progressCallback) {
  68812. _this._progressCallback(progress);
  68813. }
  68814. }).then(function (scene) {
  68815. if (_this._currentScene) {
  68816. _this._currentScene.dispose();
  68817. }
  68818. _this._currentScene = scene;
  68819. if (_this._sceneLoadedCallback) {
  68820. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68821. }
  68822. // Wait for textures and shaders to be ready
  68823. _this._currentScene.executeWhenReady(function () {
  68824. _this._engine.runRenderLoop(function () {
  68825. _this.renderFunction();
  68826. });
  68827. });
  68828. }).catch(function (error) {
  68829. if (_this._errorCallback) {
  68830. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68831. }
  68832. });
  68833. }
  68834. else {
  68835. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68836. }
  68837. };
  68838. FilesInput.FilesToLoad = {};
  68839. return FilesInput;
  68840. }());
  68841. BABYLON.FilesInput = FilesInput;
  68842. })(BABYLON || (BABYLON = {}));
  68843. //# sourceMappingURL=babylon.filesInput.js.map
  68844. var BABYLON;
  68845. (function (BABYLON) {
  68846. /**
  68847. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68848. * The underlying implementation relies on an associative array to ensure the best performances.
  68849. * The value can be anything including 'null' but except 'undefined'
  68850. */
  68851. var StringDictionary = /** @class */ (function () {
  68852. function StringDictionary() {
  68853. this._count = 0;
  68854. this._data = {};
  68855. }
  68856. /**
  68857. * This will clear this dictionary and copy the content from the 'source' one.
  68858. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68859. * @param source the dictionary to take the content from and copy to this dictionary
  68860. */
  68861. StringDictionary.prototype.copyFrom = function (source) {
  68862. var _this = this;
  68863. this.clear();
  68864. source.forEach(function (t, v) { return _this.add(t, v); });
  68865. };
  68866. /**
  68867. * Get a value based from its key
  68868. * @param key the given key to get the matching value from
  68869. * @return the value if found, otherwise undefined is returned
  68870. */
  68871. StringDictionary.prototype.get = function (key) {
  68872. var val = this._data[key];
  68873. if (val !== undefined) {
  68874. return val;
  68875. }
  68876. return undefined;
  68877. };
  68878. /**
  68879. * Get a value from its key or add it if it doesn't exist.
  68880. * This method will ensure you that a given key/data will be present in the dictionary.
  68881. * @param key the given key to get the matching value from
  68882. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68883. * The factory will only be invoked if there's no data for the given key.
  68884. * @return the value corresponding to the key.
  68885. */
  68886. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68887. var val = this.get(key);
  68888. if (val !== undefined) {
  68889. return val;
  68890. }
  68891. val = factory(key);
  68892. if (val) {
  68893. this.add(key, val);
  68894. }
  68895. return val;
  68896. };
  68897. /**
  68898. * Get a value from its key if present in the dictionary otherwise add it
  68899. * @param key the key to get the value from
  68900. * @param val if there's no such key/value pair in the dictionary add it with this value
  68901. * @return the value corresponding to the key
  68902. */
  68903. StringDictionary.prototype.getOrAdd = function (key, val) {
  68904. var curVal = this.get(key);
  68905. if (curVal !== undefined) {
  68906. return curVal;
  68907. }
  68908. this.add(key, val);
  68909. return val;
  68910. };
  68911. /**
  68912. * Check if there's a given key in the dictionary
  68913. * @param key the key to check for
  68914. * @return true if the key is present, false otherwise
  68915. */
  68916. StringDictionary.prototype.contains = function (key) {
  68917. return this._data[key] !== undefined;
  68918. };
  68919. /**
  68920. * Add a new key and its corresponding value
  68921. * @param key the key to add
  68922. * @param value the value corresponding to the key
  68923. * @return true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary
  68924. */
  68925. StringDictionary.prototype.add = function (key, value) {
  68926. if (this._data[key] !== undefined) {
  68927. return false;
  68928. }
  68929. this._data[key] = value;
  68930. ++this._count;
  68931. return true;
  68932. };
  68933. StringDictionary.prototype.set = function (key, value) {
  68934. if (this._data[key] === undefined) {
  68935. return false;
  68936. }
  68937. this._data[key] = value;
  68938. return true;
  68939. };
  68940. /**
  68941. * Get the element of the given key and remove it from the dictionary
  68942. * @param key
  68943. */
  68944. StringDictionary.prototype.getAndRemove = function (key) {
  68945. var val = this.get(key);
  68946. if (val !== undefined) {
  68947. delete this._data[key];
  68948. --this._count;
  68949. return val;
  68950. }
  68951. return null;
  68952. };
  68953. /**
  68954. * Remove a key/value from the dictionary.
  68955. * @param key the key to remove
  68956. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68957. */
  68958. StringDictionary.prototype.remove = function (key) {
  68959. if (this.contains(key)) {
  68960. delete this._data[key];
  68961. --this._count;
  68962. return true;
  68963. }
  68964. return false;
  68965. };
  68966. /**
  68967. * Clear the whole content of the dictionary
  68968. */
  68969. StringDictionary.prototype.clear = function () {
  68970. this._data = {};
  68971. this._count = 0;
  68972. };
  68973. Object.defineProperty(StringDictionary.prototype, "count", {
  68974. get: function () {
  68975. return this._count;
  68976. },
  68977. enumerable: true,
  68978. configurable: true
  68979. });
  68980. /**
  68981. * Execute a callback on each key/val of the dictionary.
  68982. * Note that you can remove any element in this dictionary in the callback implementation
  68983. * @param callback the callback to execute on a given key/value pair
  68984. */
  68985. StringDictionary.prototype.forEach = function (callback) {
  68986. for (var cur in this._data) {
  68987. var val = this._data[cur];
  68988. callback(cur, val);
  68989. }
  68990. };
  68991. /**
  68992. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68993. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68994. * Note that you can remove any element in this dictionary in the callback implementation
  68995. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68996. */
  68997. StringDictionary.prototype.first = function (callback) {
  68998. for (var cur in this._data) {
  68999. var val = this._data[cur];
  69000. var res = callback(cur, val);
  69001. if (res) {
  69002. return res;
  69003. }
  69004. }
  69005. return null;
  69006. };
  69007. return StringDictionary;
  69008. }());
  69009. BABYLON.StringDictionary = StringDictionary;
  69010. })(BABYLON || (BABYLON = {}));
  69011. //# sourceMappingURL=babylon.stringDictionary.js.map
  69012. var BABYLON;
  69013. (function (BABYLON) {
  69014. var Tags = /** @class */ (function () {
  69015. function Tags() {
  69016. }
  69017. Tags.EnableFor = function (obj) {
  69018. obj._tags = obj._tags || {};
  69019. obj.hasTags = function () {
  69020. return Tags.HasTags(obj);
  69021. };
  69022. obj.addTags = function (tagsString) {
  69023. return Tags.AddTagsTo(obj, tagsString);
  69024. };
  69025. obj.removeTags = function (tagsString) {
  69026. return Tags.RemoveTagsFrom(obj, tagsString);
  69027. };
  69028. obj.matchesTagsQuery = function (tagsQuery) {
  69029. return Tags.MatchesQuery(obj, tagsQuery);
  69030. };
  69031. };
  69032. Tags.DisableFor = function (obj) {
  69033. delete obj._tags;
  69034. delete obj.hasTags;
  69035. delete obj.addTags;
  69036. delete obj.removeTags;
  69037. delete obj.matchesTagsQuery;
  69038. };
  69039. Tags.HasTags = function (obj) {
  69040. if (!obj._tags) {
  69041. return false;
  69042. }
  69043. return !BABYLON.Tools.IsEmpty(obj._tags);
  69044. };
  69045. Tags.GetTags = function (obj, asString) {
  69046. if (asString === void 0) { asString = true; }
  69047. if (!obj._tags) {
  69048. return null;
  69049. }
  69050. if (asString) {
  69051. var tagsArray = [];
  69052. for (var tag in obj._tags) {
  69053. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  69054. tagsArray.push(tag);
  69055. }
  69056. }
  69057. return tagsArray.join(" ");
  69058. }
  69059. else {
  69060. return obj._tags;
  69061. }
  69062. };
  69063. // the tags 'true' and 'false' are reserved and cannot be used as tags
  69064. // a tag cannot start with '||', '&&', and '!'
  69065. // it cannot contain whitespaces
  69066. Tags.AddTagsTo = function (obj, tagsString) {
  69067. if (!tagsString) {
  69068. return;
  69069. }
  69070. if (typeof tagsString !== "string") {
  69071. return;
  69072. }
  69073. var tags = tagsString.split(" ");
  69074. tags.forEach(function (tag, index, array) {
  69075. Tags._AddTagTo(obj, tag);
  69076. });
  69077. };
  69078. Tags._AddTagTo = function (obj, tag) {
  69079. tag = tag.trim();
  69080. if (tag === "" || tag === "true" || tag === "false") {
  69081. return;
  69082. }
  69083. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  69084. return;
  69085. }
  69086. Tags.EnableFor(obj);
  69087. obj._tags[tag] = true;
  69088. };
  69089. Tags.RemoveTagsFrom = function (obj, tagsString) {
  69090. if (!Tags.HasTags(obj)) {
  69091. return;
  69092. }
  69093. var tags = tagsString.split(" ");
  69094. for (var t in tags) {
  69095. Tags._RemoveTagFrom(obj, tags[t]);
  69096. }
  69097. };
  69098. Tags._RemoveTagFrom = function (obj, tag) {
  69099. delete obj._tags[tag];
  69100. };
  69101. Tags.MatchesQuery = function (obj, tagsQuery) {
  69102. if (tagsQuery === undefined) {
  69103. return true;
  69104. }
  69105. if (tagsQuery === "") {
  69106. return Tags.HasTags(obj);
  69107. }
  69108. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  69109. };
  69110. return Tags;
  69111. }());
  69112. BABYLON.Tags = Tags;
  69113. })(BABYLON || (BABYLON = {}));
  69114. //# sourceMappingURL=babylon.tags.js.map
  69115. var BABYLON;
  69116. (function (BABYLON) {
  69117. /**
  69118. * Class used to evalaute queries containing `and` and `or` operators
  69119. */
  69120. var AndOrNotEvaluator = /** @class */ (function () {
  69121. function AndOrNotEvaluator() {
  69122. }
  69123. /**
  69124. * Evaluate a query
  69125. * @param query defines the query to evaluate
  69126. * @param evaluateCallback defines the callback used to filter result
  69127. * @returns true if the query matches
  69128. */
  69129. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  69130. if (!query.match(/\([^\(\)]*\)/g)) {
  69131. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  69132. }
  69133. else {
  69134. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  69135. // remove parenthesis
  69136. r = r.slice(1, r.length - 1);
  69137. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  69138. });
  69139. }
  69140. if (query === "true") {
  69141. return true;
  69142. }
  69143. if (query === "false") {
  69144. return false;
  69145. }
  69146. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  69147. };
  69148. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  69149. evaluateCallback = evaluateCallback || (function (r) {
  69150. return r === "true" ? true : false;
  69151. });
  69152. var result;
  69153. var or = parenthesisContent.split("||");
  69154. for (var i in or) {
  69155. if (or.hasOwnProperty(i)) {
  69156. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  69157. var and = ori.split("&&");
  69158. if (and.length > 1) {
  69159. for (var j = 0; j < and.length; ++j) {
  69160. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  69161. if (andj !== "true" && andj !== "false") {
  69162. if (andj[0] === "!") {
  69163. result = !evaluateCallback(andj.substring(1));
  69164. }
  69165. else {
  69166. result = evaluateCallback(andj);
  69167. }
  69168. }
  69169. else {
  69170. result = andj === "true" ? true : false;
  69171. }
  69172. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  69173. ori = "false";
  69174. break;
  69175. }
  69176. }
  69177. }
  69178. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  69179. result = true;
  69180. break;
  69181. }
  69182. // result equals false (or undefined)
  69183. if (ori !== "true" && ori !== "false") {
  69184. if (ori[0] === "!") {
  69185. result = !evaluateCallback(ori.substring(1));
  69186. }
  69187. else {
  69188. result = evaluateCallback(ori);
  69189. }
  69190. }
  69191. else {
  69192. result = ori === "true" ? true : false;
  69193. }
  69194. }
  69195. }
  69196. // the whole parenthesis scope is replaced by 'true' or 'false'
  69197. return result ? "true" : "false";
  69198. };
  69199. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  69200. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  69201. // remove whitespaces
  69202. r = r.replace(/[\s]/g, function () { return ""; });
  69203. return r.length % 2 ? "!" : "";
  69204. });
  69205. booleanString = booleanString.trim();
  69206. if (booleanString === "!true") {
  69207. booleanString = "false";
  69208. }
  69209. else if (booleanString === "!false") {
  69210. booleanString = "true";
  69211. }
  69212. return booleanString;
  69213. };
  69214. return AndOrNotEvaluator;
  69215. }());
  69216. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  69217. })(BABYLON || (BABYLON = {}));
  69218. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  69219. var BABYLON;
  69220. (function (BABYLON) {
  69221. /**
  69222. * Class used to enable access to IndexedDB
  69223. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  69224. */
  69225. var Database = /** @class */ (function () {
  69226. /**
  69227. * Creates a new Database
  69228. * @param urlToScene defines the url to load the scene
  69229. * @param callbackManifestChecked defines the callback to use when manifest is checked
  69230. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  69231. */
  69232. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  69233. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  69234. var _this = this;
  69235. // Handling various flavors of prefixed version of IndexedDB
  69236. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  69237. this.callbackManifestChecked = callbackManifestChecked;
  69238. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  69239. this.db = null;
  69240. this._enableSceneOffline = false;
  69241. this._enableTexturesOffline = false;
  69242. this.manifestVersionFound = 0;
  69243. this.mustUpdateRessources = false;
  69244. this.hasReachedQuota = false;
  69245. if (!Database.IDBStorageEnabled) {
  69246. this.callbackManifestChecked(true);
  69247. }
  69248. else {
  69249. if (disableManifestCheck) {
  69250. this._enableSceneOffline = true;
  69251. this._enableTexturesOffline = true;
  69252. this.manifestVersionFound = 1;
  69253. BABYLON.Tools.SetImmediate(function () {
  69254. _this.callbackManifestChecked(true);
  69255. });
  69256. }
  69257. else {
  69258. this._checkManifestFile();
  69259. }
  69260. }
  69261. }
  69262. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  69263. /**
  69264. * Gets a boolean indicating if scene must be saved in the database
  69265. */
  69266. get: function () {
  69267. return this._enableSceneOffline;
  69268. },
  69269. enumerable: true,
  69270. configurable: true
  69271. });
  69272. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69273. /**
  69274. * Gets a boolean indicating if textures must be saved in the database
  69275. */
  69276. get: function () {
  69277. return this._enableTexturesOffline;
  69278. },
  69279. enumerable: true,
  69280. configurable: true
  69281. });
  69282. Database.prototype._checkManifestFile = function () {
  69283. var _this = this;
  69284. var noManifestFile = function () {
  69285. _this._enableSceneOffline = false;
  69286. _this._enableTexturesOffline = false;
  69287. _this.callbackManifestChecked(false);
  69288. };
  69289. var timeStampUsed = false;
  69290. var manifestURL = this.currentSceneUrl + ".manifest";
  69291. var xhr = new XMLHttpRequest();
  69292. if (navigator.onLine) {
  69293. // Adding a timestamp to by-pass browsers' cache
  69294. timeStampUsed = true;
  69295. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69296. }
  69297. xhr.open("GET", manifestURL, true);
  69298. xhr.addEventListener("load", function () {
  69299. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69300. try {
  69301. var manifestFile = JSON.parse(xhr.response);
  69302. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69303. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69304. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69305. _this.manifestVersionFound = manifestFile.version;
  69306. }
  69307. if (_this.callbackManifestChecked) {
  69308. _this.callbackManifestChecked(true);
  69309. }
  69310. }
  69311. catch (ex) {
  69312. noManifestFile();
  69313. }
  69314. }
  69315. else {
  69316. noManifestFile();
  69317. }
  69318. }, false);
  69319. xhr.addEventListener("error", function (event) {
  69320. if (timeStampUsed) {
  69321. timeStampUsed = false;
  69322. // Let's retry without the timeStamp
  69323. // It could fail when coupled with HTML5 Offline API
  69324. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69325. xhr.open("GET", retryManifestURL, true);
  69326. xhr.send();
  69327. }
  69328. else {
  69329. noManifestFile();
  69330. }
  69331. }, false);
  69332. try {
  69333. xhr.send();
  69334. }
  69335. catch (ex) {
  69336. BABYLON.Tools.Error("Error on XHR send request.");
  69337. this.callbackManifestChecked(false);
  69338. }
  69339. };
  69340. /**
  69341. * Open the database and make it available
  69342. * @param successCallback defines the callback to call on success
  69343. * @param errorCallback defines the callback to call on error
  69344. */
  69345. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69346. var _this = this;
  69347. var handleError = function () {
  69348. _this.isSupported = false;
  69349. if (errorCallback)
  69350. errorCallback();
  69351. };
  69352. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69353. // Your browser doesn't support IndexedDB
  69354. this.isSupported = false;
  69355. if (errorCallback)
  69356. errorCallback();
  69357. }
  69358. else {
  69359. // If the DB hasn't been opened or created yet
  69360. if (!this.db) {
  69361. this.hasReachedQuota = false;
  69362. this.isSupported = true;
  69363. var request = this.idbFactory.open("babylonjs", 1);
  69364. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69365. request.onerror = function (event) {
  69366. handleError();
  69367. };
  69368. // executes when a version change transaction cannot complete due to other active transactions
  69369. request.onblocked = function (event) {
  69370. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69371. handleError();
  69372. };
  69373. // DB has been opened successfully
  69374. request.onsuccess = function (event) {
  69375. _this.db = request.result;
  69376. successCallback();
  69377. };
  69378. // Initialization of the DB. Creating Scenes & Textures stores
  69379. request.onupgradeneeded = function (event) {
  69380. _this.db = (event.target).result;
  69381. if (_this.db) {
  69382. try {
  69383. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69384. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69385. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69386. }
  69387. catch (ex) {
  69388. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69389. handleError();
  69390. }
  69391. }
  69392. };
  69393. }
  69394. // DB has already been created and opened
  69395. else {
  69396. if (successCallback)
  69397. successCallback();
  69398. }
  69399. }
  69400. };
  69401. /**
  69402. * Loads an image from the database
  69403. * @param url defines the url to load from
  69404. * @param image defines the target DOM image
  69405. */
  69406. Database.prototype.loadImageFromDB = function (url, image) {
  69407. var _this = this;
  69408. var completeURL = Database._ReturnFullUrlLocation(url);
  69409. var saveAndLoadImage = function () {
  69410. if (!_this.hasReachedQuota && _this.db !== null) {
  69411. // the texture is not yet in the DB, let's try to save it
  69412. _this._saveImageIntoDBAsync(completeURL, image);
  69413. }
  69414. // If the texture is not in the DB and we've reached the DB quota limit
  69415. // let's load it directly from the web
  69416. else {
  69417. image.src = url;
  69418. }
  69419. };
  69420. if (!this.mustUpdateRessources) {
  69421. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69422. }
  69423. // First time we're download the images or update requested in the manifest file by a version change
  69424. else {
  69425. saveAndLoadImage();
  69426. }
  69427. };
  69428. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69429. if (this.isSupported && this.db !== null) {
  69430. var texture;
  69431. var transaction = this.db.transaction(["textures"]);
  69432. transaction.onabort = function (event) {
  69433. image.src = url;
  69434. };
  69435. transaction.oncomplete = function (event) {
  69436. var blobTextureURL;
  69437. if (texture) {
  69438. var URL = window.URL || window.webkitURL;
  69439. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69440. image.onerror = function () {
  69441. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69442. image.src = url;
  69443. };
  69444. image.src = blobTextureURL;
  69445. }
  69446. else {
  69447. notInDBCallback();
  69448. }
  69449. };
  69450. var getRequest = transaction.objectStore("textures").get(url);
  69451. getRequest.onsuccess = function (event) {
  69452. texture = (event.target).result;
  69453. };
  69454. getRequest.onerror = function (event) {
  69455. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69456. image.src = url;
  69457. };
  69458. }
  69459. else {
  69460. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69461. image.src = url;
  69462. }
  69463. };
  69464. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69465. var _this = this;
  69466. if (this.isSupported) {
  69467. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69468. var generateBlobUrl = function () {
  69469. var blobTextureURL;
  69470. if (blob) {
  69471. var URL = window.URL || window.webkitURL;
  69472. try {
  69473. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69474. }
  69475. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69476. catch (ex) {
  69477. blobTextureURL = URL.createObjectURL(blob);
  69478. }
  69479. }
  69480. if (blobTextureURL) {
  69481. image.src = blobTextureURL;
  69482. }
  69483. };
  69484. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69485. var xhr = new XMLHttpRequest(), blob;
  69486. xhr.open("GET", url, true);
  69487. xhr.responseType = "blob";
  69488. xhr.addEventListener("load", function () {
  69489. if (xhr.status === 200 && _this.db) {
  69490. // Blob as response (XHR2)
  69491. blob = xhr.response;
  69492. var transaction = _this.db.transaction(["textures"], "readwrite");
  69493. // the transaction could abort because of a QuotaExceededError error
  69494. transaction.onabort = function (event) {
  69495. try {
  69496. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69497. var srcElement = (event.srcElement || event.target);
  69498. var error = srcElement.error;
  69499. if (error && error.name === "QuotaExceededError") {
  69500. _this.hasReachedQuota = true;
  69501. }
  69502. }
  69503. catch (ex) { }
  69504. generateBlobUrl();
  69505. };
  69506. transaction.oncomplete = function (event) {
  69507. generateBlobUrl();
  69508. };
  69509. var newTexture = { textureUrl: url, data: blob };
  69510. try {
  69511. // Put the blob into the dabase
  69512. var addRequest = transaction.objectStore("textures").put(newTexture);
  69513. addRequest.onsuccess = function (event) {
  69514. };
  69515. addRequest.onerror = function (event) {
  69516. generateBlobUrl();
  69517. };
  69518. }
  69519. catch (ex) {
  69520. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69521. if (ex.code === 25) {
  69522. Database.IsUASupportingBlobStorage = false;
  69523. }
  69524. image.src = url;
  69525. }
  69526. }
  69527. else {
  69528. image.src = url;
  69529. }
  69530. }, false);
  69531. xhr.addEventListener("error", function (event) {
  69532. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69533. image.src = url;
  69534. }, false);
  69535. xhr.send();
  69536. }
  69537. else {
  69538. image.src = url;
  69539. }
  69540. }
  69541. else {
  69542. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69543. image.src = url;
  69544. }
  69545. };
  69546. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69547. var _this = this;
  69548. var updateVersion = function () {
  69549. // the version is not yet in the DB or we need to update it
  69550. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69551. };
  69552. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69553. };
  69554. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69555. var _this = this;
  69556. if (this.isSupported && this.db) {
  69557. var version;
  69558. try {
  69559. var transaction = this.db.transaction(["versions"]);
  69560. transaction.oncomplete = function (event) {
  69561. if (version) {
  69562. // If the version in the JSON file is different from the version in DB
  69563. if (_this.manifestVersionFound !== version.data) {
  69564. _this.mustUpdateRessources = true;
  69565. updateInDBCallback();
  69566. }
  69567. else {
  69568. callback(version.data);
  69569. }
  69570. }
  69571. // version was not found in DB
  69572. else {
  69573. _this.mustUpdateRessources = true;
  69574. updateInDBCallback();
  69575. }
  69576. };
  69577. transaction.onabort = function (event) {
  69578. callback(-1);
  69579. };
  69580. var getRequest = transaction.objectStore("versions").get(url);
  69581. getRequest.onsuccess = function (event) {
  69582. version = (event.target).result;
  69583. };
  69584. getRequest.onerror = function (event) {
  69585. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69586. callback(-1);
  69587. };
  69588. }
  69589. catch (ex) {
  69590. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69591. callback(-1);
  69592. }
  69593. }
  69594. else {
  69595. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69596. callback(-1);
  69597. }
  69598. };
  69599. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69600. var _this = this;
  69601. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69602. try {
  69603. // Open a transaction to the database
  69604. var transaction = this.db.transaction(["versions"], "readwrite");
  69605. // the transaction could abort because of a QuotaExceededError error
  69606. transaction.onabort = function (event) {
  69607. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69608. var error = event.srcElement['error'];
  69609. if (error && error.name === "QuotaExceededError") {
  69610. _this.hasReachedQuota = true;
  69611. }
  69612. }
  69613. catch (ex) { }
  69614. callback(-1);
  69615. };
  69616. transaction.oncomplete = function (event) {
  69617. callback(_this.manifestVersionFound);
  69618. };
  69619. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69620. // Put the scene into the database
  69621. var addRequest = transaction.objectStore("versions").put(newVersion);
  69622. addRequest.onsuccess = function (event) {
  69623. };
  69624. addRequest.onerror = function (event) {
  69625. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69626. };
  69627. }
  69628. catch (ex) {
  69629. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69630. callback(-1);
  69631. }
  69632. }
  69633. else {
  69634. callback(-1);
  69635. }
  69636. };
  69637. /**
  69638. * Loads a file from database
  69639. * @param url defines the URL to load from
  69640. * @param sceneLoaded defines a callback to call on success
  69641. * @param progressCallBack defines a callback to call when progress changed
  69642. * @param errorCallback defines a callback to call on error
  69643. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69644. */
  69645. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69646. var _this = this;
  69647. var completeUrl = Database._ReturnFullUrlLocation(url);
  69648. var saveAndLoadFile = function () {
  69649. // the scene is not yet in the DB, let's try to save it
  69650. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69651. };
  69652. this._checkVersionFromDB(completeUrl, function (version) {
  69653. if (version !== -1) {
  69654. if (!_this.mustUpdateRessources) {
  69655. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69656. }
  69657. else {
  69658. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69659. }
  69660. }
  69661. else {
  69662. if (errorCallback) {
  69663. errorCallback();
  69664. }
  69665. }
  69666. });
  69667. };
  69668. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69669. if (this.isSupported && this.db) {
  69670. var targetStore;
  69671. if (url.indexOf(".babylon") !== -1) {
  69672. targetStore = "scenes";
  69673. }
  69674. else {
  69675. targetStore = "textures";
  69676. }
  69677. var file;
  69678. var transaction = this.db.transaction([targetStore]);
  69679. transaction.oncomplete = function (event) {
  69680. if (file) {
  69681. callback(file.data);
  69682. }
  69683. // file was not found in DB
  69684. else {
  69685. notInDBCallback();
  69686. }
  69687. };
  69688. transaction.onabort = function (event) {
  69689. notInDBCallback();
  69690. };
  69691. var getRequest = transaction.objectStore(targetStore).get(url);
  69692. getRequest.onsuccess = function (event) {
  69693. file = (event.target).result;
  69694. };
  69695. getRequest.onerror = function (event) {
  69696. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69697. notInDBCallback();
  69698. };
  69699. }
  69700. else {
  69701. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69702. callback();
  69703. }
  69704. };
  69705. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69706. var _this = this;
  69707. if (this.isSupported) {
  69708. var targetStore;
  69709. if (url.indexOf(".babylon") !== -1) {
  69710. targetStore = "scenes";
  69711. }
  69712. else {
  69713. targetStore = "textures";
  69714. }
  69715. // Create XHR
  69716. var xhr = new XMLHttpRequest();
  69717. var fileData;
  69718. xhr.open("GET", url, true);
  69719. if (useArrayBuffer) {
  69720. xhr.responseType = "arraybuffer";
  69721. }
  69722. if (progressCallback) {
  69723. xhr.onprogress = progressCallback;
  69724. }
  69725. xhr.addEventListener("load", function () {
  69726. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69727. // Blob as response (XHR2)
  69728. //fileData = xhr.responseText;
  69729. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69730. if (!_this.hasReachedQuota && _this.db) {
  69731. // Open a transaction to the database
  69732. var transaction = _this.db.transaction([targetStore], "readwrite");
  69733. // the transaction could abort because of a QuotaExceededError error
  69734. transaction.onabort = function (event) {
  69735. try {
  69736. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69737. var error = event.srcElement['error'];
  69738. if (error && error.name === "QuotaExceededError") {
  69739. _this.hasReachedQuota = true;
  69740. }
  69741. }
  69742. catch (ex) { }
  69743. callback(fileData);
  69744. };
  69745. transaction.oncomplete = function (event) {
  69746. callback(fileData);
  69747. };
  69748. var newFile;
  69749. if (targetStore === "scenes") {
  69750. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69751. }
  69752. else {
  69753. newFile = { textureUrl: url, data: fileData };
  69754. }
  69755. try {
  69756. // Put the scene into the database
  69757. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69758. addRequest.onsuccess = function (event) {
  69759. };
  69760. addRequest.onerror = function (event) {
  69761. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69762. };
  69763. }
  69764. catch (ex) {
  69765. callback(fileData);
  69766. }
  69767. }
  69768. else {
  69769. callback(fileData);
  69770. }
  69771. }
  69772. else {
  69773. callback();
  69774. }
  69775. }, false);
  69776. xhr.addEventListener("error", function (event) {
  69777. BABYLON.Tools.Error("error on XHR request.");
  69778. callback();
  69779. }, false);
  69780. xhr.send();
  69781. }
  69782. else {
  69783. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69784. callback();
  69785. }
  69786. };
  69787. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69788. Database.IsUASupportingBlobStorage = true;
  69789. /** Gets a boolean indicating if Database storate is enabled */
  69790. Database.IDBStorageEnabled = true;
  69791. Database._ParseURL = function (url) {
  69792. var a = document.createElement('a');
  69793. a.href = url;
  69794. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69795. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69796. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69797. return absLocation;
  69798. };
  69799. Database._ReturnFullUrlLocation = function (url) {
  69800. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69801. return (Database._ParseURL(window.location.href) + url);
  69802. }
  69803. else {
  69804. return url;
  69805. }
  69806. };
  69807. return Database;
  69808. }());
  69809. BABYLON.Database = Database;
  69810. })(BABYLON || (BABYLON = {}));
  69811. //# sourceMappingURL=babylon.database.js.map
  69812. var BABYLON;
  69813. (function (BABYLON) {
  69814. var FresnelParameters = /** @class */ (function () {
  69815. function FresnelParameters() {
  69816. this._isEnabled = true;
  69817. this.leftColor = BABYLON.Color3.White();
  69818. this.rightColor = BABYLON.Color3.Black();
  69819. this.bias = 0;
  69820. this.power = 1;
  69821. }
  69822. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69823. get: function () {
  69824. return this._isEnabled;
  69825. },
  69826. set: function (value) {
  69827. if (this._isEnabled === value) {
  69828. return;
  69829. }
  69830. this._isEnabled = value;
  69831. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69832. },
  69833. enumerable: true,
  69834. configurable: true
  69835. });
  69836. FresnelParameters.prototype.clone = function () {
  69837. var newFresnelParameters = new FresnelParameters();
  69838. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69839. return newFresnelParameters;
  69840. };
  69841. FresnelParameters.prototype.serialize = function () {
  69842. var serializationObject = {};
  69843. serializationObject.isEnabled = this.isEnabled;
  69844. serializationObject.leftColor = this.leftColor.asArray();
  69845. serializationObject.rightColor = this.rightColor.asArray();
  69846. serializationObject.bias = this.bias;
  69847. serializationObject.power = this.power;
  69848. return serializationObject;
  69849. };
  69850. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69851. var fresnelParameters = new FresnelParameters();
  69852. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69853. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69854. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69855. fresnelParameters.bias = parsedFresnelParameters.bias;
  69856. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69857. return fresnelParameters;
  69858. };
  69859. return FresnelParameters;
  69860. }());
  69861. BABYLON.FresnelParameters = FresnelParameters;
  69862. })(BABYLON || (BABYLON = {}));
  69863. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69864. var BABYLON;
  69865. (function (BABYLON) {
  69866. var MultiMaterial = /** @class */ (function (_super) {
  69867. __extends(MultiMaterial, _super);
  69868. function MultiMaterial(name, scene) {
  69869. var _this = _super.call(this, name, scene, true) || this;
  69870. scene.multiMaterials.push(_this);
  69871. _this.subMaterials = new Array();
  69872. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69873. return _this;
  69874. }
  69875. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69876. get: function () {
  69877. return this._subMaterials;
  69878. },
  69879. set: function (value) {
  69880. this._subMaterials = value;
  69881. this._hookArray(value);
  69882. },
  69883. enumerable: true,
  69884. configurable: true
  69885. });
  69886. MultiMaterial.prototype._hookArray = function (array) {
  69887. var _this = this;
  69888. var oldPush = array.push;
  69889. array.push = function () {
  69890. var items = [];
  69891. for (var _i = 0; _i < arguments.length; _i++) {
  69892. items[_i] = arguments[_i];
  69893. }
  69894. var result = oldPush.apply(array, items);
  69895. _this._markAllSubMeshesAsTexturesDirty();
  69896. return result;
  69897. };
  69898. var oldSplice = array.splice;
  69899. array.splice = function (index, deleteCount) {
  69900. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69901. _this._markAllSubMeshesAsTexturesDirty();
  69902. return deleted;
  69903. };
  69904. };
  69905. // Properties
  69906. MultiMaterial.prototype.getSubMaterial = function (index) {
  69907. if (index < 0 || index >= this.subMaterials.length) {
  69908. return this.getScene().defaultMaterial;
  69909. }
  69910. return this.subMaterials[index];
  69911. };
  69912. MultiMaterial.prototype.getActiveTextures = function () {
  69913. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69914. if (subMaterial) {
  69915. return subMaterial.getActiveTextures();
  69916. }
  69917. else {
  69918. return [];
  69919. }
  69920. }));
  69921. var _a;
  69922. };
  69923. // Methods
  69924. MultiMaterial.prototype.getClassName = function () {
  69925. return "MultiMaterial";
  69926. };
  69927. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69928. for (var index = 0; index < this.subMaterials.length; index++) {
  69929. var subMaterial = this.subMaterials[index];
  69930. if (subMaterial) {
  69931. if (subMaterial.storeEffectOnSubMeshes) {
  69932. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69933. return false;
  69934. }
  69935. continue;
  69936. }
  69937. if (!subMaterial.isReady(mesh)) {
  69938. return false;
  69939. }
  69940. }
  69941. }
  69942. return true;
  69943. };
  69944. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69945. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69946. for (var index = 0; index < this.subMaterials.length; index++) {
  69947. var subMaterial = null;
  69948. var current = this.subMaterials[index];
  69949. if (cloneChildren && current) {
  69950. subMaterial = current.clone(name + "-" + current.name);
  69951. }
  69952. else {
  69953. subMaterial = this.subMaterials[index];
  69954. }
  69955. newMultiMaterial.subMaterials.push(subMaterial);
  69956. }
  69957. return newMultiMaterial;
  69958. };
  69959. MultiMaterial.prototype.serialize = function () {
  69960. var serializationObject = {};
  69961. serializationObject.name = this.name;
  69962. serializationObject.id = this.id;
  69963. if (BABYLON.Tags) {
  69964. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69965. }
  69966. serializationObject.materials = [];
  69967. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69968. var subMat = this.subMaterials[matIndex];
  69969. if (subMat) {
  69970. serializationObject.materials.push(subMat.id);
  69971. }
  69972. else {
  69973. serializationObject.materials.push(null);
  69974. }
  69975. }
  69976. return serializationObject;
  69977. };
  69978. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69979. var scene = this.getScene();
  69980. if (!scene) {
  69981. return;
  69982. }
  69983. var index = scene.multiMaterials.indexOf(this);
  69984. if (index >= 0) {
  69985. scene.multiMaterials.splice(index, 1);
  69986. }
  69987. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69988. };
  69989. return MultiMaterial;
  69990. }(BABYLON.Material));
  69991. BABYLON.MultiMaterial = MultiMaterial;
  69992. })(BABYLON || (BABYLON = {}));
  69993. //# sourceMappingURL=babylon.multiMaterial.js.map
  69994. var BABYLON;
  69995. (function (BABYLON) {
  69996. var FreeCameraTouchInput = /** @class */ (function () {
  69997. function FreeCameraTouchInput() {
  69998. this._offsetX = null;
  69999. this._offsetY = null;
  70000. this._pointerPressed = new Array();
  70001. this.touchAngularSensibility = 200000.0;
  70002. this.touchMoveSensibility = 250.0;
  70003. }
  70004. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  70005. var _this = this;
  70006. var previousPosition = null;
  70007. if (this._pointerInput === undefined) {
  70008. this._onLostFocus = function (evt) {
  70009. _this._offsetX = null;
  70010. _this._offsetY = null;
  70011. };
  70012. this._pointerInput = function (p, s) {
  70013. var evt = p.event;
  70014. if (evt.pointerType === "mouse") {
  70015. return;
  70016. }
  70017. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  70018. if (!noPreventDefault) {
  70019. evt.preventDefault();
  70020. }
  70021. _this._pointerPressed.push(evt.pointerId);
  70022. if (_this._pointerPressed.length !== 1) {
  70023. return;
  70024. }
  70025. previousPosition = {
  70026. x: evt.clientX,
  70027. y: evt.clientY
  70028. };
  70029. }
  70030. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  70031. if (!noPreventDefault) {
  70032. evt.preventDefault();
  70033. }
  70034. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70035. if (index === -1) {
  70036. return;
  70037. }
  70038. _this._pointerPressed.splice(index, 1);
  70039. if (index != 0) {
  70040. return;
  70041. }
  70042. previousPosition = null;
  70043. _this._offsetX = null;
  70044. _this._offsetY = null;
  70045. }
  70046. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  70047. if (!noPreventDefault) {
  70048. evt.preventDefault();
  70049. }
  70050. if (!previousPosition) {
  70051. return;
  70052. }
  70053. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70054. if (index != 0) {
  70055. return;
  70056. }
  70057. _this._offsetX = evt.clientX - previousPosition.x;
  70058. _this._offsetY = -(evt.clientY - previousPosition.y);
  70059. }
  70060. };
  70061. }
  70062. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  70063. if (this._onLostFocus) {
  70064. element.addEventListener("blur", this._onLostFocus);
  70065. }
  70066. };
  70067. FreeCameraTouchInput.prototype.detachControl = function (element) {
  70068. if (this._pointerInput && element) {
  70069. if (this._observer) {
  70070. this.camera.getScene().onPointerObservable.remove(this._observer);
  70071. this._observer = null;
  70072. }
  70073. if (this._onLostFocus) {
  70074. element.removeEventListener("blur", this._onLostFocus);
  70075. this._onLostFocus = null;
  70076. }
  70077. this._pointerPressed = [];
  70078. this._offsetX = null;
  70079. this._offsetY = null;
  70080. }
  70081. };
  70082. FreeCameraTouchInput.prototype.checkInputs = function () {
  70083. if (this._offsetX && this._offsetY) {
  70084. var camera = this.camera;
  70085. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  70086. if (this._pointerPressed.length > 1) {
  70087. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  70088. }
  70089. else {
  70090. var speed = camera._computeLocalCameraSpeed();
  70091. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  70092. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  70093. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  70094. }
  70095. }
  70096. };
  70097. FreeCameraTouchInput.prototype.getClassName = function () {
  70098. return "FreeCameraTouchInput";
  70099. };
  70100. FreeCameraTouchInput.prototype.getSimpleName = function () {
  70101. return "touch";
  70102. };
  70103. __decorate([
  70104. BABYLON.serialize()
  70105. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  70106. __decorate([
  70107. BABYLON.serialize()
  70108. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  70109. return FreeCameraTouchInput;
  70110. }());
  70111. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  70112. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  70113. })(BABYLON || (BABYLON = {}));
  70114. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  70115. var BABYLON;
  70116. (function (BABYLON) {
  70117. // We're mainly based on the logic defined into the FreeCamera code
  70118. var TouchCamera = /** @class */ (function (_super) {
  70119. __extends(TouchCamera, _super);
  70120. //-- end properties for backward compatibility for inputs
  70121. function TouchCamera(name, position, scene) {
  70122. var _this = _super.call(this, name, position, scene) || this;
  70123. _this.inputs.addTouch();
  70124. _this._setupInputs();
  70125. return _this;
  70126. }
  70127. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  70128. //-- Begin properties for backward compatibility for inputs
  70129. get: function () {
  70130. var touch = this.inputs.attached["touch"];
  70131. if (touch)
  70132. return touch.touchAngularSensibility;
  70133. return 0;
  70134. },
  70135. set: function (value) {
  70136. var touch = this.inputs.attached["touch"];
  70137. if (touch)
  70138. touch.touchAngularSensibility = value;
  70139. },
  70140. enumerable: true,
  70141. configurable: true
  70142. });
  70143. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  70144. get: function () {
  70145. var touch = this.inputs.attached["touch"];
  70146. if (touch)
  70147. return touch.touchMoveSensibility;
  70148. return 0;
  70149. },
  70150. set: function (value) {
  70151. var touch = this.inputs.attached["touch"];
  70152. if (touch)
  70153. touch.touchMoveSensibility = value;
  70154. },
  70155. enumerable: true,
  70156. configurable: true
  70157. });
  70158. TouchCamera.prototype.getClassName = function () {
  70159. return "TouchCamera";
  70160. };
  70161. TouchCamera.prototype._setupInputs = function () {
  70162. var mouse = this.inputs.attached["mouse"];
  70163. if (mouse) {
  70164. mouse.touchEnabled = false;
  70165. }
  70166. };
  70167. return TouchCamera;
  70168. }(BABYLON.FreeCamera));
  70169. BABYLON.TouchCamera = TouchCamera;
  70170. })(BABYLON || (BABYLON = {}));
  70171. //# sourceMappingURL=babylon.touchCamera.js.map
  70172. var BABYLON;
  70173. (function (BABYLON) {
  70174. var ProceduralTexture = /** @class */ (function (_super) {
  70175. __extends(ProceduralTexture, _super);
  70176. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  70177. if (fallbackTexture === void 0) { fallbackTexture = null; }
  70178. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70179. if (isCube === void 0) { isCube = false; }
  70180. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70181. _this.isCube = isCube;
  70182. _this.isEnabled = true;
  70183. _this._currentRefreshId = -1;
  70184. _this._refreshRate = 1;
  70185. _this._vertexBuffers = {};
  70186. _this._uniforms = new Array();
  70187. _this._samplers = new Array();
  70188. _this._textures = {};
  70189. _this._floats = {};
  70190. _this._floatsArrays = {};
  70191. _this._colors3 = {};
  70192. _this._colors4 = {};
  70193. _this._vectors2 = {};
  70194. _this._vectors3 = {};
  70195. _this._matrices = {};
  70196. _this._fallbackTextureUsed = false;
  70197. scene.proceduralTextures.push(_this);
  70198. _this._engine = scene.getEngine();
  70199. _this.name = name;
  70200. _this.isRenderTarget = true;
  70201. _this._size = size;
  70202. _this._generateMipMaps = generateMipMaps;
  70203. _this.setFragment(fragment);
  70204. _this._fallbackTexture = fallbackTexture;
  70205. if (isCube) {
  70206. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  70207. _this.setFloat("face", 0);
  70208. }
  70209. else {
  70210. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  70211. }
  70212. // VBO
  70213. var vertices = [];
  70214. vertices.push(1, 1);
  70215. vertices.push(-1, 1);
  70216. vertices.push(-1, -1);
  70217. vertices.push(1, -1);
  70218. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70219. _this._createIndexBuffer();
  70220. return _this;
  70221. }
  70222. ProceduralTexture.prototype._createIndexBuffer = function () {
  70223. var engine = this._engine;
  70224. // Indices
  70225. var indices = [];
  70226. indices.push(0);
  70227. indices.push(1);
  70228. indices.push(2);
  70229. indices.push(0);
  70230. indices.push(2);
  70231. indices.push(3);
  70232. this._indexBuffer = engine.createIndexBuffer(indices);
  70233. };
  70234. ProceduralTexture.prototype._rebuild = function () {
  70235. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70236. if (vb) {
  70237. vb._rebuild();
  70238. }
  70239. this._createIndexBuffer();
  70240. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70241. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70242. }
  70243. };
  70244. ProceduralTexture.prototype.reset = function () {
  70245. if (this._effect === undefined) {
  70246. return;
  70247. }
  70248. var engine = this._engine;
  70249. engine._releaseEffect(this._effect);
  70250. };
  70251. ProceduralTexture.prototype.isReady = function () {
  70252. var _this = this;
  70253. var engine = this._engine;
  70254. var shaders;
  70255. if (!this._fragment) {
  70256. return false;
  70257. }
  70258. if (this._fallbackTextureUsed) {
  70259. return true;
  70260. }
  70261. if (this._fragment.fragmentElement !== undefined) {
  70262. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  70263. }
  70264. else {
  70265. shaders = { vertex: "procedural", fragment: this._fragment };
  70266. }
  70267. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70268. _this.releaseInternalTexture();
  70269. if (_this._fallbackTexture) {
  70270. _this._texture = _this._fallbackTexture._texture;
  70271. if (_this._texture) {
  70272. _this._texture.incrementReferences();
  70273. }
  70274. }
  70275. _this._fallbackTextureUsed = true;
  70276. });
  70277. return this._effect.isReady();
  70278. };
  70279. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70280. this._currentRefreshId = -1;
  70281. };
  70282. ProceduralTexture.prototype.setFragment = function (fragment) {
  70283. this._fragment = fragment;
  70284. };
  70285. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70286. get: function () {
  70287. return this._refreshRate;
  70288. },
  70289. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70290. set: function (value) {
  70291. this._refreshRate = value;
  70292. this.resetRefreshCounter();
  70293. },
  70294. enumerable: true,
  70295. configurable: true
  70296. });
  70297. ProceduralTexture.prototype._shouldRender = function () {
  70298. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70299. return false;
  70300. }
  70301. if (this._fallbackTextureUsed) {
  70302. return false;
  70303. }
  70304. if (this._currentRefreshId === -1) { // At least render once
  70305. this._currentRefreshId = 1;
  70306. return true;
  70307. }
  70308. if (this.refreshRate === this._currentRefreshId) {
  70309. this._currentRefreshId = 1;
  70310. return true;
  70311. }
  70312. this._currentRefreshId++;
  70313. return false;
  70314. };
  70315. ProceduralTexture.prototype.getRenderSize = function () {
  70316. return this._size;
  70317. };
  70318. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70319. if (this._fallbackTextureUsed) {
  70320. return;
  70321. }
  70322. this.releaseInternalTexture();
  70323. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70324. };
  70325. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70326. if (this._uniforms.indexOf(uniformName) === -1) {
  70327. this._uniforms.push(uniformName);
  70328. }
  70329. };
  70330. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70331. if (this._samplers.indexOf(name) === -1) {
  70332. this._samplers.push(name);
  70333. }
  70334. this._textures[name] = texture;
  70335. return this;
  70336. };
  70337. ProceduralTexture.prototype.setFloat = function (name, value) {
  70338. this._checkUniform(name);
  70339. this._floats[name] = value;
  70340. return this;
  70341. };
  70342. ProceduralTexture.prototype.setFloats = function (name, value) {
  70343. this._checkUniform(name);
  70344. this._floatsArrays[name] = value;
  70345. return this;
  70346. };
  70347. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70348. this._checkUniform(name);
  70349. this._colors3[name] = value;
  70350. return this;
  70351. };
  70352. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70353. this._checkUniform(name);
  70354. this._colors4[name] = value;
  70355. return this;
  70356. };
  70357. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70358. this._checkUniform(name);
  70359. this._vectors2[name] = value;
  70360. return this;
  70361. };
  70362. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70363. this._checkUniform(name);
  70364. this._vectors3[name] = value;
  70365. return this;
  70366. };
  70367. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70368. this._checkUniform(name);
  70369. this._matrices[name] = value;
  70370. return this;
  70371. };
  70372. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70373. var scene = this.getScene();
  70374. if (!scene) {
  70375. return;
  70376. }
  70377. var engine = this._engine;
  70378. // Render
  70379. engine.enableEffect(this._effect);
  70380. engine.setState(false);
  70381. // Texture
  70382. for (var name in this._textures) {
  70383. this._effect.setTexture(name, this._textures[name]);
  70384. }
  70385. // Float
  70386. for (name in this._floats) {
  70387. this._effect.setFloat(name, this._floats[name]);
  70388. }
  70389. // Floats
  70390. for (name in this._floatsArrays) {
  70391. this._effect.setArray(name, this._floatsArrays[name]);
  70392. }
  70393. // Color3
  70394. for (name in this._colors3) {
  70395. this._effect.setColor3(name, this._colors3[name]);
  70396. }
  70397. // Color4
  70398. for (name in this._colors4) {
  70399. var color = this._colors4[name];
  70400. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70401. }
  70402. // Vector2
  70403. for (name in this._vectors2) {
  70404. this._effect.setVector2(name, this._vectors2[name]);
  70405. }
  70406. // Vector3
  70407. for (name in this._vectors3) {
  70408. this._effect.setVector3(name, this._vectors3[name]);
  70409. }
  70410. // Matrix
  70411. for (name in this._matrices) {
  70412. this._effect.setMatrix(name, this._matrices[name]);
  70413. }
  70414. if (!this._texture) {
  70415. return;
  70416. }
  70417. if (this.isCube) {
  70418. for (var face = 0; face < 6; face++) {
  70419. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70420. // VBOs
  70421. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70422. this._effect.setFloat("face", face);
  70423. // Clear
  70424. engine.clear(scene.clearColor, true, true, true);
  70425. // Draw order
  70426. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70427. // Mipmaps
  70428. if (face === 5) {
  70429. engine.generateMipMapsForCubemap(this._texture);
  70430. }
  70431. }
  70432. }
  70433. else {
  70434. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70435. // VBOs
  70436. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70437. // Clear
  70438. engine.clear(scene.clearColor, true, true, true);
  70439. // Draw order
  70440. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70441. }
  70442. // Unbind
  70443. engine.unBindFramebuffer(this._texture, this.isCube);
  70444. if (this.onGenerated) {
  70445. this.onGenerated();
  70446. }
  70447. };
  70448. ProceduralTexture.prototype.clone = function () {
  70449. var textureSize = this.getSize();
  70450. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70451. // Base texture
  70452. newTexture.hasAlpha = this.hasAlpha;
  70453. newTexture.level = this.level;
  70454. // RenderTarget Texture
  70455. newTexture.coordinatesMode = this.coordinatesMode;
  70456. return newTexture;
  70457. };
  70458. ProceduralTexture.prototype.dispose = function () {
  70459. var scene = this.getScene();
  70460. if (!scene) {
  70461. return;
  70462. }
  70463. var index = scene.proceduralTextures.indexOf(this);
  70464. if (index >= 0) {
  70465. scene.proceduralTextures.splice(index, 1);
  70466. }
  70467. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70468. if (vertexBuffer) {
  70469. vertexBuffer.dispose();
  70470. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70471. }
  70472. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70473. this._indexBuffer = null;
  70474. }
  70475. _super.prototype.dispose.call(this);
  70476. };
  70477. return ProceduralTexture;
  70478. }(BABYLON.Texture));
  70479. BABYLON.ProceduralTexture = ProceduralTexture;
  70480. })(BABYLON || (BABYLON = {}));
  70481. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70482. var BABYLON;
  70483. (function (BABYLON) {
  70484. var CustomProceduralTexture = /** @class */ (function (_super) {
  70485. __extends(CustomProceduralTexture, _super);
  70486. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70487. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70488. _this._animate = true;
  70489. _this._time = 0;
  70490. _this._texturePath = texturePath;
  70491. //Try to load json
  70492. _this.loadJson(texturePath);
  70493. _this.refreshRate = 1;
  70494. return _this;
  70495. }
  70496. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70497. var _this = this;
  70498. var noConfigFile = function () {
  70499. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70500. try {
  70501. _this.setFragment(_this._texturePath);
  70502. }
  70503. catch (ex) {
  70504. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70505. }
  70506. };
  70507. var configFileUrl = jsonUrl + "/config.json";
  70508. var xhr = new XMLHttpRequest();
  70509. xhr.open("GET", configFileUrl, true);
  70510. xhr.addEventListener("load", function () {
  70511. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70512. try {
  70513. _this._config = JSON.parse(xhr.response);
  70514. _this.updateShaderUniforms();
  70515. _this.updateTextures();
  70516. _this.setFragment(_this._texturePath + "/custom");
  70517. _this._animate = _this._config.animate;
  70518. _this.refreshRate = _this._config.refreshrate;
  70519. }
  70520. catch (ex) {
  70521. noConfigFile();
  70522. }
  70523. }
  70524. else {
  70525. noConfigFile();
  70526. }
  70527. }, false);
  70528. xhr.addEventListener("error", function () {
  70529. noConfigFile();
  70530. }, false);
  70531. try {
  70532. xhr.send();
  70533. }
  70534. catch (ex) {
  70535. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70536. }
  70537. };
  70538. CustomProceduralTexture.prototype.isReady = function () {
  70539. if (!_super.prototype.isReady.call(this)) {
  70540. return false;
  70541. }
  70542. for (var name in this._textures) {
  70543. var texture = this._textures[name];
  70544. if (!texture.isReady()) {
  70545. return false;
  70546. }
  70547. }
  70548. return true;
  70549. };
  70550. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70551. var scene = this.getScene();
  70552. if (this._animate && scene) {
  70553. this._time += scene.getAnimationRatio() * 0.03;
  70554. this.updateShaderUniforms();
  70555. }
  70556. _super.prototype.render.call(this, useCameraPostProcess);
  70557. };
  70558. CustomProceduralTexture.prototype.updateTextures = function () {
  70559. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70560. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70561. }
  70562. };
  70563. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70564. if (this._config) {
  70565. for (var j = 0; j < this._config.uniforms.length; j++) {
  70566. var uniform = this._config.uniforms[j];
  70567. switch (uniform.type) {
  70568. case "float":
  70569. this.setFloat(uniform.name, uniform.value);
  70570. break;
  70571. case "color3":
  70572. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70573. break;
  70574. case "color4":
  70575. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70576. break;
  70577. case "vector2":
  70578. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70579. break;
  70580. case "vector3":
  70581. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70582. break;
  70583. }
  70584. }
  70585. }
  70586. this.setFloat("time", this._time);
  70587. };
  70588. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70589. get: function () {
  70590. return this._animate;
  70591. },
  70592. set: function (value) {
  70593. this._animate = value;
  70594. },
  70595. enumerable: true,
  70596. configurable: true
  70597. });
  70598. return CustomProceduralTexture;
  70599. }(BABYLON.ProceduralTexture));
  70600. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70601. })(BABYLON || (BABYLON = {}));
  70602. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70603. var BABYLON;
  70604. (function (BABYLON) {
  70605. var FreeCameraGamepadInput = /** @class */ (function () {
  70606. function FreeCameraGamepadInput() {
  70607. this.gamepadAngularSensibility = 200;
  70608. this.gamepadMoveSensibility = 40;
  70609. // private members
  70610. this._cameraTransform = BABYLON.Matrix.Identity();
  70611. this._deltaTransform = BABYLON.Vector3.Zero();
  70612. this._vector3 = BABYLON.Vector3.Zero();
  70613. this._vector2 = BABYLON.Vector2.Zero();
  70614. }
  70615. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70616. var _this = this;
  70617. var manager = this.camera.getScene().gamepadManager;
  70618. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70619. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70620. // prioritize XBOX gamepads.
  70621. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70622. _this.gamepad = gamepad;
  70623. }
  70624. }
  70625. });
  70626. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70627. if (_this.gamepad === gamepad) {
  70628. _this.gamepad = null;
  70629. }
  70630. });
  70631. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70632. };
  70633. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70634. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70635. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70636. this.gamepad = null;
  70637. };
  70638. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70639. if (this.gamepad && this.gamepad.leftStick) {
  70640. var camera = this.camera;
  70641. var LSValues = this.gamepad.leftStick;
  70642. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70643. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70644. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70645. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70646. var RSValues = this.gamepad.rightStick;
  70647. if (RSValues) {
  70648. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70649. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70650. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70651. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70652. }
  70653. else {
  70654. RSValues = { x: 0, y: 0 };
  70655. }
  70656. if (!camera.rotationQuaternion) {
  70657. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70658. }
  70659. else {
  70660. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70661. }
  70662. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70663. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70664. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70665. camera.cameraDirection.addInPlace(this._deltaTransform);
  70666. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70667. camera.cameraRotation.addInPlace(this._vector2);
  70668. }
  70669. };
  70670. FreeCameraGamepadInput.prototype.getClassName = function () {
  70671. return "FreeCameraGamepadInput";
  70672. };
  70673. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70674. return "gamepad";
  70675. };
  70676. __decorate([
  70677. BABYLON.serialize()
  70678. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70679. __decorate([
  70680. BABYLON.serialize()
  70681. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70682. return FreeCameraGamepadInput;
  70683. }());
  70684. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70685. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70686. })(BABYLON || (BABYLON = {}));
  70687. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70688. var BABYLON;
  70689. (function (BABYLON) {
  70690. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70691. function ArcRotateCameraGamepadInput() {
  70692. this.gamepadRotationSensibility = 80;
  70693. this.gamepadMoveSensibility = 40;
  70694. }
  70695. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70696. var _this = this;
  70697. var manager = this.camera.getScene().gamepadManager;
  70698. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70699. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70700. // prioritize XBOX gamepads.
  70701. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70702. _this.gamepad = gamepad;
  70703. }
  70704. }
  70705. });
  70706. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70707. if (_this.gamepad === gamepad) {
  70708. _this.gamepad = null;
  70709. }
  70710. });
  70711. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70712. };
  70713. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70714. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70715. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70716. this.gamepad = null;
  70717. };
  70718. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70719. if (this.gamepad) {
  70720. var camera = this.camera;
  70721. var RSValues = this.gamepad.rightStick;
  70722. if (RSValues) {
  70723. if (RSValues.x != 0) {
  70724. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70725. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70726. camera.inertialAlphaOffset += normalizedRX;
  70727. }
  70728. }
  70729. if (RSValues.y != 0) {
  70730. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70731. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70732. camera.inertialBetaOffset += normalizedRY;
  70733. }
  70734. }
  70735. }
  70736. var LSValues = this.gamepad.leftStick;
  70737. if (LSValues && LSValues.y != 0) {
  70738. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70739. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70740. this.camera.inertialRadiusOffset -= normalizedLY;
  70741. }
  70742. }
  70743. }
  70744. };
  70745. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70746. return "ArcRotateCameraGamepadInput";
  70747. };
  70748. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70749. return "gamepad";
  70750. };
  70751. __decorate([
  70752. BABYLON.serialize()
  70753. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70754. __decorate([
  70755. BABYLON.serialize()
  70756. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70757. return ArcRotateCameraGamepadInput;
  70758. }());
  70759. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70760. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70761. })(BABYLON || (BABYLON = {}));
  70762. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70763. var BABYLON;
  70764. (function (BABYLON) {
  70765. var GamepadManager = /** @class */ (function () {
  70766. function GamepadManager(_scene) {
  70767. var _this = this;
  70768. this._scene = _scene;
  70769. this._babylonGamepads = [];
  70770. this._oneGamepadConnected = false;
  70771. this._isMonitoring = false;
  70772. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70773. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70774. this._gamepadEventSupported = false;
  70775. }
  70776. else {
  70777. this._gamepadEventSupported = 'GamepadEvent' in window;
  70778. this._gamepadSupport = (navigator.getGamepads ||
  70779. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70780. }
  70781. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70782. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70783. for (var i in _this._babylonGamepads) {
  70784. var gamepad = _this._babylonGamepads[i];
  70785. if (gamepad && gamepad._isConnected) {
  70786. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70787. }
  70788. }
  70789. });
  70790. this._onGamepadConnectedEvent = function (evt) {
  70791. var gamepad = evt.gamepad;
  70792. if (gamepad.index in _this._babylonGamepads) {
  70793. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70794. return;
  70795. }
  70796. }
  70797. var newGamepad;
  70798. if (_this._babylonGamepads[gamepad.index]) {
  70799. newGamepad = _this._babylonGamepads[gamepad.index];
  70800. newGamepad.browserGamepad = gamepad;
  70801. newGamepad._isConnected = true;
  70802. }
  70803. else {
  70804. newGamepad = _this._addNewGamepad(gamepad);
  70805. }
  70806. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70807. _this._startMonitoringGamepads();
  70808. };
  70809. this._onGamepadDisconnectedEvent = function (evt) {
  70810. var gamepad = evt.gamepad;
  70811. // Remove the gamepad from the list of gamepads to monitor.
  70812. for (var i in _this._babylonGamepads) {
  70813. if (_this._babylonGamepads[i].index === gamepad.index) {
  70814. var disconnectedGamepad = _this._babylonGamepads[i];
  70815. disconnectedGamepad._isConnected = false;
  70816. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70817. break;
  70818. }
  70819. }
  70820. };
  70821. if (this._gamepadSupport) {
  70822. //first add already-connected gamepads
  70823. this._updateGamepadObjects();
  70824. if (this._babylonGamepads.length) {
  70825. this._startMonitoringGamepads();
  70826. }
  70827. // Checking if the gamepad connected event is supported (like in Firefox)
  70828. if (this._gamepadEventSupported) {
  70829. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70830. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70831. }
  70832. else {
  70833. this._startMonitoringGamepads();
  70834. }
  70835. }
  70836. }
  70837. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70838. get: function () {
  70839. return this._babylonGamepads;
  70840. },
  70841. enumerable: true,
  70842. configurable: true
  70843. });
  70844. GamepadManager.prototype.getGamepadByType = function (type) {
  70845. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70846. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70847. var gamepad = _a[_i];
  70848. if (gamepad && gamepad.type === type) {
  70849. return gamepad;
  70850. }
  70851. }
  70852. return null;
  70853. };
  70854. GamepadManager.prototype.dispose = function () {
  70855. if (this._gamepadEventSupported) {
  70856. if (this._onGamepadConnectedEvent) {
  70857. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70858. }
  70859. if (this._onGamepadDisconnectedEvent) {
  70860. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70861. }
  70862. this._onGamepadConnectedEvent = null;
  70863. this._onGamepadDisconnectedEvent = null;
  70864. }
  70865. this._babylonGamepads.forEach(function (gamepad) {
  70866. gamepad.dispose();
  70867. });
  70868. this.onGamepadConnectedObservable.clear();
  70869. this.onGamepadDisconnectedObservable.clear();
  70870. this._oneGamepadConnected = false;
  70871. this._stopMonitoringGamepads();
  70872. this._babylonGamepads = [];
  70873. };
  70874. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70875. if (!this._oneGamepadConnected) {
  70876. this._oneGamepadConnected = true;
  70877. }
  70878. var newGamepad;
  70879. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70880. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70881. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70882. }
  70883. // if pose is supported, use the (WebVR) pose enabled controller
  70884. else if (gamepad.pose) {
  70885. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70886. }
  70887. else {
  70888. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70889. }
  70890. this._babylonGamepads[newGamepad.index] = newGamepad;
  70891. return newGamepad;
  70892. };
  70893. GamepadManager.prototype._startMonitoringGamepads = function () {
  70894. if (!this._isMonitoring) {
  70895. this._isMonitoring = true;
  70896. //back-comp
  70897. if (!this._scene) {
  70898. this._checkGamepadsStatus();
  70899. }
  70900. }
  70901. };
  70902. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70903. this._isMonitoring = false;
  70904. };
  70905. GamepadManager.prototype._checkGamepadsStatus = function () {
  70906. var _this = this;
  70907. // Hack to be compatible Chrome
  70908. this._updateGamepadObjects();
  70909. for (var i in this._babylonGamepads) {
  70910. var gamepad = this._babylonGamepads[i];
  70911. if (!gamepad || !gamepad.isConnected) {
  70912. continue;
  70913. }
  70914. gamepad.update();
  70915. }
  70916. if (this._isMonitoring && !this._scene) {
  70917. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70918. }
  70919. };
  70920. // This function is called only on Chrome, which does not properly support
  70921. // connection/disconnection events and forces you to recopy again the gamepad object
  70922. GamepadManager.prototype._updateGamepadObjects = function () {
  70923. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70924. for (var i = 0; i < gamepads.length; i++) {
  70925. var gamepad = gamepads[i];
  70926. if (gamepad) {
  70927. if (!this._babylonGamepads[gamepad.index]) {
  70928. var newGamepad = this._addNewGamepad(gamepad);
  70929. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70930. }
  70931. else {
  70932. // Forced to copy again this object for Chrome for unknown reason
  70933. this._babylonGamepads[i].browserGamepad = gamepad;
  70934. if (!this._babylonGamepads[i].isConnected) {
  70935. this._babylonGamepads[i]._isConnected = true;
  70936. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70937. }
  70938. }
  70939. }
  70940. }
  70941. };
  70942. return GamepadManager;
  70943. }());
  70944. BABYLON.GamepadManager = GamepadManager;
  70945. })(BABYLON || (BABYLON = {}));
  70946. //# sourceMappingURL=babylon.gamepadManager.js.map
  70947. var BABYLON;
  70948. (function (BABYLON) {
  70949. var StickValues = /** @class */ (function () {
  70950. function StickValues(x, y) {
  70951. this.x = x;
  70952. this.y = y;
  70953. }
  70954. return StickValues;
  70955. }());
  70956. BABYLON.StickValues = StickValues;
  70957. var Gamepad = /** @class */ (function () {
  70958. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70959. if (leftStickX === void 0) { leftStickX = 0; }
  70960. if (leftStickY === void 0) { leftStickY = 1; }
  70961. if (rightStickX === void 0) { rightStickX = 2; }
  70962. if (rightStickY === void 0) { rightStickY = 3; }
  70963. this.id = id;
  70964. this.index = index;
  70965. this.browserGamepad = browserGamepad;
  70966. this._isConnected = true;
  70967. this._invertLeftStickY = false;
  70968. this.type = Gamepad.GAMEPAD;
  70969. this._leftStickAxisX = leftStickX;
  70970. this._leftStickAxisY = leftStickY;
  70971. this._rightStickAxisX = rightStickX;
  70972. this._rightStickAxisY = rightStickY;
  70973. if (this.browserGamepad.axes.length >= 2) {
  70974. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70975. }
  70976. if (this.browserGamepad.axes.length >= 4) {
  70977. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70978. }
  70979. }
  70980. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70981. get: function () {
  70982. return this._isConnected;
  70983. },
  70984. enumerable: true,
  70985. configurable: true
  70986. });
  70987. Gamepad.prototype.onleftstickchanged = function (callback) {
  70988. this._onleftstickchanged = callback;
  70989. };
  70990. Gamepad.prototype.onrightstickchanged = function (callback) {
  70991. this._onrightstickchanged = callback;
  70992. };
  70993. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70994. get: function () {
  70995. return this._leftStick;
  70996. },
  70997. set: function (newValues) {
  70998. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70999. this._onleftstickchanged(newValues);
  71000. }
  71001. this._leftStick = newValues;
  71002. },
  71003. enumerable: true,
  71004. configurable: true
  71005. });
  71006. Object.defineProperty(Gamepad.prototype, "rightStick", {
  71007. get: function () {
  71008. return this._rightStick;
  71009. },
  71010. set: function (newValues) {
  71011. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  71012. this._onrightstickchanged(newValues);
  71013. }
  71014. this._rightStick = newValues;
  71015. },
  71016. enumerable: true,
  71017. configurable: true
  71018. });
  71019. Gamepad.prototype.update = function () {
  71020. if (this._leftStick) {
  71021. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71022. if (this._invertLeftStickY) {
  71023. this.leftStick.y *= -1;
  71024. }
  71025. }
  71026. if (this._rightStick) {
  71027. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71028. }
  71029. };
  71030. Gamepad.prototype.dispose = function () {
  71031. };
  71032. Gamepad.GAMEPAD = 0;
  71033. Gamepad.GENERIC = 1;
  71034. Gamepad.XBOX = 2;
  71035. Gamepad.POSE_ENABLED = 3;
  71036. return Gamepad;
  71037. }());
  71038. BABYLON.Gamepad = Gamepad;
  71039. var GenericPad = /** @class */ (function (_super) {
  71040. __extends(GenericPad, _super);
  71041. function GenericPad(id, index, browserGamepad) {
  71042. var _this = _super.call(this, id, index, browserGamepad) || this;
  71043. _this.onButtonDownObservable = new BABYLON.Observable();
  71044. _this.onButtonUpObservable = new BABYLON.Observable();
  71045. _this.type = Gamepad.GENERIC;
  71046. _this._buttons = new Array(browserGamepad.buttons.length);
  71047. return _this;
  71048. }
  71049. GenericPad.prototype.onbuttondown = function (callback) {
  71050. this._onbuttondown = callback;
  71051. };
  71052. GenericPad.prototype.onbuttonup = function (callback) {
  71053. this._onbuttonup = callback;
  71054. };
  71055. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  71056. if (newValue !== currentValue) {
  71057. if (newValue === 1) {
  71058. if (this._onbuttondown) {
  71059. this._onbuttondown(buttonIndex);
  71060. }
  71061. this.onButtonDownObservable.notifyObservers(buttonIndex);
  71062. }
  71063. if (newValue === 0) {
  71064. if (this._onbuttonup) {
  71065. this._onbuttonup(buttonIndex);
  71066. }
  71067. this.onButtonUpObservable.notifyObservers(buttonIndex);
  71068. }
  71069. }
  71070. return newValue;
  71071. };
  71072. GenericPad.prototype.update = function () {
  71073. _super.prototype.update.call(this);
  71074. for (var index = 0; index < this._buttons.length; index++) {
  71075. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  71076. }
  71077. };
  71078. GenericPad.prototype.dispose = function () {
  71079. _super.prototype.dispose.call(this);
  71080. this.onButtonDownObservable.clear();
  71081. this.onButtonUpObservable.clear();
  71082. };
  71083. return GenericPad;
  71084. }(Gamepad));
  71085. BABYLON.GenericPad = GenericPad;
  71086. })(BABYLON || (BABYLON = {}));
  71087. //# sourceMappingURL=babylon.gamepad.js.map
  71088. var BABYLON;
  71089. (function (BABYLON) {
  71090. /**
  71091. * Defines supported buttons for XBox360 compatible gamepads
  71092. */
  71093. var Xbox360Button;
  71094. (function (Xbox360Button) {
  71095. /** A */
  71096. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  71097. /** B */
  71098. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  71099. /** X */
  71100. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  71101. /** Y */
  71102. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  71103. /** Start */
  71104. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  71105. /** Back */
  71106. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  71107. /** Left button */
  71108. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  71109. /** Right button */
  71110. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  71111. /** Left stick */
  71112. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  71113. /** Right stick */
  71114. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  71115. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  71116. /** Defines values for XBox360 DPad */
  71117. var Xbox360Dpad;
  71118. (function (Xbox360Dpad) {
  71119. /** Up */
  71120. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  71121. /** Down */
  71122. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  71123. /** Left */
  71124. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  71125. /** Right */
  71126. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  71127. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  71128. /**
  71129. * Defines a XBox360 gamepad
  71130. */
  71131. var Xbox360Pad = /** @class */ (function (_super) {
  71132. __extends(Xbox360Pad, _super);
  71133. /**
  71134. * Creates a new XBox360 gamepad object
  71135. * @param id defines the id of this gamepad
  71136. * @param index defines its index
  71137. * @param gamepad defines the internal HTML gamepad object
  71138. * @param xboxOne defines if it is a XBox One gamepad
  71139. */
  71140. function Xbox360Pad(id, index, gamepad, xboxOne) {
  71141. if (xboxOne === void 0) { xboxOne = false; }
  71142. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  71143. _this._leftTrigger = 0;
  71144. _this._rightTrigger = 0;
  71145. /** Observable raised when a button is pressed */
  71146. _this.onButtonDownObservable = new BABYLON.Observable();
  71147. /** Observable raised when a button is released */
  71148. _this.onButtonUpObservable = new BABYLON.Observable();
  71149. /** Observable raised when a pad is pressed */
  71150. _this.onPadDownObservable = new BABYLON.Observable();
  71151. /** Observable raised when a pad is released */
  71152. _this.onPadUpObservable = new BABYLON.Observable();
  71153. _this._buttonA = 0;
  71154. _this._buttonB = 0;
  71155. _this._buttonX = 0;
  71156. _this._buttonY = 0;
  71157. _this._buttonBack = 0;
  71158. _this._buttonStart = 0;
  71159. _this._buttonLB = 0;
  71160. _this._buttonRB = 0;
  71161. _this._buttonLeftStick = 0;
  71162. _this._buttonRightStick = 0;
  71163. _this._dPadUp = 0;
  71164. _this._dPadDown = 0;
  71165. _this._dPadLeft = 0;
  71166. _this._dPadRight = 0;
  71167. _this._isXboxOnePad = false;
  71168. _this.type = BABYLON.Gamepad.XBOX;
  71169. _this._isXboxOnePad = xboxOne;
  71170. return _this;
  71171. }
  71172. /**
  71173. * Defines the callback to call when left trigger is pressed
  71174. * @param callback defines the callback to use
  71175. */
  71176. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  71177. this._onlefttriggerchanged = callback;
  71178. };
  71179. /**
  71180. * Defines the callback to call when right trigger is pressed
  71181. * @param callback defines the callback to use
  71182. */
  71183. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  71184. this._onrighttriggerchanged = callback;
  71185. };
  71186. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  71187. /**
  71188. * Gets or sets left trigger value
  71189. */
  71190. get: function () {
  71191. return this._leftTrigger;
  71192. },
  71193. set: function (newValue) {
  71194. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  71195. this._onlefttriggerchanged(newValue);
  71196. }
  71197. this._leftTrigger = newValue;
  71198. },
  71199. enumerable: true,
  71200. configurable: true
  71201. });
  71202. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  71203. /**
  71204. * Gets or sets right trigger value
  71205. */
  71206. get: function () {
  71207. return this._rightTrigger;
  71208. },
  71209. set: function (newValue) {
  71210. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  71211. this._onrighttriggerchanged(newValue);
  71212. }
  71213. this._rightTrigger = newValue;
  71214. },
  71215. enumerable: true,
  71216. configurable: true
  71217. });
  71218. /**
  71219. * Defines the callback to call when a button is pressed
  71220. * @param callback defines the callback to use
  71221. */
  71222. Xbox360Pad.prototype.onbuttondown = function (callback) {
  71223. this._onbuttondown = callback;
  71224. };
  71225. /**
  71226. * Defines the callback to call when a button is released
  71227. * @param callback defines the callback to use
  71228. */
  71229. Xbox360Pad.prototype.onbuttonup = function (callback) {
  71230. this._onbuttonup = callback;
  71231. };
  71232. /**
  71233. * Defines the callback to call when a pad is pressed
  71234. * @param callback defines the callback to use
  71235. */
  71236. Xbox360Pad.prototype.ondpaddown = function (callback) {
  71237. this._ondpaddown = callback;
  71238. };
  71239. /**
  71240. * Defines the callback to call when a pad is released
  71241. * @param callback defines the callback to use
  71242. */
  71243. Xbox360Pad.prototype.ondpadup = function (callback) {
  71244. this._ondpadup = callback;
  71245. };
  71246. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  71247. if (newValue !== currentValue) {
  71248. if (newValue === 1) {
  71249. if (this._onbuttondown) {
  71250. this._onbuttondown(buttonType);
  71251. }
  71252. this.onButtonDownObservable.notifyObservers(buttonType);
  71253. }
  71254. if (newValue === 0) {
  71255. if (this._onbuttonup) {
  71256. this._onbuttonup(buttonType);
  71257. }
  71258. this.onButtonUpObservable.notifyObservers(buttonType);
  71259. }
  71260. }
  71261. return newValue;
  71262. };
  71263. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71264. if (newValue !== currentValue) {
  71265. if (newValue === 1) {
  71266. if (this._ondpaddown) {
  71267. this._ondpaddown(buttonType);
  71268. }
  71269. this.onPadDownObservable.notifyObservers(buttonType);
  71270. }
  71271. if (newValue === 0) {
  71272. if (this._ondpadup) {
  71273. this._ondpadup(buttonType);
  71274. }
  71275. this.onPadUpObservable.notifyObservers(buttonType);
  71276. }
  71277. }
  71278. return newValue;
  71279. };
  71280. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71281. /** Gets or sets value of A button */
  71282. get: function () {
  71283. return this._buttonA;
  71284. },
  71285. set: function (value) {
  71286. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71287. },
  71288. enumerable: true,
  71289. configurable: true
  71290. });
  71291. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71292. /** Gets or sets value of B button */
  71293. get: function () {
  71294. return this._buttonB;
  71295. },
  71296. set: function (value) {
  71297. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71298. },
  71299. enumerable: true,
  71300. configurable: true
  71301. });
  71302. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71303. /** Gets or sets value of X button */
  71304. get: function () {
  71305. return this._buttonX;
  71306. },
  71307. set: function (value) {
  71308. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71309. },
  71310. enumerable: true,
  71311. configurable: true
  71312. });
  71313. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71314. /** Gets or sets value of Y button */
  71315. get: function () {
  71316. return this._buttonY;
  71317. },
  71318. set: function (value) {
  71319. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71320. },
  71321. enumerable: true,
  71322. configurable: true
  71323. });
  71324. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71325. /** Gets or sets value of Start button */
  71326. get: function () {
  71327. return this._buttonStart;
  71328. },
  71329. set: function (value) {
  71330. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71331. },
  71332. enumerable: true,
  71333. configurable: true
  71334. });
  71335. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71336. /** Gets or sets value of Back button */
  71337. get: function () {
  71338. return this._buttonBack;
  71339. },
  71340. set: function (value) {
  71341. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71342. },
  71343. enumerable: true,
  71344. configurable: true
  71345. });
  71346. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71347. /** Gets or sets value of Left button */
  71348. get: function () {
  71349. return this._buttonLB;
  71350. },
  71351. set: function (value) {
  71352. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71353. },
  71354. enumerable: true,
  71355. configurable: true
  71356. });
  71357. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71358. /** Gets or sets value of Right button */
  71359. get: function () {
  71360. return this._buttonRB;
  71361. },
  71362. set: function (value) {
  71363. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71364. },
  71365. enumerable: true,
  71366. configurable: true
  71367. });
  71368. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71369. /** Gets or sets value of left stick */
  71370. get: function () {
  71371. return this._buttonLeftStick;
  71372. },
  71373. set: function (value) {
  71374. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71375. },
  71376. enumerable: true,
  71377. configurable: true
  71378. });
  71379. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71380. /** Gets or sets value of right stick */
  71381. get: function () {
  71382. return this._buttonRightStick;
  71383. },
  71384. set: function (value) {
  71385. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71386. },
  71387. enumerable: true,
  71388. configurable: true
  71389. });
  71390. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71391. /** Gets or sets value of DPad up */
  71392. get: function () {
  71393. return this._dPadUp;
  71394. },
  71395. set: function (value) {
  71396. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71397. },
  71398. enumerable: true,
  71399. configurable: true
  71400. });
  71401. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71402. /** Gets or sets value of DPad down */
  71403. get: function () {
  71404. return this._dPadDown;
  71405. },
  71406. set: function (value) {
  71407. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71408. },
  71409. enumerable: true,
  71410. configurable: true
  71411. });
  71412. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71413. /** Gets or sets value of DPad left */
  71414. get: function () {
  71415. return this._dPadLeft;
  71416. },
  71417. set: function (value) {
  71418. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71419. },
  71420. enumerable: true,
  71421. configurable: true
  71422. });
  71423. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71424. /** Gets or sets value of DPad right */
  71425. get: function () {
  71426. return this._dPadRight;
  71427. },
  71428. set: function (value) {
  71429. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71430. },
  71431. enumerable: true,
  71432. configurable: true
  71433. });
  71434. /**
  71435. * Force the gamepad to synchronize with device values
  71436. */
  71437. Xbox360Pad.prototype.update = function () {
  71438. _super.prototype.update.call(this);
  71439. if (this._isXboxOnePad) {
  71440. this.buttonA = this.browserGamepad.buttons[0].value;
  71441. this.buttonB = this.browserGamepad.buttons[1].value;
  71442. this.buttonX = this.browserGamepad.buttons[2].value;
  71443. this.buttonY = this.browserGamepad.buttons[3].value;
  71444. this.buttonLB = this.browserGamepad.buttons[4].value;
  71445. this.buttonRB = this.browserGamepad.buttons[5].value;
  71446. this.leftTrigger = this.browserGamepad.axes[2];
  71447. this.rightTrigger = this.browserGamepad.axes[5];
  71448. this.buttonBack = this.browserGamepad.buttons[9].value;
  71449. this.buttonStart = this.browserGamepad.buttons[8].value;
  71450. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71451. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71452. this.dPadUp = this.browserGamepad.buttons[11].value;
  71453. this.dPadDown = this.browserGamepad.buttons[12].value;
  71454. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71455. this.dPadRight = this.browserGamepad.buttons[14].value;
  71456. }
  71457. else {
  71458. this.buttonA = this.browserGamepad.buttons[0].value;
  71459. this.buttonB = this.browserGamepad.buttons[1].value;
  71460. this.buttonX = this.browserGamepad.buttons[2].value;
  71461. this.buttonY = this.browserGamepad.buttons[3].value;
  71462. this.buttonLB = this.browserGamepad.buttons[4].value;
  71463. this.buttonRB = this.browserGamepad.buttons[5].value;
  71464. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71465. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71466. this.buttonBack = this.browserGamepad.buttons[8].value;
  71467. this.buttonStart = this.browserGamepad.buttons[9].value;
  71468. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71469. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71470. this.dPadUp = this.browserGamepad.buttons[12].value;
  71471. this.dPadDown = this.browserGamepad.buttons[13].value;
  71472. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71473. this.dPadRight = this.browserGamepad.buttons[15].value;
  71474. }
  71475. };
  71476. Xbox360Pad.prototype.dispose = function () {
  71477. _super.prototype.dispose.call(this);
  71478. this.onButtonDownObservable.clear();
  71479. this.onButtonUpObservable.clear();
  71480. this.onPadDownObservable.clear();
  71481. this.onPadUpObservable.clear();
  71482. };
  71483. return Xbox360Pad;
  71484. }(BABYLON.Gamepad));
  71485. BABYLON.Xbox360Pad = Xbox360Pad;
  71486. })(BABYLON || (BABYLON = {}));
  71487. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71488. var BABYLON;
  71489. (function (BABYLON) {
  71490. /**
  71491. * Defines the types of pose enabled controllers that are supported
  71492. */
  71493. var PoseEnabledControllerType;
  71494. (function (PoseEnabledControllerType) {
  71495. /**
  71496. * HTC Vive
  71497. */
  71498. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71499. /**
  71500. * Oculus Rift
  71501. */
  71502. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71503. /**
  71504. * Windows mixed reality
  71505. */
  71506. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71507. /**
  71508. * Samsung gear VR
  71509. */
  71510. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71511. /**
  71512. * Google Daydream
  71513. */
  71514. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71515. /**
  71516. * Generic
  71517. */
  71518. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71519. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71520. /**
  71521. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71522. */
  71523. var PoseEnabledControllerHelper = /** @class */ (function () {
  71524. function PoseEnabledControllerHelper() {
  71525. }
  71526. /**
  71527. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71528. * @param vrGamepad the gamepad to initialized
  71529. * @returns a vr controller of the type the gamepad identified as
  71530. */
  71531. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71532. // Oculus Touch
  71533. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71534. return new BABYLON.OculusTouchController(vrGamepad);
  71535. }
  71536. // Windows Mixed Reality controllers
  71537. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71538. return new BABYLON.WindowsMotionController(vrGamepad);
  71539. }
  71540. // HTC Vive
  71541. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71542. return new BABYLON.ViveController(vrGamepad);
  71543. }
  71544. // Samsung/Oculus Gear VR or Oculus Go
  71545. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71546. return new BABYLON.GearVRController(vrGamepad);
  71547. }
  71548. // Google Daydream
  71549. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71550. return new BABYLON.DaydreamController(vrGamepad);
  71551. }
  71552. // Generic
  71553. else {
  71554. return new BABYLON.GenericController(vrGamepad);
  71555. }
  71556. };
  71557. return PoseEnabledControllerHelper;
  71558. }());
  71559. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71560. /**
  71561. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71562. */
  71563. var PoseEnabledController = /** @class */ (function (_super) {
  71564. __extends(PoseEnabledController, _super);
  71565. /**
  71566. * Creates a new PoseEnabledController from a gamepad
  71567. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71568. */
  71569. function PoseEnabledController(browserGamepad) {
  71570. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71571. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71572. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71573. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71574. /**
  71575. * The device position in babylon space
  71576. */
  71577. _this.devicePosition = BABYLON.Vector3.Zero();
  71578. /**
  71579. * The device rotation in babylon space
  71580. */
  71581. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71582. /**
  71583. * The scale factor of the device in babylon space
  71584. */
  71585. _this.deviceScaleFactor = 1;
  71586. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71587. /**
  71588. * Internal, matrix used to convert room space to babylon space
  71589. */
  71590. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71591. /**
  71592. * Node to be used when casting a ray from the controller
  71593. */
  71594. _this._pointingPoseNode = null;
  71595. _this._workingMatrix = BABYLON.Matrix.Identity();
  71596. /**
  71597. * @hidden
  71598. */
  71599. _this._meshAttachedObservable = new BABYLON.Observable();
  71600. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71601. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71602. _this.position = BABYLON.Vector3.Zero();
  71603. _this.rotationQuaternion = new BABYLON.Quaternion();
  71604. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71605. _this._calculatedRotation = new BABYLON.Quaternion();
  71606. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71607. return _this;
  71608. }
  71609. /**
  71610. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71611. */
  71612. PoseEnabledController.prototype.update = function () {
  71613. _super.prototype.update.call(this);
  71614. var pose = this.browserGamepad.pose;
  71615. this.updateFromDevice(pose);
  71616. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71617. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71618. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71619. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71620. if (this._mesh) {
  71621. this._mesh.position.copyFrom(this.devicePosition);
  71622. if (this._mesh.rotationQuaternion) {
  71623. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71624. }
  71625. }
  71626. };
  71627. /**
  71628. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71629. * @param poseData raw pose fromthe device
  71630. */
  71631. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71632. if (poseData) {
  71633. this.rawPose = poseData;
  71634. if (poseData.position) {
  71635. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71636. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71637. this._deviceRoomPosition.z *= -1;
  71638. }
  71639. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71640. this._calculatedPosition.addInPlace(this.position);
  71641. }
  71642. var pose = this.rawPose;
  71643. if (poseData.orientation && pose.orientation) {
  71644. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71645. if (this._mesh) {
  71646. if (this._mesh.getScene().useRightHandedSystem) {
  71647. this._deviceRoomRotationQuaternion.z *= -1;
  71648. this._deviceRoomRotationQuaternion.w *= -1;
  71649. }
  71650. else {
  71651. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71652. }
  71653. }
  71654. // if the camera is set, rotate to the camera's rotation
  71655. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71656. }
  71657. }
  71658. };
  71659. /**
  71660. * Attaches a mesh to the controller
  71661. * @param mesh the mesh to be attached
  71662. */
  71663. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71664. if (this._mesh) {
  71665. this._mesh.parent = null;
  71666. }
  71667. this._mesh = mesh;
  71668. if (this._poseControlledCamera) {
  71669. this._mesh.parent = this._poseControlledCamera;
  71670. }
  71671. if (!this._mesh.rotationQuaternion) {
  71672. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71673. }
  71674. this._meshAttachedObservable.notifyObservers(mesh);
  71675. };
  71676. /**
  71677. * Attaches the controllers mesh to a camera
  71678. * @param camera the camera the mesh should be attached to
  71679. */
  71680. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71681. this._poseControlledCamera = camera;
  71682. if (this._mesh) {
  71683. this._mesh.parent = this._poseControlledCamera;
  71684. }
  71685. };
  71686. /**
  71687. * Disposes of the controller
  71688. */
  71689. PoseEnabledController.prototype.dispose = function () {
  71690. if (this._mesh) {
  71691. this._mesh.dispose();
  71692. }
  71693. this._mesh = null;
  71694. _super.prototype.dispose.call(this);
  71695. };
  71696. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71697. /**
  71698. * The mesh that is attached to the controller
  71699. */
  71700. get: function () {
  71701. return this._mesh;
  71702. },
  71703. enumerable: true,
  71704. configurable: true
  71705. });
  71706. /**
  71707. * Gets the ray of the controller in the direction the controller is pointing
  71708. * @param length the length the resulting ray should be
  71709. * @returns a ray in the direction the controller is pointing
  71710. */
  71711. PoseEnabledController.prototype.getForwardRay = function (length) {
  71712. if (length === void 0) { length = 100; }
  71713. if (!this.mesh) {
  71714. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71715. }
  71716. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71717. var origin = m.getTranslation();
  71718. var forward = new BABYLON.Vector3(0, 0, -1);
  71719. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71720. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71721. return new BABYLON.Ray(origin, direction, length);
  71722. };
  71723. /**
  71724. * Name of the child mesh that can be used to cast a ray from the controller
  71725. */
  71726. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71727. return PoseEnabledController;
  71728. }(BABYLON.Gamepad));
  71729. BABYLON.PoseEnabledController = PoseEnabledController;
  71730. })(BABYLON || (BABYLON = {}));
  71731. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71732. var BABYLON;
  71733. (function (BABYLON) {
  71734. /**
  71735. * Defines the WebVRController object that represents controllers tracked in 3D space
  71736. */
  71737. var WebVRController = /** @class */ (function (_super) {
  71738. __extends(WebVRController, _super);
  71739. /**
  71740. * Creates a new WebVRController from a gamepad
  71741. * @param vrGamepad the gamepad that the WebVRController should be created from
  71742. */
  71743. function WebVRController(vrGamepad) {
  71744. var _this = _super.call(this, vrGamepad) || this;
  71745. // Observables
  71746. /**
  71747. * Fired when the trigger state has changed
  71748. */
  71749. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71750. /**
  71751. * Fired when the main button state has changed
  71752. */
  71753. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71754. /**
  71755. * Fired when the secondary button state has changed
  71756. */
  71757. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71758. /**
  71759. * Fired when the pad state has changed
  71760. */
  71761. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71762. /**
  71763. * Fired when controllers stick values have changed
  71764. */
  71765. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71766. /**
  71767. * X and Y axis corrisponding to the controllers joystick
  71768. */
  71769. _this.pad = { x: 0, y: 0 };
  71770. // avoid GC, store state in a tmp object
  71771. _this._changes = {
  71772. pressChanged: false,
  71773. touchChanged: false,
  71774. valueChanged: false,
  71775. changed: false
  71776. };
  71777. _this._buttons = new Array(vrGamepad.buttons.length);
  71778. _this.hand = vrGamepad.hand;
  71779. return _this;
  71780. }
  71781. /**
  71782. * Fired when a controller button's state has changed
  71783. * @param callback the callback containing the button that was modified
  71784. */
  71785. WebVRController.prototype.onButtonStateChange = function (callback) {
  71786. this._onButtonStateChange = callback;
  71787. };
  71788. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71789. /**
  71790. * The default controller model for the controller
  71791. */
  71792. get: function () {
  71793. return this._defaultModel;
  71794. },
  71795. enumerable: true,
  71796. configurable: true
  71797. });
  71798. /**
  71799. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71800. */
  71801. WebVRController.prototype.update = function () {
  71802. _super.prototype.update.call(this);
  71803. for (var index = 0; index < this._buttons.length; index++) {
  71804. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71805. }
  71806. ;
  71807. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71808. this.pad.x = this.leftStick.x;
  71809. this.pad.y = this.leftStick.y;
  71810. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71811. }
  71812. };
  71813. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71814. if (!newState) {
  71815. newState = {
  71816. pressed: false,
  71817. touched: false,
  71818. value: 0
  71819. };
  71820. }
  71821. if (!currentState) {
  71822. this._buttons[buttonIndex] = {
  71823. pressed: newState.pressed,
  71824. touched: newState.touched,
  71825. value: newState.value
  71826. };
  71827. return;
  71828. }
  71829. this._checkChanges(newState, currentState);
  71830. if (this._changes.changed) {
  71831. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71832. this._handleButtonChange(buttonIndex, newState, this._changes);
  71833. }
  71834. this._buttons[buttonIndex].pressed = newState.pressed;
  71835. this._buttons[buttonIndex].touched = newState.touched;
  71836. // oculus triggers are never 0, thou not touched.
  71837. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71838. };
  71839. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71840. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71841. this._changes.touchChanged = newState.touched !== currentState.touched;
  71842. this._changes.valueChanged = newState.value !== currentState.value;
  71843. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71844. return this._changes;
  71845. };
  71846. /**
  71847. * Disposes of th webVRCOntroller
  71848. */
  71849. WebVRController.prototype.dispose = function () {
  71850. _super.prototype.dispose.call(this);
  71851. this.onTriggerStateChangedObservable.clear();
  71852. this.onMainButtonStateChangedObservable.clear();
  71853. this.onSecondaryButtonStateChangedObservable.clear();
  71854. this.onPadStateChangedObservable.clear();
  71855. this.onPadValuesChangedObservable.clear();
  71856. };
  71857. return WebVRController;
  71858. }(BABYLON.PoseEnabledController));
  71859. BABYLON.WebVRController = WebVRController;
  71860. })(BABYLON || (BABYLON = {}));
  71861. //# sourceMappingURL=babylon.webVRController.js.map
  71862. var BABYLON;
  71863. (function (BABYLON) {
  71864. /**
  71865. * Oculus Touch Controller
  71866. */
  71867. var OculusTouchController = /** @class */ (function (_super) {
  71868. __extends(OculusTouchController, _super);
  71869. /**
  71870. * Creates a new OculusTouchController from a gamepad
  71871. * @param vrGamepad the gamepad that the controller should be created from
  71872. */
  71873. function OculusTouchController(vrGamepad) {
  71874. var _this = _super.call(this, vrGamepad) || this;
  71875. /**
  71876. * Fired when the secondary trigger on this controller is modified
  71877. */
  71878. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71879. /**
  71880. * Fired when the thumb rest on this controller is modified
  71881. */
  71882. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71883. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71884. return _this;
  71885. }
  71886. /**
  71887. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71888. * @param scene scene in which to add meshes
  71889. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71890. */
  71891. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71892. var _this = this;
  71893. var meshName;
  71894. // Hand
  71895. if (this.hand === 'left') {
  71896. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71897. }
  71898. else { // Right is the default if no hand is specified
  71899. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71900. }
  71901. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71902. /*
  71903. Parent Mesh name: oculus_touch_left
  71904. - body
  71905. - trigger
  71906. - thumbstick
  71907. - grip
  71908. - button_y
  71909. - button_x
  71910. - button_enter
  71911. */
  71912. _this._defaultModel = newMeshes[1];
  71913. _this.attachToMesh(_this._defaultModel);
  71914. if (meshLoaded) {
  71915. meshLoaded(_this._defaultModel);
  71916. }
  71917. });
  71918. };
  71919. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71920. /**
  71921. * Fired when the A button on this controller is modified
  71922. */
  71923. get: function () {
  71924. if (this.hand === 'right') {
  71925. return this.onMainButtonStateChangedObservable;
  71926. }
  71927. else {
  71928. throw new Error('No A button on left hand');
  71929. }
  71930. },
  71931. enumerable: true,
  71932. configurable: true
  71933. });
  71934. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71935. /**
  71936. * Fired when the B button on this controller is modified
  71937. */
  71938. get: function () {
  71939. if (this.hand === 'right') {
  71940. return this.onSecondaryButtonStateChangedObservable;
  71941. }
  71942. else {
  71943. throw new Error('No B button on left hand');
  71944. }
  71945. },
  71946. enumerable: true,
  71947. configurable: true
  71948. });
  71949. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71950. /**
  71951. * Fired when the X button on this controller is modified
  71952. */
  71953. get: function () {
  71954. if (this.hand === 'left') {
  71955. return this.onMainButtonStateChangedObservable;
  71956. }
  71957. else {
  71958. throw new Error('No X button on right hand');
  71959. }
  71960. },
  71961. enumerable: true,
  71962. configurable: true
  71963. });
  71964. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71965. /**
  71966. * Fired when the Y button on this controller is modified
  71967. */
  71968. get: function () {
  71969. if (this.hand === 'left') {
  71970. return this.onSecondaryButtonStateChangedObservable;
  71971. }
  71972. else {
  71973. throw new Error('No Y button on right hand');
  71974. }
  71975. },
  71976. enumerable: true,
  71977. configurable: true
  71978. });
  71979. /**
  71980. * Called once for each button that changed state since the last frame
  71981. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71982. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71983. * 2) secondary trigger (same)
  71984. * 3) A (right) X (left), touch, pressed = value
  71985. * 4) B / Y
  71986. * 5) thumb rest
  71987. * @param buttonIdx Which button index changed
  71988. * @param state New state of the button
  71989. * @param changes Which properties on the state changed since last frame
  71990. */
  71991. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71992. var notifyObject = state; //{ state: state, changes: changes };
  71993. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71994. switch (buttonIdx) {
  71995. case 0:
  71996. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71997. return;
  71998. case 1: // index trigger
  71999. if (this._defaultModel) {
  72000. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  72001. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  72002. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  72003. }
  72004. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72005. return;
  72006. case 2: // secondary trigger
  72007. if (this._defaultModel) {
  72008. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  72009. }
  72010. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  72011. return;
  72012. case 3:
  72013. if (this._defaultModel) {
  72014. if (notifyObject.pressed) {
  72015. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  72016. }
  72017. else {
  72018. (this._defaultModel.getChildren()[1]).position.y = 0;
  72019. }
  72020. }
  72021. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72022. return;
  72023. case 4:
  72024. if (this._defaultModel) {
  72025. if (notifyObject.pressed) {
  72026. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72027. }
  72028. else {
  72029. (this._defaultModel.getChildren()[2]).position.y = 0;
  72030. }
  72031. }
  72032. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72033. return;
  72034. case 5:
  72035. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  72036. return;
  72037. }
  72038. };
  72039. /**
  72040. * Base Url for the controller model.
  72041. */
  72042. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  72043. /**
  72044. * File name for the left controller model.
  72045. */
  72046. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  72047. /**
  72048. * File name for the right controller model.
  72049. */
  72050. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  72051. return OculusTouchController;
  72052. }(BABYLON.WebVRController));
  72053. BABYLON.OculusTouchController = OculusTouchController;
  72054. })(BABYLON || (BABYLON = {}));
  72055. //# sourceMappingURL=babylon.oculusTouchController.js.map
  72056. var BABYLON;
  72057. (function (BABYLON) {
  72058. /**
  72059. * Vive Controller
  72060. */
  72061. var ViveController = /** @class */ (function (_super) {
  72062. __extends(ViveController, _super);
  72063. /**
  72064. * Creates a new ViveController from a gamepad
  72065. * @param vrGamepad the gamepad that the controller should be created from
  72066. */
  72067. function ViveController(vrGamepad) {
  72068. var _this = _super.call(this, vrGamepad) || this;
  72069. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  72070. _this._invertLeftStickY = true;
  72071. return _this;
  72072. }
  72073. /**
  72074. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72075. * @param scene scene in which to add meshes
  72076. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72077. */
  72078. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72079. var _this = this;
  72080. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  72081. /*
  72082. Parent Mesh name: ViveWand
  72083. - body
  72084. - r_gripper
  72085. - l_gripper
  72086. - menu_button
  72087. - system_button
  72088. - trackpad
  72089. - trigger
  72090. - LED
  72091. */
  72092. _this._defaultModel = newMeshes[1];
  72093. _this.attachToMesh(_this._defaultModel);
  72094. if (meshLoaded) {
  72095. meshLoaded(_this._defaultModel);
  72096. }
  72097. });
  72098. };
  72099. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  72100. /**
  72101. * Fired when the left button on this controller is modified
  72102. */
  72103. get: function () {
  72104. return this.onMainButtonStateChangedObservable;
  72105. },
  72106. enumerable: true,
  72107. configurable: true
  72108. });
  72109. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  72110. /**
  72111. * Fired when the right button on this controller is modified
  72112. */
  72113. get: function () {
  72114. return this.onMainButtonStateChangedObservable;
  72115. },
  72116. enumerable: true,
  72117. configurable: true
  72118. });
  72119. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  72120. /**
  72121. * Fired when the menu button on this controller is modified
  72122. */
  72123. get: function () {
  72124. return this.onSecondaryButtonStateChangedObservable;
  72125. },
  72126. enumerable: true,
  72127. configurable: true
  72128. });
  72129. /**
  72130. * Called once for each button that changed state since the last frame
  72131. * Vive mapping:
  72132. * 0: touchpad
  72133. * 1: trigger
  72134. * 2: left AND right buttons
  72135. * 3: menu button
  72136. * @param buttonIdx Which button index changed
  72137. * @param state New state of the button
  72138. * @param changes Which properties on the state changed since last frame
  72139. */
  72140. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72141. var notifyObject = state; //{ state: state, changes: changes };
  72142. switch (buttonIdx) {
  72143. case 0:
  72144. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72145. return;
  72146. case 1: // index trigger
  72147. if (this._defaultModel) {
  72148. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  72149. }
  72150. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72151. return;
  72152. case 2: // left AND right button
  72153. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72154. return;
  72155. case 3:
  72156. if (this._defaultModel) {
  72157. if (notifyObject.pressed) {
  72158. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72159. }
  72160. else {
  72161. (this._defaultModel.getChildren()[2]).position.y = 0;
  72162. }
  72163. }
  72164. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72165. return;
  72166. }
  72167. };
  72168. /**
  72169. * Base Url for the controller model.
  72170. */
  72171. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  72172. /**
  72173. * File name for the controller model.
  72174. */
  72175. ViveController.MODEL_FILENAME = 'wand.babylon';
  72176. return ViveController;
  72177. }(BABYLON.WebVRController));
  72178. BABYLON.ViveController = ViveController;
  72179. })(BABYLON || (BABYLON = {}));
  72180. //# sourceMappingURL=babylon.viveController.js.map
  72181. var BABYLON;
  72182. (function (BABYLON) {
  72183. /**
  72184. * Generic Controller
  72185. */
  72186. var GenericController = /** @class */ (function (_super) {
  72187. __extends(GenericController, _super);
  72188. /**
  72189. * Creates a new GenericController from a gamepad
  72190. * @param vrGamepad the gamepad that the controller should be created from
  72191. */
  72192. function GenericController(vrGamepad) {
  72193. return _super.call(this, vrGamepad) || this;
  72194. }
  72195. /**
  72196. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72197. * @param scene scene in which to add meshes
  72198. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72199. */
  72200. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72201. var _this = this;
  72202. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  72203. _this._defaultModel = newMeshes[1];
  72204. _this.attachToMesh(_this._defaultModel);
  72205. if (meshLoaded) {
  72206. meshLoaded(_this._defaultModel);
  72207. }
  72208. });
  72209. };
  72210. /**
  72211. * Called once for each button that changed state since the last frame
  72212. * @param buttonIdx Which button index changed
  72213. * @param state New state of the button
  72214. * @param changes Which properties on the state changed since last frame
  72215. */
  72216. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72217. console.log("Button id: " + buttonIdx + "state: ");
  72218. console.dir(state);
  72219. };
  72220. /**
  72221. * Base Url for the controller model.
  72222. */
  72223. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72224. /**
  72225. * File name for the controller model.
  72226. */
  72227. GenericController.MODEL_FILENAME = 'generic.babylon';
  72228. return GenericController;
  72229. }(BABYLON.WebVRController));
  72230. BABYLON.GenericController = GenericController;
  72231. })(BABYLON || (BABYLON = {}));
  72232. //# sourceMappingURL=babylon.genericController.js.map
  72233. var BABYLON;
  72234. (function (BABYLON) {
  72235. /**
  72236. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  72237. */
  72238. var LoadedMeshInfo = /** @class */ (function () {
  72239. function LoadedMeshInfo() {
  72240. /**
  72241. * Map of the button meshes contained in the controller
  72242. */
  72243. this.buttonMeshes = {};
  72244. /**
  72245. * Map of the axis meshes contained in the controller
  72246. */
  72247. this.axisMeshes = {};
  72248. }
  72249. return LoadedMeshInfo;
  72250. }());
  72251. /**
  72252. * Defines the WindowsMotionController object that the state of the windows motion controller
  72253. */
  72254. var WindowsMotionController = /** @class */ (function (_super) {
  72255. __extends(WindowsMotionController, _super);
  72256. /**
  72257. * Creates a new WindowsMotionController from a gamepad
  72258. * @param vrGamepad the gamepad that the controller should be created from
  72259. */
  72260. function WindowsMotionController(vrGamepad) {
  72261. var _this = _super.call(this, vrGamepad) || this;
  72262. _this._mapping = {
  72263. // Semantic button names
  72264. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72265. // A mapping of the button name to glTF model node name
  72266. // that should be transformed by button value.
  72267. buttonMeshNames: {
  72268. 'trigger': 'SELECT',
  72269. 'menu': 'MENU',
  72270. 'grip': 'GRASP',
  72271. 'thumbstick': 'THUMBSTICK_PRESS',
  72272. 'trackpad': 'TOUCHPAD_PRESS'
  72273. },
  72274. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72275. buttonObservableNames: {
  72276. 'trigger': 'onTriggerStateChangedObservable',
  72277. 'menu': 'onSecondaryButtonStateChangedObservable',
  72278. 'grip': 'onMainButtonStateChangedObservable',
  72279. 'thumbstick': 'onPadStateChangedObservable',
  72280. 'trackpad': 'onTrackpadChangedObservable'
  72281. },
  72282. // A mapping of the axis name to glTF model node name
  72283. // that should be transformed by axis value.
  72284. // This array mirrors the browserGamepad.axes array, such that
  72285. // the mesh corresponding to axis 0 is in this array index 0.
  72286. axisMeshNames: [
  72287. 'THUMBSTICK_X',
  72288. 'THUMBSTICK_Y',
  72289. 'TOUCHPAD_TOUCH_X',
  72290. 'TOUCHPAD_TOUCH_Y'
  72291. ],
  72292. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72293. };
  72294. /**
  72295. * Fired when the trackpad on this controller is clicked
  72296. */
  72297. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72298. /**
  72299. * Fired when the trackpad on this controller is modified
  72300. */
  72301. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72302. /**
  72303. * The current x and y values of this controller's trackpad
  72304. */
  72305. _this.trackpad = { x: 0, y: 0 };
  72306. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72307. _this._loadedMeshInfo = null;
  72308. return _this;
  72309. }
  72310. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72311. /**
  72312. * Fired when the trigger on this controller is modified
  72313. */
  72314. get: function () {
  72315. return this.onTriggerStateChangedObservable;
  72316. },
  72317. enumerable: true,
  72318. configurable: true
  72319. });
  72320. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72321. /**
  72322. * Fired when the menu button on this controller is modified
  72323. */
  72324. get: function () {
  72325. return this.onSecondaryButtonStateChangedObservable;
  72326. },
  72327. enumerable: true,
  72328. configurable: true
  72329. });
  72330. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72331. /**
  72332. * Fired when the grip button on this controller is modified
  72333. */
  72334. get: function () {
  72335. return this.onMainButtonStateChangedObservable;
  72336. },
  72337. enumerable: true,
  72338. configurable: true
  72339. });
  72340. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72341. /**
  72342. * Fired when the thumbstick button on this controller is modified
  72343. */
  72344. get: function () {
  72345. return this.onPadStateChangedObservable;
  72346. },
  72347. enumerable: true,
  72348. configurable: true
  72349. });
  72350. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72351. /**
  72352. * Fired when the touchpad button on this controller is modified
  72353. */
  72354. get: function () {
  72355. return this.onTrackpadChangedObservable;
  72356. },
  72357. enumerable: true,
  72358. configurable: true
  72359. });
  72360. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72361. /**
  72362. * Fired when the touchpad values on this controller are modified
  72363. */
  72364. get: function () {
  72365. return this.onTrackpadValuesChangedObservable;
  72366. },
  72367. enumerable: true,
  72368. configurable: true
  72369. });
  72370. /**
  72371. * Called once per frame by the engine.
  72372. */
  72373. WindowsMotionController.prototype.update = function () {
  72374. _super.prototype.update.call(this);
  72375. if (this.browserGamepad.axes) {
  72376. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  72377. this.trackpad.x = this.browserGamepad["axes"][2];
  72378. this.trackpad.y = this.browserGamepad["axes"][3];
  72379. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72380. }
  72381. // Only need to animate axes if there is a loaded mesh
  72382. if (this._loadedMeshInfo) {
  72383. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72384. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72385. }
  72386. }
  72387. }
  72388. };
  72389. /**
  72390. * Called once for each button that changed state since the last frame
  72391. * @param buttonIdx Which button index changed
  72392. * @param state New state of the button
  72393. * @param changes Which properties on the state changed since last frame
  72394. */
  72395. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72396. var buttonName = this._mapping.buttons[buttonIdx];
  72397. if (!buttonName) {
  72398. return;
  72399. }
  72400. // Only emit events for buttons that we know how to map from index to name
  72401. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72402. if (observable) {
  72403. observable.notifyObservers(state);
  72404. }
  72405. this._lerpButtonTransform(buttonName, state.value);
  72406. };
  72407. /**
  72408. * Moves the buttons on the controller mesh based on their current state
  72409. * @param buttonName the name of the button to move
  72410. * @param buttonValue the value of the button which determines the buttons new position
  72411. */
  72412. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72413. // If there is no loaded mesh, there is nothing to transform.
  72414. if (!this._loadedMeshInfo) {
  72415. return;
  72416. }
  72417. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72418. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72419. return;
  72420. }
  72421. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72422. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72423. };
  72424. /**
  72425. * Moves the axis on the controller mesh based on its current state
  72426. * @param axis the index of the axis
  72427. * @param axisValue the value of the axis which determines the meshes new position
  72428. * @hidden
  72429. */
  72430. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72431. if (!this._loadedMeshInfo) {
  72432. return;
  72433. }
  72434. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72435. if (!meshInfo) {
  72436. return;
  72437. }
  72438. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72439. return;
  72440. }
  72441. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72442. var lerpValue = axisValue * 0.5 + 0.5;
  72443. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72444. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72445. };
  72446. /**
  72447. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72448. * @param scene scene in which to add meshes
  72449. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72450. */
  72451. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72452. var _this = this;
  72453. if (forceDefault === void 0) { forceDefault = false; }
  72454. var path;
  72455. var filename;
  72456. // Checking if GLB loader is present
  72457. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72458. // Determine the device specific folder based on the ID suffix
  72459. var device = 'default';
  72460. if (this.id && !forceDefault) {
  72461. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72462. device = ((match && match[0]) || device);
  72463. }
  72464. // Hand
  72465. if (this.hand === 'left') {
  72466. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72467. }
  72468. else { // Right is the default if no hand is specified
  72469. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72470. }
  72471. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72472. }
  72473. else {
  72474. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72475. path = BABYLON.GenericController.MODEL_BASE_URL;
  72476. filename = BABYLON.GenericController.MODEL_FILENAME;
  72477. }
  72478. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72479. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72480. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72481. if (!_this._loadedMeshInfo) {
  72482. return;
  72483. }
  72484. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72485. _this.attachToMesh(_this._defaultModel);
  72486. if (meshLoaded) {
  72487. meshLoaded(_this._defaultModel);
  72488. }
  72489. }, null, function (scene, message) {
  72490. BABYLON.Tools.Log(message);
  72491. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72492. if (!forceDefault) {
  72493. _this.initControllerMesh(scene, meshLoaded, true);
  72494. }
  72495. });
  72496. };
  72497. /**
  72498. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72499. * can be transformed by button presses and axes values, based on this._mapping.
  72500. *
  72501. * @param scene scene in which the meshes exist
  72502. * @param meshes list of meshes that make up the controller model to process
  72503. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72504. */
  72505. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72506. var loadedMeshInfo = null;
  72507. // Create a new mesh to contain the glTF hierarchy
  72508. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72509. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72510. var childMesh = null;
  72511. for (var i = 0; i < meshes.length; i++) {
  72512. var mesh = meshes[i];
  72513. if (!mesh.parent) {
  72514. // Exclude controller meshes from picking results
  72515. mesh.isPickable = false;
  72516. // Handle root node, attach to the new parentMesh
  72517. childMesh = mesh;
  72518. break;
  72519. }
  72520. }
  72521. if (childMesh) {
  72522. childMesh.setParent(parentMesh);
  72523. // Create our mesh info. Note that this method will always return non-null.
  72524. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72525. }
  72526. else {
  72527. BABYLON.Tools.Warn('Could not find root node in model file.');
  72528. }
  72529. return loadedMeshInfo;
  72530. };
  72531. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72532. var loadedMeshInfo = new LoadedMeshInfo();
  72533. var i;
  72534. loadedMeshInfo.rootNode = rootNode;
  72535. // Reset the caches
  72536. loadedMeshInfo.buttonMeshes = {};
  72537. loadedMeshInfo.axisMeshes = {};
  72538. // Button Meshes
  72539. for (i = 0; i < this._mapping.buttons.length; i++) {
  72540. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72541. if (!buttonMeshName) {
  72542. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72543. continue;
  72544. }
  72545. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72546. if (!buttonMesh) {
  72547. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72548. continue;
  72549. }
  72550. var buttonMeshInfo = {
  72551. index: i,
  72552. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72553. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72554. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72555. };
  72556. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72557. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72558. }
  72559. else {
  72560. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72561. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72562. '(VALUE: ' + !!buttonMeshInfo.value +
  72563. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72564. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72565. ')');
  72566. }
  72567. }
  72568. // Axis Meshes
  72569. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72570. var axisMeshName = this._mapping.axisMeshNames[i];
  72571. if (!axisMeshName) {
  72572. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72573. continue;
  72574. }
  72575. var axisMesh = getChildByName(rootNode, axisMeshName);
  72576. if (!axisMesh) {
  72577. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72578. continue;
  72579. }
  72580. var axisMeshInfo = {
  72581. index: i,
  72582. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72583. min: getImmediateChildByName(axisMesh, 'MIN'),
  72584. max: getImmediateChildByName(axisMesh, 'MAX')
  72585. };
  72586. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72587. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72588. }
  72589. else {
  72590. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72591. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72592. '(VALUE: ' + !!axisMeshInfo.value +
  72593. ', MIN: ' + !!axisMeshInfo.min +
  72594. ', MAX:' + !!axisMeshInfo.max +
  72595. ')');
  72596. }
  72597. }
  72598. // Pointing Ray
  72599. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72600. if (!loadedMeshInfo.pointingPoseNode) {
  72601. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72602. }
  72603. return loadedMeshInfo;
  72604. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72605. function getChildByName(node, name) {
  72606. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72607. }
  72608. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72609. function getImmediateChildByName(node, name) {
  72610. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72611. }
  72612. };
  72613. /**
  72614. * Gets the ray of the controller in the direction the controller is pointing
  72615. * @param length the length the resulting ray should be
  72616. * @returns a ray in the direction the controller is pointing
  72617. */
  72618. WindowsMotionController.prototype.getForwardRay = function (length) {
  72619. if (length === void 0) { length = 100; }
  72620. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72621. return _super.prototype.getForwardRay.call(this, length);
  72622. }
  72623. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72624. var origin = m.getTranslation();
  72625. var forward = new BABYLON.Vector3(0, 0, -1);
  72626. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72627. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72628. return new BABYLON.Ray(origin, direction, length);
  72629. };
  72630. /**
  72631. * Disposes of the controller
  72632. */
  72633. WindowsMotionController.prototype.dispose = function () {
  72634. _super.prototype.dispose.call(this);
  72635. this.onTrackpadChangedObservable.clear();
  72636. };
  72637. /**
  72638. * The base url used to load the left and right controller models
  72639. */
  72640. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72641. /**
  72642. * The name of the left controller model file
  72643. */
  72644. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72645. /**
  72646. * The name of the right controller model file
  72647. */
  72648. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72649. /**
  72650. * The controller name prefix for this controller type
  72651. */
  72652. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72653. /**
  72654. * The controller id pattern for this controller type
  72655. */
  72656. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72657. return WindowsMotionController;
  72658. }(BABYLON.WebVRController));
  72659. BABYLON.WindowsMotionController = WindowsMotionController;
  72660. })(BABYLON || (BABYLON = {}));
  72661. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72662. var BABYLON;
  72663. (function (BABYLON) {
  72664. /**
  72665. * Gear VR Controller
  72666. */
  72667. var GearVRController = /** @class */ (function (_super) {
  72668. __extends(GearVRController, _super);
  72669. /**
  72670. * Creates a new GearVRController from a gamepad
  72671. * @param vrGamepad the gamepad that the controller should be created from
  72672. */
  72673. function GearVRController(vrGamepad) {
  72674. var _this = _super.call(this, vrGamepad) || this;
  72675. _this._buttonIndexToObservableNameMap = [
  72676. 'onTrackpadChangedObservable',
  72677. 'onTriggerStateChangedObservable' // Trigger
  72678. ];
  72679. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72680. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72681. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72682. return _this;
  72683. }
  72684. /**
  72685. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72686. * @param scene scene in which to add meshes
  72687. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72688. */
  72689. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72690. var _this = this;
  72691. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72692. _this._defaultModel = newMeshes[1];
  72693. _this.attachToMesh(_this._defaultModel);
  72694. if (meshLoaded) {
  72695. meshLoaded(_this._defaultModel);
  72696. }
  72697. });
  72698. };
  72699. /**
  72700. * Called once for each button that changed state since the last frame
  72701. * @param buttonIdx Which button index changed
  72702. * @param state New state of the button
  72703. * @param changes Which properties on the state changed since last frame
  72704. */
  72705. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72706. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72707. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72708. // Only emit events for buttons that we know how to map from index to observable
  72709. var observable = this[observableName];
  72710. if (observable) {
  72711. observable.notifyObservers(state);
  72712. }
  72713. }
  72714. };
  72715. /**
  72716. * Base Url for the controller model.
  72717. */
  72718. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72719. /**
  72720. * File name for the controller model.
  72721. */
  72722. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72723. /**
  72724. * Gamepad Id prefix used to identify this controller.
  72725. */
  72726. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72727. return GearVRController;
  72728. }(BABYLON.WebVRController));
  72729. BABYLON.GearVRController = GearVRController;
  72730. })(BABYLON || (BABYLON = {}));
  72731. //# sourceMappingURL=babylon.gearVRController.js.map
  72732. var BABYLON;
  72733. (function (BABYLON) {
  72734. /**
  72735. * Google Daydream controller
  72736. */
  72737. var DaydreamController = /** @class */ (function (_super) {
  72738. __extends(DaydreamController, _super);
  72739. /**
  72740. * Creates a new DaydreamController from a gamepad
  72741. * @param vrGamepad the gamepad that the controller should be created from
  72742. */
  72743. function DaydreamController(vrGamepad) {
  72744. var _this = _super.call(this, vrGamepad) || this;
  72745. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72746. return _this;
  72747. }
  72748. /**
  72749. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72750. * @param scene scene in which to add meshes
  72751. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72752. */
  72753. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72754. var _this = this;
  72755. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72756. _this._defaultModel = newMeshes[1];
  72757. _this.attachToMesh(_this._defaultModel);
  72758. if (meshLoaded) {
  72759. meshLoaded(_this._defaultModel);
  72760. }
  72761. });
  72762. };
  72763. /**
  72764. * Called once for each button that changed state since the last frame
  72765. * @param buttonIdx Which button index changed
  72766. * @param state New state of the button
  72767. * @param changes Which properties on the state changed since last frame
  72768. */
  72769. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72770. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72771. if (buttonIdx === 0) {
  72772. var observable = this.onTriggerStateChangedObservable;
  72773. if (observable) {
  72774. observable.notifyObservers(state);
  72775. }
  72776. }
  72777. else {
  72778. // If the app or home buttons are ever made available
  72779. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72780. }
  72781. };
  72782. /**
  72783. * Base Url for the controller model.
  72784. */
  72785. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72786. /**
  72787. * File name for the controller model.
  72788. */
  72789. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72790. /**
  72791. * Gamepad Id prefix used to identify Daydream Controller.
  72792. */
  72793. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72794. return DaydreamController;
  72795. }(BABYLON.WebVRController));
  72796. BABYLON.DaydreamController = DaydreamController;
  72797. })(BABYLON || (BABYLON = {}));
  72798. //# sourceMappingURL=babylon.daydreamController.js.map
  72799. var BABYLON;
  72800. (function (BABYLON) {
  72801. var FollowCamera = /** @class */ (function (_super) {
  72802. __extends(FollowCamera, _super);
  72803. function FollowCamera(name, position, scene, lockedTarget) {
  72804. if (lockedTarget === void 0) { lockedTarget = null; }
  72805. var _this = _super.call(this, name, position, scene) || this;
  72806. _this.radius = 12;
  72807. _this.rotationOffset = 0;
  72808. _this.heightOffset = 4;
  72809. _this.cameraAcceleration = 0.05;
  72810. _this.maxCameraSpeed = 20;
  72811. _this.lockedTarget = lockedTarget;
  72812. return _this;
  72813. }
  72814. FollowCamera.prototype.getRadians = function (degrees) {
  72815. return degrees * Math.PI / 180;
  72816. };
  72817. FollowCamera.prototype.follow = function (cameraTarget) {
  72818. if (!cameraTarget)
  72819. return;
  72820. var yRotation;
  72821. if (cameraTarget.rotationQuaternion) {
  72822. var rotMatrix = new BABYLON.Matrix();
  72823. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72824. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72825. }
  72826. else {
  72827. yRotation = cameraTarget.rotation.y;
  72828. }
  72829. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72830. var targetPosition = cameraTarget.getAbsolutePosition();
  72831. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72832. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72833. var dx = targetX - this.position.x;
  72834. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72835. var dz = (targetZ) - this.position.z;
  72836. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72837. var vy = dy * this.cameraAcceleration;
  72838. var vz = dz * this.cameraAcceleration * 2;
  72839. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72840. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72841. }
  72842. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72843. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72844. }
  72845. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72846. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72847. }
  72848. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72849. this.setTarget(targetPosition);
  72850. };
  72851. FollowCamera.prototype._checkInputs = function () {
  72852. _super.prototype._checkInputs.call(this);
  72853. if (this.lockedTarget) {
  72854. this.follow(this.lockedTarget);
  72855. }
  72856. };
  72857. FollowCamera.prototype.getClassName = function () {
  72858. return "FollowCamera";
  72859. };
  72860. __decorate([
  72861. BABYLON.serialize()
  72862. ], FollowCamera.prototype, "radius", void 0);
  72863. __decorate([
  72864. BABYLON.serialize()
  72865. ], FollowCamera.prototype, "rotationOffset", void 0);
  72866. __decorate([
  72867. BABYLON.serialize()
  72868. ], FollowCamera.prototype, "heightOffset", void 0);
  72869. __decorate([
  72870. BABYLON.serialize()
  72871. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72872. __decorate([
  72873. BABYLON.serialize()
  72874. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72875. __decorate([
  72876. BABYLON.serializeAsMeshReference("lockedTargetId")
  72877. ], FollowCamera.prototype, "lockedTarget", void 0);
  72878. return FollowCamera;
  72879. }(BABYLON.TargetCamera));
  72880. BABYLON.FollowCamera = FollowCamera;
  72881. var ArcFollowCamera = /** @class */ (function (_super) {
  72882. __extends(ArcFollowCamera, _super);
  72883. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72884. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72885. _this.alpha = alpha;
  72886. _this.beta = beta;
  72887. _this.radius = radius;
  72888. _this.target = target;
  72889. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72890. _this.follow();
  72891. return _this;
  72892. }
  72893. ArcFollowCamera.prototype.follow = function () {
  72894. if (!this.target) {
  72895. return;
  72896. }
  72897. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72898. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72899. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72900. var targetPosition = this.target.getAbsolutePosition();
  72901. this.position = targetPosition.add(this._cartesianCoordinates);
  72902. this.setTarget(targetPosition);
  72903. };
  72904. ArcFollowCamera.prototype._checkInputs = function () {
  72905. _super.prototype._checkInputs.call(this);
  72906. this.follow();
  72907. };
  72908. ArcFollowCamera.prototype.getClassName = function () {
  72909. return "ArcFollowCamera";
  72910. };
  72911. return ArcFollowCamera;
  72912. }(BABYLON.TargetCamera));
  72913. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72914. })(BABYLON || (BABYLON = {}));
  72915. //# sourceMappingURL=babylon.followCamera.js.map
  72916. var BABYLON;
  72917. (function (BABYLON) {
  72918. // We're mainly based on the logic defined into the FreeCamera code
  72919. var UniversalCamera = /** @class */ (function (_super) {
  72920. __extends(UniversalCamera, _super);
  72921. //-- end properties for backward compatibility for inputs
  72922. function UniversalCamera(name, position, scene) {
  72923. var _this = _super.call(this, name, position, scene) || this;
  72924. _this.inputs.addGamepad();
  72925. return _this;
  72926. }
  72927. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72928. //-- Begin properties for backward compatibility for inputs
  72929. get: function () {
  72930. var gamepad = this.inputs.attached["gamepad"];
  72931. if (gamepad)
  72932. return gamepad.gamepadAngularSensibility;
  72933. return 0;
  72934. },
  72935. set: function (value) {
  72936. var gamepad = this.inputs.attached["gamepad"];
  72937. if (gamepad)
  72938. gamepad.gamepadAngularSensibility = value;
  72939. },
  72940. enumerable: true,
  72941. configurable: true
  72942. });
  72943. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72944. get: function () {
  72945. var gamepad = this.inputs.attached["gamepad"];
  72946. if (gamepad)
  72947. return gamepad.gamepadMoveSensibility;
  72948. return 0;
  72949. },
  72950. set: function (value) {
  72951. var gamepad = this.inputs.attached["gamepad"];
  72952. if (gamepad)
  72953. gamepad.gamepadMoveSensibility = value;
  72954. },
  72955. enumerable: true,
  72956. configurable: true
  72957. });
  72958. UniversalCamera.prototype.getClassName = function () {
  72959. return "UniversalCamera";
  72960. };
  72961. return UniversalCamera;
  72962. }(BABYLON.TouchCamera));
  72963. BABYLON.UniversalCamera = UniversalCamera;
  72964. })(BABYLON || (BABYLON = {}));
  72965. //# sourceMappingURL=babylon.universalCamera.js.map
  72966. var BABYLON;
  72967. (function (BABYLON) {
  72968. // We're mainly based on the logic defined into the FreeCamera code
  72969. var GamepadCamera = /** @class */ (function (_super) {
  72970. __extends(GamepadCamera, _super);
  72971. //-- end properties for backward compatibility for inputs
  72972. function GamepadCamera(name, position, scene) {
  72973. return _super.call(this, name, position, scene) || this;
  72974. }
  72975. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72976. //-- Begin properties for backward compatibility for inputs
  72977. get: function () {
  72978. var gamepad = this.inputs.attached["gamepad"];
  72979. if (gamepad)
  72980. return gamepad.gamepadAngularSensibility;
  72981. return 0;
  72982. },
  72983. set: function (value) {
  72984. var gamepad = this.inputs.attached["gamepad"];
  72985. if (gamepad)
  72986. gamepad.gamepadAngularSensibility = value;
  72987. },
  72988. enumerable: true,
  72989. configurable: true
  72990. });
  72991. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72992. get: function () {
  72993. var gamepad = this.inputs.attached["gamepad"];
  72994. if (gamepad)
  72995. return gamepad.gamepadMoveSensibility;
  72996. return 0;
  72997. },
  72998. set: function (value) {
  72999. var gamepad = this.inputs.attached["gamepad"];
  73000. if (gamepad)
  73001. gamepad.gamepadMoveSensibility = value;
  73002. },
  73003. enumerable: true,
  73004. configurable: true
  73005. });
  73006. GamepadCamera.prototype.getClassName = function () {
  73007. return "GamepadCamera";
  73008. };
  73009. return GamepadCamera;
  73010. }(BABYLON.UniversalCamera));
  73011. BABYLON.GamepadCamera = GamepadCamera;
  73012. })(BABYLON || (BABYLON = {}));
  73013. //# sourceMappingURL=babylon.gamepadCamera.js.map
  73014. var BABYLON;
  73015. (function (BABYLON) {
  73016. var PostProcessRenderPipelineManager = /** @class */ (function () {
  73017. function PostProcessRenderPipelineManager() {
  73018. this._renderPipelines = {};
  73019. }
  73020. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  73021. this._renderPipelines[renderPipeline._name] = renderPipeline;
  73022. };
  73023. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  73024. if (unique === void 0) { unique = false; }
  73025. var renderPipeline = this._renderPipelines[renderPipelineName];
  73026. if (!renderPipeline) {
  73027. return;
  73028. }
  73029. renderPipeline._attachCameras(cameras, unique);
  73030. };
  73031. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  73032. var renderPipeline = this._renderPipelines[renderPipelineName];
  73033. if (!renderPipeline) {
  73034. return;
  73035. }
  73036. renderPipeline._detachCameras(cameras);
  73037. };
  73038. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73039. var renderPipeline = this._renderPipelines[renderPipelineName];
  73040. if (!renderPipeline) {
  73041. return;
  73042. }
  73043. renderPipeline._enableEffect(renderEffectName, cameras);
  73044. };
  73045. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73046. var renderPipeline = this._renderPipelines[renderPipelineName];
  73047. if (!renderPipeline) {
  73048. return;
  73049. }
  73050. renderPipeline._disableEffect(renderEffectName, cameras);
  73051. };
  73052. PostProcessRenderPipelineManager.prototype.update = function () {
  73053. for (var renderPipelineName in this._renderPipelines) {
  73054. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73055. var pipeline = this._renderPipelines[renderPipelineName];
  73056. if (!pipeline.isSupported) {
  73057. pipeline.dispose();
  73058. delete this._renderPipelines[renderPipelineName];
  73059. }
  73060. else {
  73061. pipeline._update();
  73062. }
  73063. }
  73064. }
  73065. };
  73066. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  73067. for (var renderPipelineName in this._renderPipelines) {
  73068. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73069. var pipeline = this._renderPipelines[renderPipelineName];
  73070. pipeline._rebuild();
  73071. }
  73072. }
  73073. };
  73074. PostProcessRenderPipelineManager.prototype.dispose = function () {
  73075. for (var renderPipelineName in this._renderPipelines) {
  73076. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73077. var pipeline = this._renderPipelines[renderPipelineName];
  73078. pipeline.dispose();
  73079. }
  73080. }
  73081. };
  73082. return PostProcessRenderPipelineManager;
  73083. }());
  73084. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  73085. })(BABYLON || (BABYLON = {}));
  73086. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  73087. var BABYLON;
  73088. (function (BABYLON) {
  73089. /**
  73090. * This represents a set of one or more post processes in Babylon.
  73091. * A post process can be used to apply a shader to a texture after it is rendered.
  73092. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  73093. */
  73094. var PostProcessRenderEffect = /** @class */ (function () {
  73095. /**
  73096. * Instantiates a post process render effect.
  73097. * A post process can be used to apply a shader to a texture after it is rendered.
  73098. * @param engine The engine the effect is tied to
  73099. * @param name The name of the effect
  73100. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  73101. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  73102. */
  73103. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  73104. this._name = name;
  73105. this._singleInstance = singleInstance || true;
  73106. this._getPostProcesses = getPostProcesses;
  73107. this._cameras = {};
  73108. this._indicesForCamera = {};
  73109. this._postProcesses = {};
  73110. }
  73111. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  73112. /**
  73113. * Checks if all the post processes in the effect are supported.
  73114. */
  73115. get: function () {
  73116. for (var index in this._postProcesses) {
  73117. if (this._postProcesses.hasOwnProperty(index)) {
  73118. var pps = this._postProcesses[index];
  73119. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  73120. if (!pps[ppIndex].isSupported) {
  73121. return false;
  73122. }
  73123. }
  73124. }
  73125. }
  73126. return true;
  73127. },
  73128. enumerable: true,
  73129. configurable: true
  73130. });
  73131. /**
  73132. * Updates the current state of the effect
  73133. */
  73134. PostProcessRenderEffect.prototype._update = function () {
  73135. };
  73136. /**
  73137. * Attaches the effect on cameras
  73138. * @param cameras The camera to attach to.
  73139. */
  73140. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  73141. var _this = this;
  73142. var cameraKey;
  73143. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73144. if (!cams) {
  73145. return;
  73146. }
  73147. for (var i = 0; i < cams.length; i++) {
  73148. var camera = cams[i];
  73149. var cameraName = camera.name;
  73150. if (this._singleInstance) {
  73151. cameraKey = 0;
  73152. }
  73153. else {
  73154. cameraKey = cameraName;
  73155. }
  73156. if (!this._postProcesses[cameraKey]) {
  73157. var postProcess = this._getPostProcesses();
  73158. if (postProcess) {
  73159. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  73160. }
  73161. }
  73162. if (!this._indicesForCamera[cameraName]) {
  73163. this._indicesForCamera[cameraName] = [];
  73164. }
  73165. this._postProcesses[cameraKey].forEach(function (postProcess) {
  73166. var index = camera.attachPostProcess(postProcess);
  73167. _this._indicesForCamera[cameraName].push(index);
  73168. });
  73169. if (!this._cameras[cameraName]) {
  73170. this._cameras[cameraName] = camera;
  73171. }
  73172. }
  73173. };
  73174. /**
  73175. * Detatches the effect on cameras
  73176. * @param cameras The camera to detatch from.
  73177. */
  73178. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  73179. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73180. if (!cams) {
  73181. return;
  73182. }
  73183. for (var i = 0; i < cams.length; i++) {
  73184. var camera = cams[i];
  73185. var cameraName = camera.name;
  73186. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73187. camera.detachPostProcess(postProcess);
  73188. });
  73189. if (this._cameras[cameraName]) {
  73190. //this._indicesForCamera.splice(index, 1);
  73191. this._cameras[cameraName] = null;
  73192. }
  73193. }
  73194. };
  73195. /**
  73196. * Enables the effect on given cameras
  73197. * @param cameras The camera to enable.
  73198. */
  73199. PostProcessRenderEffect.prototype._enable = function (cameras) {
  73200. var _this = this;
  73201. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73202. if (!cams) {
  73203. return;
  73204. }
  73205. for (var i = 0; i < cams.length; i++) {
  73206. var camera = cams[i];
  73207. var cameraName = camera.name;
  73208. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  73209. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  73210. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73211. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  73212. });
  73213. }
  73214. }
  73215. }
  73216. };
  73217. /**
  73218. * Disables the effect on the given cameras
  73219. * @param cameras The camera to disable.
  73220. */
  73221. PostProcessRenderEffect.prototype._disable = function (cameras) {
  73222. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73223. if (!cams) {
  73224. return;
  73225. }
  73226. for (var i = 0; i < cams.length; i++) {
  73227. var camera = cams[i];
  73228. var cameraName = camera.name;
  73229. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73230. camera.detachPostProcess(postProcess);
  73231. });
  73232. }
  73233. };
  73234. /**
  73235. * Gets a list of the post processes contained in the effect.
  73236. * @param camera The camera to get the post processes on.
  73237. * @returns The list of the post processes in the effect.
  73238. */
  73239. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73240. if (this._singleInstance) {
  73241. return this._postProcesses[0];
  73242. }
  73243. else {
  73244. if (!camera) {
  73245. return null;
  73246. }
  73247. return this._postProcesses[camera.name];
  73248. }
  73249. };
  73250. return PostProcessRenderEffect;
  73251. }());
  73252. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73253. })(BABYLON || (BABYLON = {}));
  73254. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73255. var BABYLON;
  73256. (function (BABYLON) {
  73257. var PostProcessRenderPipeline = /** @class */ (function () {
  73258. function PostProcessRenderPipeline(engine, name) {
  73259. this.engine = engine;
  73260. this._name = name;
  73261. this._renderEffects = {};
  73262. this._renderEffectsForIsolatedPass = new Array();
  73263. this._cameras = [];
  73264. }
  73265. PostProcessRenderPipeline.prototype.getClassName = function () {
  73266. return "PostProcessRenderPipeline";
  73267. };
  73268. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73269. get: function () {
  73270. for (var renderEffectName in this._renderEffects) {
  73271. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73272. if (!this._renderEffects[renderEffectName].isSupported) {
  73273. return false;
  73274. }
  73275. }
  73276. }
  73277. return true;
  73278. },
  73279. enumerable: true,
  73280. configurable: true
  73281. });
  73282. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73283. this._renderEffects[renderEffect._name] = renderEffect;
  73284. };
  73285. // private
  73286. PostProcessRenderPipeline.prototype._rebuild = function () {
  73287. };
  73288. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73289. var renderEffects = this._renderEffects[renderEffectName];
  73290. if (!renderEffects) {
  73291. return;
  73292. }
  73293. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73294. };
  73295. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73296. var renderEffects = this._renderEffects[renderEffectName];
  73297. if (!renderEffects) {
  73298. return;
  73299. }
  73300. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73301. };
  73302. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73303. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73304. if (!cams) {
  73305. return;
  73306. }
  73307. var indicesToDelete = [];
  73308. var i;
  73309. for (i = 0; i < cams.length; i++) {
  73310. var camera = cams[i];
  73311. var cameraName = camera.name;
  73312. if (this._cameras.indexOf(camera) === -1) {
  73313. this._cameras[cameraName] = camera;
  73314. }
  73315. else if (unique) {
  73316. indicesToDelete.push(i);
  73317. }
  73318. }
  73319. for (i = 0; i < indicesToDelete.length; i++) {
  73320. cameras.splice(indicesToDelete[i], 1);
  73321. }
  73322. for (var renderEffectName in this._renderEffects) {
  73323. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73324. this._renderEffects[renderEffectName]._attachCameras(cams);
  73325. }
  73326. }
  73327. };
  73328. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73329. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73330. if (!cams) {
  73331. return;
  73332. }
  73333. for (var renderEffectName in this._renderEffects) {
  73334. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73335. this._renderEffects[renderEffectName]._detachCameras(cams);
  73336. }
  73337. }
  73338. for (var i = 0; i < cams.length; i++) {
  73339. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73340. }
  73341. };
  73342. PostProcessRenderPipeline.prototype._update = function () {
  73343. for (var renderEffectName in this._renderEffects) {
  73344. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73345. this._renderEffects[renderEffectName]._update();
  73346. }
  73347. }
  73348. for (var i = 0; i < this._cameras.length; i++) {
  73349. var cameraName = this._cameras[i].name;
  73350. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73351. this._renderEffectsForIsolatedPass[cameraName]._update();
  73352. }
  73353. }
  73354. };
  73355. PostProcessRenderPipeline.prototype._reset = function () {
  73356. this._renderEffects = {};
  73357. this._renderEffectsForIsolatedPass = new Array();
  73358. };
  73359. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73360. // Set samples of the very first post process to 4 to enable native anti-aliasing in browsers that support webGL 2.0 (See: https://github.com/BabylonJS/Babylon.js/issues/3754)
  73361. var effectKeys = Object.keys(this._renderEffects);
  73362. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73363. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73364. if (postProcesses) {
  73365. postProcesses[0].samples = sampleCount;
  73366. return true;
  73367. }
  73368. }
  73369. return false;
  73370. };
  73371. PostProcessRenderPipeline.prototype.dispose = function () {
  73372. // Must be implemented by children
  73373. };
  73374. __decorate([
  73375. BABYLON.serialize()
  73376. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73377. return PostProcessRenderPipeline;
  73378. }());
  73379. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73380. })(BABYLON || (BABYLON = {}));
  73381. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73382. var BABYLON;
  73383. (function (BABYLON) {
  73384. /**
  73385. * This represents a depth renderer in Babylon.
  73386. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73387. */
  73388. var DepthRenderer = /** @class */ (function () {
  73389. /**
  73390. * Instantiates a depth renderer
  73391. * @param scene The scene the renderer belongs to
  73392. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73393. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73394. */
  73395. function DepthRenderer(scene, type, camera) {
  73396. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73397. if (camera === void 0) { camera = null; }
  73398. var _this = this;
  73399. this._scene = scene;
  73400. this._camera = camera;
  73401. var engine = scene.getEngine();
  73402. // Render target
  73403. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73404. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73405. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73406. this._depthMap.refreshRate = 1;
  73407. this._depthMap.renderParticles = false;
  73408. this._depthMap.renderList = null;
  73409. // Camera to get depth map from to support multiple concurrent cameras
  73410. this._depthMap.activeCamera = this._camera;
  73411. this._depthMap.ignoreCameraViewport = true;
  73412. this._depthMap.useCameraPostProcesses = false;
  73413. // set default depth value to 1.0 (far away)
  73414. this._depthMap.onClearObservable.add(function (engine) {
  73415. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73416. });
  73417. // Custom render function
  73418. var renderSubMesh = function (subMesh) {
  73419. var mesh = subMesh.getRenderingMesh();
  73420. var scene = _this._scene;
  73421. var engine = scene.getEngine();
  73422. var material = subMesh.getMaterial();
  73423. if (!material) {
  73424. return;
  73425. }
  73426. // Culling and reverse (right handed system)
  73427. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73428. // Managing instances
  73429. var batch = mesh._getInstancesRenderList(subMesh._id);
  73430. if (batch.mustReturn) {
  73431. return;
  73432. }
  73433. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73434. var camera = _this._camera || scene.activeCamera;
  73435. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73436. engine.enableEffect(_this._effect);
  73437. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73438. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73439. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73440. // Alpha test
  73441. if (material && material.needAlphaTesting()) {
  73442. var alphaTexture = material.getAlphaTestTexture();
  73443. if (alphaTexture) {
  73444. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73445. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73446. }
  73447. }
  73448. // Bones
  73449. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73450. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73451. }
  73452. // Draw
  73453. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73454. }
  73455. };
  73456. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73457. var index;
  73458. if (depthOnlySubMeshes.length) {
  73459. engine.setColorWrite(false);
  73460. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73461. renderSubMesh(depthOnlySubMeshes.data[index]);
  73462. }
  73463. engine.setColorWrite(true);
  73464. }
  73465. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73466. renderSubMesh(opaqueSubMeshes.data[index]);
  73467. }
  73468. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73469. renderSubMesh(alphaTestSubMeshes.data[index]);
  73470. }
  73471. };
  73472. }
  73473. /**
  73474. * Creates the depth rendering effect and checks if the effect is ready.
  73475. * @param subMesh The submesh to be used to render the depth map of
  73476. * @param useInstances If multiple world instances should be used
  73477. * @returns if the depth renderer is ready to render the depth map
  73478. */
  73479. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73480. var material = subMesh.getMaterial();
  73481. if (material.disableDepthWrite) {
  73482. return false;
  73483. }
  73484. var defines = [];
  73485. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73486. var mesh = subMesh.getMesh();
  73487. // Alpha test
  73488. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73489. defines.push("#define ALPHATEST");
  73490. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73491. attribs.push(BABYLON.VertexBuffer.UVKind);
  73492. defines.push("#define UV1");
  73493. }
  73494. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73495. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73496. defines.push("#define UV2");
  73497. }
  73498. }
  73499. // Bones
  73500. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73501. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73502. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73503. if (mesh.numBoneInfluencers > 4) {
  73504. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73505. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73506. }
  73507. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73508. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73509. }
  73510. else {
  73511. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73512. }
  73513. // Instances
  73514. if (useInstances) {
  73515. defines.push("#define INSTANCES");
  73516. attribs.push("world0");
  73517. attribs.push("world1");
  73518. attribs.push("world2");
  73519. attribs.push("world3");
  73520. }
  73521. // Get correct effect
  73522. var join = defines.join("\n");
  73523. if (this._cachedDefines !== join) {
  73524. this._cachedDefines = join;
  73525. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73526. }
  73527. return this._effect.isReady();
  73528. };
  73529. /**
  73530. * Gets the texture which the depth map will be written to.
  73531. * @returns The depth map texture
  73532. */
  73533. DepthRenderer.prototype.getDepthMap = function () {
  73534. return this._depthMap;
  73535. };
  73536. /**
  73537. * Disposes of the depth renderer.
  73538. */
  73539. DepthRenderer.prototype.dispose = function () {
  73540. this._depthMap.dispose();
  73541. };
  73542. return DepthRenderer;
  73543. }());
  73544. BABYLON.DepthRenderer = DepthRenderer;
  73545. })(BABYLON || (BABYLON = {}));
  73546. //# sourceMappingURL=babylon.depthRenderer.js.map
  73547. var BABYLON;
  73548. (function (BABYLON) {
  73549. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73550. __extends(SSAORenderingPipeline, _super);
  73551. /**
  73552. * @constructor
  73553. * @param {string} name - The rendering pipeline name
  73554. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73555. * @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 }
  73556. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73557. */
  73558. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73559. var _this = _super.call(this, scene.getEngine(), name) || this;
  73560. // Members
  73561. /**
  73562. * The PassPostProcess id in the pipeline that contains the original scene color
  73563. */
  73564. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73565. /**
  73566. * The SSAO PostProcess id in the pipeline
  73567. */
  73568. _this.SSAORenderEffect = "SSAORenderEffect";
  73569. /**
  73570. * The horizontal blur PostProcess id in the pipeline
  73571. */
  73572. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73573. /**
  73574. * The vertical blur PostProcess id in the pipeline
  73575. */
  73576. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73577. /**
  73578. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73579. */
  73580. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73581. /**
  73582. * The output strength of the SSAO post-process. Default value is 1.0.
  73583. */
  73584. _this.totalStrength = 1.0;
  73585. /**
  73586. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73587. */
  73588. _this.radius = 0.0001;
  73589. /**
  73590. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73591. * Must not be equal to fallOff and superior to fallOff.
  73592. * Default value is 0.975
  73593. */
  73594. _this.area = 0.0075;
  73595. /**
  73596. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73597. * Must not be equal to area and inferior to area.
  73598. * Default value is 0.0
  73599. */
  73600. _this.fallOff = 0.000001;
  73601. /**
  73602. * The base color of the SSAO post-process
  73603. * The final result is "base + ssao" between [0, 1]
  73604. */
  73605. _this.base = 0.5;
  73606. _this._firstUpdate = true;
  73607. _this._scene = scene;
  73608. // Set up assets
  73609. _this._createRandomTexture();
  73610. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73611. var ssaoRatio = ratio.ssaoRatio || ratio;
  73612. var combineRatio = ratio.combineRatio || ratio;
  73613. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73614. _this._createSSAOPostProcess(ssaoRatio);
  73615. _this._createBlurPostProcess(ssaoRatio);
  73616. _this._createSSAOCombinePostProcess(combineRatio);
  73617. // Set up pipeline
  73618. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73619. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73620. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73621. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73622. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73623. // Finish
  73624. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73625. if (cameras)
  73626. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73627. return _this;
  73628. }
  73629. // Public Methods
  73630. /**
  73631. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73632. */
  73633. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73634. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73635. for (var i = 0; i < this._scene.cameras.length; i++) {
  73636. var camera = this._scene.cameras[i];
  73637. this._originalColorPostProcess.dispose(camera);
  73638. this._ssaoPostProcess.dispose(camera);
  73639. this._blurHPostProcess.dispose(camera);
  73640. this._blurVPostProcess.dispose(camera);
  73641. this._ssaoCombinePostProcess.dispose(camera);
  73642. }
  73643. this._randomTexture.dispose();
  73644. if (disableDepthRender)
  73645. this._scene.disableDepthRenderer();
  73646. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73647. _super.prototype.dispose.call(this);
  73648. };
  73649. // Private Methods
  73650. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73651. var _this = this;
  73652. var size = 16;
  73653. this._blurHPostProcess = new BABYLON.BlurPostProcess("BlurH", new BABYLON.Vector2(1, 0), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  73654. this._blurVPostProcess = new BABYLON.BlurPostProcess("BlurV", new BABYLON.Vector2(0, 1), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  73655. this._blurHPostProcess.onActivateObservable.add(function () {
  73656. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73657. _this._blurHPostProcess.kernel = size * dw;
  73658. });
  73659. this._blurVPostProcess.onActivateObservable.add(function () {
  73660. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73661. _this._blurVPostProcess.kernel = size * dw;
  73662. });
  73663. };
  73664. SSAORenderingPipeline.prototype._rebuild = function () {
  73665. this._firstUpdate = true;
  73666. _super.prototype._rebuild.call(this);
  73667. };
  73668. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73669. var _this = this;
  73670. var numSamples = 16;
  73671. var sampleSphere = [
  73672. 0.5381, 0.1856, -0.4319,
  73673. 0.1379, 0.2486, 0.4430,
  73674. 0.3371, 0.5679, -0.0057,
  73675. -0.6999, -0.0451, -0.0019,
  73676. 0.0689, -0.1598, -0.8547,
  73677. 0.0560, 0.0069, -0.1843,
  73678. -0.0146, 0.1402, 0.0762,
  73679. 0.0100, -0.1924, -0.0344,
  73680. -0.3577, -0.5301, -0.4358,
  73681. -0.3169, 0.1063, 0.0158,
  73682. 0.0103, -0.5869, 0.0046,
  73683. -0.0897, -0.4940, 0.3287,
  73684. 0.7119, -0.0154, -0.0918,
  73685. -0.0533, 0.0596, -0.5411,
  73686. 0.0352, -0.0631, 0.5460,
  73687. -0.4776, 0.2847, -0.0271
  73688. ];
  73689. var samplesFactor = 1.0 / numSamples;
  73690. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73691. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73692. "area", "fallOff", "base", "range", "viewport"
  73693. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73694. this._ssaoPostProcess.onApply = function (effect) {
  73695. if (_this._firstUpdate) {
  73696. effect.setArray3("sampleSphere", sampleSphere);
  73697. effect.setFloat("samplesFactor", samplesFactor);
  73698. effect.setFloat("randTextureTiles", 4.0);
  73699. }
  73700. effect.setFloat("totalStrength", _this.totalStrength);
  73701. effect.setFloat("radius", _this.radius);
  73702. effect.setFloat("area", _this.area);
  73703. effect.setFloat("fallOff", _this.fallOff);
  73704. effect.setFloat("base", _this.base);
  73705. effect.setTexture("textureSampler", _this._depthTexture);
  73706. effect.setTexture("randomSampler", _this._randomTexture);
  73707. };
  73708. };
  73709. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73710. var _this = this;
  73711. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73712. this._ssaoCombinePostProcess.onApply = function (effect) {
  73713. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73714. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73715. };
  73716. };
  73717. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73718. var size = 512;
  73719. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73720. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73721. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73722. var context = this._randomTexture.getContext();
  73723. var rand = function (min, max) {
  73724. return Math.random() * (max - min) + min;
  73725. };
  73726. var randVector = BABYLON.Vector3.Zero();
  73727. for (var x = 0; x < size; x++) {
  73728. for (var y = 0; y < size; y++) {
  73729. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73730. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73731. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73732. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73733. context.fillRect(x, y, 1, 1);
  73734. }
  73735. }
  73736. this._randomTexture.update(false);
  73737. };
  73738. __decorate([
  73739. BABYLON.serialize()
  73740. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73741. __decorate([
  73742. BABYLON.serialize()
  73743. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73744. __decorate([
  73745. BABYLON.serialize()
  73746. ], SSAORenderingPipeline.prototype, "area", void 0);
  73747. __decorate([
  73748. BABYLON.serialize()
  73749. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73750. __decorate([
  73751. BABYLON.serialize()
  73752. ], SSAORenderingPipeline.prototype, "base", void 0);
  73753. return SSAORenderingPipeline;
  73754. }(BABYLON.PostProcessRenderPipeline));
  73755. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73756. })(BABYLON || (BABYLON = {}));
  73757. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73758. var BABYLON;
  73759. (function (BABYLON) {
  73760. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73761. __extends(SSAO2RenderingPipeline, _super);
  73762. /**
  73763. * @constructor
  73764. * @param {string} name - The rendering pipeline name
  73765. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73766. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, blurRatio: 1.0 }
  73767. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73768. */
  73769. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73770. var _this = _super.call(this, scene.getEngine(), name) || this;
  73771. // Members
  73772. /**
  73773. * The PassPostProcess id in the pipeline that contains the original scene color
  73774. */
  73775. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73776. /**
  73777. * The SSAO PostProcess id in the pipeline
  73778. */
  73779. _this.SSAORenderEffect = "SSAORenderEffect";
  73780. /**
  73781. * The horizontal blur PostProcess id in the pipeline
  73782. */
  73783. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73784. /**
  73785. * The vertical blur PostProcess id in the pipeline
  73786. */
  73787. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73788. /**
  73789. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73790. */
  73791. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73792. /**
  73793. * The output strength of the SSAO post-process. Default value is 1.0.
  73794. */
  73795. _this.totalStrength = 1.0;
  73796. /**
  73797. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73798. */
  73799. _this.maxZ = 100.0;
  73800. /**
  73801. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73802. */
  73803. _this.minZAspect = 0.2;
  73804. /**
  73805. * Number of samples used for the SSAO calculations. Default value is 8
  73806. */
  73807. _this._samples = 8;
  73808. /**
  73809. * Are we using bilateral blur ?
  73810. */
  73811. _this._expensiveBlur = true;
  73812. /**
  73813. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73814. */
  73815. _this.radius = 2.0;
  73816. /**
  73817. * The base color of the SSAO post-process
  73818. * The final result is "base + ssao" between [0, 1]
  73819. */
  73820. _this.base = 0.1;
  73821. _this._firstUpdate = true;
  73822. _this._scene = scene;
  73823. _this._ratio = ratio;
  73824. if (!_this.isSupported) {
  73825. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73826. return _this;
  73827. }
  73828. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73829. var blurRatio = _this._ratio.blurRatio || ratio;
  73830. // Set up assets
  73831. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73832. _this._createRandomTexture();
  73833. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73834. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73835. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73836. _this._createSSAOPostProcess(1.0);
  73837. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73838. _this._createSSAOCombinePostProcess(blurRatio);
  73839. // Set up pipeline
  73840. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73841. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73842. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73843. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73844. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73845. // Finish
  73846. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73847. if (cameras)
  73848. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73849. return _this;
  73850. }
  73851. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73852. get: function () {
  73853. return this._samples;
  73854. },
  73855. set: function (n) {
  73856. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73857. this._samples = n;
  73858. this._sampleSphere = this._generateHemisphere();
  73859. this._firstUpdate = true;
  73860. },
  73861. enumerable: true,
  73862. configurable: true
  73863. });
  73864. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73865. get: function () {
  73866. return this._expensiveBlur;
  73867. },
  73868. set: function (b) {
  73869. this._blurHPostProcess.updateEffect("#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73870. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73871. this._expensiveBlur = b;
  73872. this._firstUpdate = true;
  73873. },
  73874. enumerable: true,
  73875. configurable: true
  73876. });
  73877. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73878. /**
  73879. * Support test.
  73880. */
  73881. get: function () {
  73882. var engine = BABYLON.Engine.LastCreatedEngine;
  73883. if (!engine) {
  73884. return false;
  73885. }
  73886. return engine.getCaps().drawBuffersExtension;
  73887. },
  73888. enumerable: true,
  73889. configurable: true
  73890. });
  73891. // Public Methods
  73892. /**
  73893. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73894. */
  73895. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73896. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73897. for (var i = 0; i < this._scene.cameras.length; i++) {
  73898. var camera = this._scene.cameras[i];
  73899. this._originalColorPostProcess.dispose(camera);
  73900. this._ssaoPostProcess.dispose(camera);
  73901. this._blurHPostProcess.dispose(camera);
  73902. this._blurVPostProcess.dispose(camera);
  73903. this._ssaoCombinePostProcess.dispose(camera);
  73904. }
  73905. this._randomTexture.dispose();
  73906. if (disableGeometryBufferRenderer)
  73907. this._scene.disableGeometryBufferRenderer();
  73908. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73909. _super.prototype.dispose.call(this);
  73910. };
  73911. // Private Methods
  73912. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73913. var _this = this;
  73914. this._samplerOffsets = [];
  73915. var expensive = this.expensiveBlur;
  73916. for (var i = -8; i < 8; i++) {
  73917. this._samplerOffsets.push(i * 2 + 0.5);
  73918. }
  73919. this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao2", ["outSize", "samplerOffsets", "near", "far", "radius"], ["depthSampler"], ssaoRatio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE " + (expensive ? "1" : "0") + "\n");
  73920. this._blurHPostProcess.onApply = function (effect) {
  73921. if (!_this._scene.activeCamera) {
  73922. return;
  73923. }
  73924. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73925. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73926. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73927. effect.setFloat("radius", _this.radius);
  73928. effect.setTexture("depthSampler", _this._depthTexture);
  73929. if (_this._firstUpdate) {
  73930. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73931. }
  73932. };
  73933. this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao2", ["outSize", "samplerOffsets", "near", "far", "radius"], ["depthSampler"], blurRatio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_V\n#define SAMPLES 16\n#define EXPENSIVE " + (expensive ? "1" : "0") + "\n");
  73934. this._blurVPostProcess.onApply = function (effect) {
  73935. if (!_this._scene.activeCamera) {
  73936. return;
  73937. }
  73938. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73939. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73940. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73941. effect.setFloat("radius", _this.radius);
  73942. effect.setTexture("depthSampler", _this._depthTexture);
  73943. if (_this._firstUpdate) {
  73944. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73945. _this._firstUpdate = false;
  73946. }
  73947. };
  73948. };
  73949. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73950. this._firstUpdate = true;
  73951. _super.prototype._rebuild.call(this);
  73952. };
  73953. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73954. var numSamples = this.samples;
  73955. var result = [];
  73956. var vector, scale;
  73957. var rand = function (min, max) {
  73958. return Math.random() * (max - min) + min;
  73959. };
  73960. var i = 0;
  73961. while (i < numSamples) {
  73962. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73963. vector.normalize();
  73964. scale = i / numSamples;
  73965. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73966. vector.scaleInPlace(scale);
  73967. result.push(vector.x, vector.y, vector.z);
  73968. i++;
  73969. }
  73970. return result;
  73971. };
  73972. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73973. var _this = this;
  73974. var numSamples = this.samples;
  73975. this._sampleSphere = this._generateHemisphere();
  73976. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73977. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73978. "base", "range", "projection", "near", "far", "texelSize",
  73979. "xViewport", "yViewport", "maxZ", "minZAspect"
  73980. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73981. this._ssaoPostProcess.onApply = function (effect) {
  73982. if (_this._firstUpdate) {
  73983. effect.setArray3("sampleSphere", _this._sampleSphere);
  73984. effect.setFloat("randTextureTiles", 4.0);
  73985. }
  73986. if (!_this._scene.activeCamera) {
  73987. return;
  73988. }
  73989. effect.setFloat("samplesFactor", 1 / _this.samples);
  73990. effect.setFloat("totalStrength", _this.totalStrength);
  73991. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73992. effect.setFloat("radius", _this.radius);
  73993. effect.setFloat("maxZ", _this.maxZ);
  73994. effect.setFloat("minZAspect", _this.minZAspect);
  73995. effect.setFloat("base", _this.base);
  73996. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73997. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73998. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73999. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  74000. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  74001. effect.setTexture("textureSampler", _this._depthTexture);
  74002. effect.setTexture("normalSampler", _this._normalTexture);
  74003. effect.setTexture("randomSampler", _this._randomTexture);
  74004. };
  74005. };
  74006. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  74007. var _this = this;
  74008. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74009. this._ssaoCombinePostProcess.onApply = function (effect) {
  74010. var viewport = _this._scene.activeCamera.viewport;
  74011. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  74012. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  74013. };
  74014. };
  74015. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  74016. var size = 512;
  74017. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74018. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74019. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74020. var context = this._randomTexture.getContext();
  74021. var rand = function (min, max) {
  74022. return Math.random() * (max - min) + min;
  74023. };
  74024. var randVector = BABYLON.Vector3.Zero();
  74025. for (var x = 0; x < size; x++) {
  74026. for (var y = 0; y < size; y++) {
  74027. randVector.x = rand(0.0, 1.0);
  74028. randVector.y = rand(0.0, 1.0);
  74029. randVector.z = 0.0;
  74030. randVector.normalize();
  74031. randVector.scaleInPlace(255);
  74032. randVector.x = Math.floor(randVector.x);
  74033. randVector.y = Math.floor(randVector.y);
  74034. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  74035. context.fillRect(x, y, 1, 1);
  74036. }
  74037. }
  74038. this._randomTexture.update(false);
  74039. };
  74040. /**
  74041. * Serialize the rendering pipeline (Used when exporting)
  74042. * @returns the serialized object
  74043. */
  74044. SSAO2RenderingPipeline.prototype.serialize = function () {
  74045. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74046. serializationObject.customType = "SSAO2RenderingPipeline";
  74047. return serializationObject;
  74048. };
  74049. /**
  74050. * Parse the serialized pipeline
  74051. * @param source Source pipeline.
  74052. * @param scene The scene to load the pipeline to.
  74053. * @param rootUrl The URL of the serialized pipeline.
  74054. * @returns An instantiated pipeline from the serialized object.
  74055. */
  74056. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  74057. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74058. };
  74059. __decorate([
  74060. BABYLON.serialize()
  74061. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  74062. __decorate([
  74063. BABYLON.serialize()
  74064. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  74065. __decorate([
  74066. BABYLON.serialize()
  74067. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  74068. __decorate([
  74069. BABYLON.serialize("samples")
  74070. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  74071. __decorate([
  74072. BABYLON.serialize()
  74073. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  74074. __decorate([
  74075. BABYLON.serialize("expensiveBlur")
  74076. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  74077. __decorate([
  74078. BABYLON.serialize()
  74079. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  74080. __decorate([
  74081. BABYLON.serialize()
  74082. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  74083. return SSAO2RenderingPipeline;
  74084. }(BABYLON.PostProcessRenderPipeline));
  74085. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  74086. })(BABYLON || (BABYLON = {}));
  74087. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  74088. // BABYLON.JS Chromatic Aberration GLSL Shader
  74089. // Author: Olivier Guyot
  74090. // Separates very slightly R, G and B colors on the edges of the screen
  74091. // Inspired by Francois Tarlier & Martins Upitis
  74092. var BABYLON;
  74093. (function (BABYLON) {
  74094. var LensRenderingPipeline = /** @class */ (function (_super) {
  74095. __extends(LensRenderingPipeline, _super);
  74096. /**
  74097. * @constructor
  74098. *
  74099. * Effect parameters are as follow:
  74100. * {
  74101. * chromatic_aberration: number; // from 0 to x (1 for realism)
  74102. * edge_blur: number; // from 0 to x (1 for realism)
  74103. * distortion: number; // from 0 to x (1 for realism)
  74104. * grain_amount: number; // from 0 to 1
  74105. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  74106. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  74107. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  74108. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  74109. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  74110. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  74111. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  74112. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  74113. * }
  74114. * Note: if an effect parameter is unset, effect is disabled
  74115. *
  74116. * @param {string} name - The rendering pipeline name
  74117. * @param {object} parameters - An object containing all parameters (see above)
  74118. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74119. * @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)
  74120. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74121. */
  74122. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  74123. if (ratio === void 0) { ratio = 1.0; }
  74124. var _this = _super.call(this, scene.getEngine(), name) || this;
  74125. // Lens effects can be of the following:
  74126. // - chromatic aberration (slight shift of RGB colors)
  74127. // - blur on the edge of the lens
  74128. // - lens distortion
  74129. // - depth-of-field blur & highlights enhancing
  74130. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  74131. // - grain effect (noise or custom texture)
  74132. // Two additional texture samplers are needed:
  74133. // - depth map (for depth-of-field)
  74134. // - grain texture
  74135. /**
  74136. * The chromatic aberration PostProcess id in the pipeline
  74137. */
  74138. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  74139. /**
  74140. * The highlights enhancing PostProcess id in the pipeline
  74141. */
  74142. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  74143. /**
  74144. * The depth-of-field PostProcess id in the pipeline
  74145. */
  74146. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  74147. _this._scene = scene;
  74148. // Fetch texture samplers
  74149. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74150. if (parameters.grain_texture) {
  74151. _this._grainTexture = parameters.grain_texture;
  74152. }
  74153. else {
  74154. _this._createGrainTexture();
  74155. }
  74156. // save parameters
  74157. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  74158. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  74159. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  74160. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  74161. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  74162. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  74163. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  74164. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  74165. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  74166. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  74167. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  74168. // Create effects
  74169. _this._createChromaticAberrationPostProcess(ratio);
  74170. _this._createHighlightsPostProcess(ratio);
  74171. _this._createDepthOfFieldPostProcess(ratio / 4);
  74172. // Set up pipeline
  74173. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  74174. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  74175. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  74176. if (_this._highlightsGain === -1) {
  74177. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  74178. }
  74179. // Finish
  74180. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74181. if (cameras) {
  74182. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74183. }
  74184. return _this;
  74185. }
  74186. // public methods (self explanatory)
  74187. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  74188. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  74189. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  74190. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  74191. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  74192. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  74193. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  74194. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  74195. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  74196. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  74197. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  74198. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  74199. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  74200. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  74201. };
  74202. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  74203. this._highlightsPostProcess.updateEffect();
  74204. };
  74205. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  74206. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  74207. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  74208. this._highlightsGain = amount;
  74209. };
  74210. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  74211. if (this._highlightsGain === -1) {
  74212. this._highlightsGain = 1.0;
  74213. }
  74214. this._highlightsThreshold = amount;
  74215. };
  74216. LensRenderingPipeline.prototype.disableHighlights = function () {
  74217. this._highlightsGain = -1;
  74218. };
  74219. /**
  74220. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  74221. */
  74222. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74223. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74224. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74225. this._chromaticAberrationPostProcess = null;
  74226. this._highlightsPostProcess = null;
  74227. this._depthOfFieldPostProcess = null;
  74228. this._grainTexture.dispose();
  74229. if (disableDepthRender)
  74230. this._scene.disableDepthRenderer();
  74231. };
  74232. // colors shifting and distortion
  74233. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74234. var _this = this;
  74235. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74236. [], // samplers
  74237. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74238. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74239. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74240. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74241. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74242. effect.setFloat('radialIntensity', 1);
  74243. effect.setFloat2('direction', 17, 17);
  74244. effect.setFloat2('centerPosition', 0.5, 0.5);
  74245. };
  74246. };
  74247. // highlights enhancing
  74248. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74249. var _this = this;
  74250. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74251. [], // samplers
  74252. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74253. this._highlightsPostProcess.onApply = function (effect) {
  74254. effect.setFloat('gain', _this._highlightsGain);
  74255. effect.setFloat('threshold', _this._highlightsThreshold);
  74256. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74257. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74258. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74259. };
  74260. };
  74261. // colors shifting and distortion
  74262. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74263. var _this = this;
  74264. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74265. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74266. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74267. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74268. this._depthOfFieldPostProcess.onApply = function (effect) {
  74269. effect.setTexture("depthSampler", _this._depthTexture);
  74270. effect.setTexture("grainSampler", _this._grainTexture);
  74271. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74272. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74273. effect.setFloat('grain_amount', _this._grainAmount);
  74274. effect.setBool('blur_noise', _this._blurNoise);
  74275. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74276. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74277. effect.setFloat('distortion', _this._distortion);
  74278. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74279. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74280. effect.setFloat('aperture', _this._dofAperture);
  74281. effect.setFloat('darken', _this._dofDarken);
  74282. effect.setFloat('edge_blur', _this._edgeBlur);
  74283. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74284. if (_this._scene.activeCamera) {
  74285. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74286. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74287. }
  74288. };
  74289. };
  74290. // creates a black and white random noise texture, 512x512
  74291. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74292. var size = 512;
  74293. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74294. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74295. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74296. var context = this._grainTexture.getContext();
  74297. var rand = function (min, max) {
  74298. return Math.random() * (max - min) + min;
  74299. };
  74300. var value;
  74301. for (var x = 0; x < size; x++) {
  74302. for (var y = 0; y < size; y++) {
  74303. value = Math.floor(rand(0.42, 0.58) * 255);
  74304. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74305. context.fillRect(x, y, 1, 1);
  74306. }
  74307. }
  74308. this._grainTexture.update(false);
  74309. };
  74310. return LensRenderingPipeline;
  74311. }(BABYLON.PostProcessRenderPipeline));
  74312. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74313. })(BABYLON || (BABYLON = {}));
  74314. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74315. var BABYLON;
  74316. (function (BABYLON) {
  74317. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74318. __extends(StandardRenderingPipeline, _super);
  74319. /**
  74320. * @constructor
  74321. * @param {string} name - The rendering pipeline name
  74322. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74323. * @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)
  74324. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74325. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74326. */
  74327. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74328. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74329. var _this = _super.call(this, scene.getEngine(), name) || this;
  74330. _this.downSampleX4PostProcess = null;
  74331. _this.brightPassPostProcess = null;
  74332. _this.blurHPostProcesses = [];
  74333. _this.blurVPostProcesses = [];
  74334. _this.textureAdderPostProcess = null;
  74335. _this.volumetricLightPostProcess = null;
  74336. _this.volumetricLightSmoothXPostProcess = null;
  74337. _this.volumetricLightSmoothYPostProcess = null;
  74338. _this.volumetricLightMergePostProces = null;
  74339. _this.volumetricLightFinalPostProcess = null;
  74340. _this.luminancePostProcess = null;
  74341. _this.luminanceDownSamplePostProcesses = [];
  74342. _this.hdrPostProcess = null;
  74343. _this.textureAdderFinalPostProcess = null;
  74344. _this.lensFlareFinalPostProcess = null;
  74345. _this.hdrFinalPostProcess = null;
  74346. _this.lensFlarePostProcess = null;
  74347. _this.lensFlareComposePostProcess = null;
  74348. _this.motionBlurPostProcess = null;
  74349. _this.depthOfFieldPostProcess = null;
  74350. // Values
  74351. _this.brightThreshold = 1.0;
  74352. _this.blurWidth = 512.0;
  74353. _this.horizontalBlur = false;
  74354. _this.exposure = 1.0;
  74355. _this.lensTexture = null;
  74356. _this.volumetricLightCoefficient = 0.2;
  74357. _this.volumetricLightPower = 4.0;
  74358. _this.volumetricLightBlurScale = 64.0;
  74359. _this.sourceLight = null;
  74360. _this.hdrMinimumLuminance = 1.0;
  74361. _this.hdrDecreaseRate = 0.5;
  74362. _this.hdrIncreaseRate = 0.5;
  74363. _this.lensColorTexture = null;
  74364. _this.lensFlareStrength = 20.0;
  74365. _this.lensFlareGhostDispersal = 1.4;
  74366. _this.lensFlareHaloWidth = 0.7;
  74367. _this.lensFlareDistortionStrength = 16.0;
  74368. _this.lensStarTexture = null;
  74369. _this.lensFlareDirtTexture = null;
  74370. _this.depthOfFieldDistance = 10.0;
  74371. _this.depthOfFieldBlurWidth = 64.0;
  74372. _this.motionStrength = 1.0;
  74373. // IAnimatable
  74374. _this.animations = [];
  74375. _this._currentDepthOfFieldSource = null;
  74376. _this._hdrCurrentLuminance = 1.0;
  74377. // Getters and setters
  74378. _this._bloomEnabled = true;
  74379. _this._depthOfFieldEnabled = false;
  74380. _this._vlsEnabled = false;
  74381. _this._lensFlareEnabled = false;
  74382. _this._hdrEnabled = false;
  74383. _this._motionBlurEnabled = false;
  74384. _this._motionBlurSamples = 64.0;
  74385. _this._volumetricLightStepsCount = 50.0;
  74386. _this._cameras = cameras || [];
  74387. // Initialize
  74388. _this._scene = scene;
  74389. _this._basePostProcess = originalPostProcess;
  74390. _this._ratio = ratio;
  74391. // Misc
  74392. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74393. // Finish
  74394. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74395. _this._buildPipeline();
  74396. return _this;
  74397. }
  74398. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74399. get: function () {
  74400. return this._bloomEnabled;
  74401. },
  74402. set: function (enabled) {
  74403. if (this._bloomEnabled === enabled) {
  74404. return;
  74405. }
  74406. this._bloomEnabled = enabled;
  74407. this._buildPipeline();
  74408. },
  74409. enumerable: true,
  74410. configurable: true
  74411. });
  74412. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74413. get: function () {
  74414. return this._depthOfFieldEnabled;
  74415. },
  74416. set: function (enabled) {
  74417. if (this._depthOfFieldEnabled === enabled) {
  74418. return;
  74419. }
  74420. this._depthOfFieldEnabled = enabled;
  74421. this._buildPipeline();
  74422. },
  74423. enumerable: true,
  74424. configurable: true
  74425. });
  74426. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74427. get: function () {
  74428. return this._lensFlareEnabled;
  74429. },
  74430. set: function (enabled) {
  74431. if (this._lensFlareEnabled === enabled) {
  74432. return;
  74433. }
  74434. this._lensFlareEnabled = enabled;
  74435. this._buildPipeline();
  74436. },
  74437. enumerable: true,
  74438. configurable: true
  74439. });
  74440. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74441. get: function () {
  74442. return this._hdrEnabled;
  74443. },
  74444. set: function (enabled) {
  74445. if (this._hdrEnabled === enabled) {
  74446. return;
  74447. }
  74448. this._hdrEnabled = enabled;
  74449. this._buildPipeline();
  74450. },
  74451. enumerable: true,
  74452. configurable: true
  74453. });
  74454. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74455. get: function () {
  74456. return this._vlsEnabled;
  74457. },
  74458. set: function (enabled) {
  74459. if (this._vlsEnabled === enabled) {
  74460. return;
  74461. }
  74462. if (enabled) {
  74463. var geometry = this._scene.enableGeometryBufferRenderer();
  74464. if (!geometry) {
  74465. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74466. return;
  74467. }
  74468. }
  74469. this._vlsEnabled = enabled;
  74470. this._buildPipeline();
  74471. },
  74472. enumerable: true,
  74473. configurable: true
  74474. });
  74475. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74476. get: function () {
  74477. return this._motionBlurEnabled;
  74478. },
  74479. set: function (enabled) {
  74480. if (this._motionBlurEnabled === enabled) {
  74481. return;
  74482. }
  74483. this._motionBlurEnabled = enabled;
  74484. this._buildPipeline();
  74485. },
  74486. enumerable: true,
  74487. configurable: true
  74488. });
  74489. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74490. get: function () {
  74491. return this._volumetricLightStepsCount;
  74492. },
  74493. set: function (count) {
  74494. if (this.volumetricLightPostProcess) {
  74495. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74496. }
  74497. this._volumetricLightStepsCount = count;
  74498. },
  74499. enumerable: true,
  74500. configurable: true
  74501. });
  74502. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74503. get: function () {
  74504. return this._motionBlurSamples;
  74505. },
  74506. set: function (samples) {
  74507. if (this.motionBlurPostProcess) {
  74508. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74509. }
  74510. this._motionBlurSamples = samples;
  74511. },
  74512. enumerable: true,
  74513. configurable: true
  74514. });
  74515. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74516. var _this = this;
  74517. var ratio = this._ratio;
  74518. var scene = this._scene;
  74519. this._disposePostProcesses();
  74520. this._reset();
  74521. // Create pass post-process
  74522. if (!this._basePostProcess) {
  74523. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74524. this.originalPostProcess.onApply = function (effect) {
  74525. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74526. };
  74527. }
  74528. else {
  74529. this.originalPostProcess = this._basePostProcess;
  74530. }
  74531. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74532. this._currentDepthOfFieldSource = this.originalPostProcess;
  74533. if (this._bloomEnabled) {
  74534. // Create down sample X4 post-process
  74535. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74536. // Create bright pass post-process
  74537. this._createBrightPassPostProcess(scene, ratio / 2);
  74538. // Create gaussian blur post-processes (down sampling blurs)
  74539. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74540. // Create texture adder post-process
  74541. this._createTextureAdderPostProcess(scene, ratio);
  74542. // Create depth-of-field source post-process
  74543. this.textureAdderFinalPostProcess = new BABYLON.PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74544. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74545. }
  74546. if (this._vlsEnabled) {
  74547. // Create volumetric light
  74548. this._createVolumetricLightPostProcess(scene, ratio);
  74549. // Create volumetric light final post-process
  74550. this.volumetricLightFinalPostProcess = new BABYLON.PostProcess("HDRVLSFinal", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74551. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74552. }
  74553. if (this._lensFlareEnabled) {
  74554. // Create lens flare post-process
  74555. this._createLensFlarePostProcess(scene, ratio);
  74556. // Create depth-of-field source post-process post lens-flare and disable it now
  74557. this.lensFlareFinalPostProcess = new BABYLON.PostProcess("HDRPostLensFlareDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74558. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74559. }
  74560. if (this._hdrEnabled) {
  74561. // Create luminance
  74562. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74563. // Create HDR
  74564. this._createHdrPostProcess(scene, ratio);
  74565. // Create depth-of-field source post-process post hdr and disable it now
  74566. this.hdrFinalPostProcess = new BABYLON.PostProcess("HDRPostHDReDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74567. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74568. }
  74569. if (this._depthOfFieldEnabled) {
  74570. // Create gaussian blur used by depth-of-field
  74571. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74572. // Create depth-of-field post-process
  74573. this._createDepthOfFieldPostProcess(scene, ratio);
  74574. }
  74575. if (this._motionBlurEnabled) {
  74576. // Create motion blur post-process
  74577. this._createMotionBlurPostProcess(scene, ratio);
  74578. }
  74579. if (this._cameras !== null) {
  74580. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74581. }
  74582. };
  74583. // Down Sample X4 Post-Processs
  74584. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74585. var _this = this;
  74586. var downSampleX4Offsets = new Array(32);
  74587. this.downSampleX4PostProcess = new BABYLON.PostProcess("HDRDownSampleX4", "standard", ["dsOffsets"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74588. this.downSampleX4PostProcess.onApply = function (effect) {
  74589. var id = 0;
  74590. var width = _this.downSampleX4PostProcess.width;
  74591. var height = _this.downSampleX4PostProcess.height;
  74592. for (var i = -2; i < 2; i++) {
  74593. for (var j = -2; j < 2; j++) {
  74594. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74595. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74596. id += 2;
  74597. }
  74598. }
  74599. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74600. };
  74601. // Add to pipeline
  74602. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74603. };
  74604. // Brightpass Post-Process
  74605. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74606. var _this = this;
  74607. var brightOffsets = new Array(8);
  74608. this.brightPassPostProcess = new BABYLON.PostProcess("HDRBrightPass", "standard", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74609. this.brightPassPostProcess.onApply = function (effect) {
  74610. var sU = (1.0 / _this.brightPassPostProcess.width);
  74611. var sV = (1.0 / _this.brightPassPostProcess.height);
  74612. brightOffsets[0] = -0.5 * sU;
  74613. brightOffsets[1] = 0.5 * sV;
  74614. brightOffsets[2] = 0.5 * sU;
  74615. brightOffsets[3] = 0.5 * sV;
  74616. brightOffsets[4] = -0.5 * sU;
  74617. brightOffsets[5] = -0.5 * sV;
  74618. brightOffsets[6] = 0.5 * sU;
  74619. brightOffsets[7] = -0.5 * sV;
  74620. effect.setArray2("dsOffsets", brightOffsets);
  74621. effect.setFloat("brightThreshold", _this.brightThreshold);
  74622. };
  74623. // Add to pipeline
  74624. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74625. };
  74626. // Create blur H&V post-processes
  74627. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74628. var _this = this;
  74629. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74630. var engine = scene.getEngine();
  74631. var blurX = new BABYLON.BlurPostProcess("HDRBlurH" + "_" + indice, new BABYLON.Vector2(1, 0), this[blurWidthKey], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74632. var blurY = new BABYLON.BlurPostProcess("HDRBlurV" + "_" + indice, new BABYLON.Vector2(0, 1), this[blurWidthKey], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74633. blurX.onActivateObservable.add(function () {
  74634. var dw = blurX.width / engine.getRenderWidth();
  74635. blurX.kernel = _this[blurWidthKey] * dw;
  74636. });
  74637. blurY.onActivateObservable.add(function () {
  74638. var dw = blurY.height / engine.getRenderHeight();
  74639. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74640. });
  74641. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74642. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74643. this.blurHPostProcesses.push(blurX);
  74644. this.blurVPostProcesses.push(blurY);
  74645. };
  74646. // Create texture adder post-process
  74647. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74648. var _this = this;
  74649. this.textureAdderPostProcess = new BABYLON.PostProcess("HDRTextureAdder", "standard", ["exposure"], ["otherSampler", "lensSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74650. this.textureAdderPostProcess.onApply = function (effect) {
  74651. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74652. effect.setTexture("lensSampler", _this.lensTexture);
  74653. effect.setFloat("exposure", _this.exposure);
  74654. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74655. };
  74656. // Add to pipeline
  74657. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74658. };
  74659. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74660. var _this = this;
  74661. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74662. geometryRenderer.enablePosition = true;
  74663. var geometry = geometryRenderer.getGBuffer();
  74664. // Base post-process
  74665. this.volumetricLightPostProcess = new BABYLON.PostProcess("HDRVLS", "standard", ["shadowViewProjection", "cameraPosition", "sunDirection", "sunColor", "scatteringCoefficient", "scatteringPower", "depthValues"], ["shadowMapSampler", "positionSampler"], ratio / 8, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLS\n#define NB_STEPS " + this._volumetricLightStepsCount.toFixed(1));
  74666. var depthValues = BABYLON.Vector2.Zero();
  74667. this.volumetricLightPostProcess.onApply = function (effect) {
  74668. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74669. var generator = _this.sourceLight.getShadowGenerator();
  74670. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74671. effect.setTexture("positionSampler", geometry.textures[2]);
  74672. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74673. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74674. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74675. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74676. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74677. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74678. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74679. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74680. effect.setVector2("depthValues", depthValues);
  74681. }
  74682. };
  74683. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74684. // Smooth
  74685. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74686. // Merge
  74687. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74688. this.volumetricLightMergePostProces.onApply = function (effect) {
  74689. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74690. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74691. };
  74692. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74693. };
  74694. // Create luminance
  74695. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74696. var _this = this;
  74697. // Create luminance
  74698. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74699. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74700. var offsets = [];
  74701. this.luminancePostProcess.onApply = function (effect) {
  74702. var sU = (1.0 / _this.luminancePostProcess.width);
  74703. var sV = (1.0 / _this.luminancePostProcess.height);
  74704. offsets[0] = -0.5 * sU;
  74705. offsets[1] = 0.5 * sV;
  74706. offsets[2] = 0.5 * sU;
  74707. offsets[3] = 0.5 * sV;
  74708. offsets[4] = -0.5 * sU;
  74709. offsets[5] = -0.5 * sV;
  74710. offsets[6] = 0.5 * sU;
  74711. offsets[7] = -0.5 * sV;
  74712. effect.setArray2("lumOffsets", offsets);
  74713. };
  74714. // Add to pipeline
  74715. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74716. // Create down sample luminance
  74717. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74718. var size = Math.pow(3, i);
  74719. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74720. if (i === 0) {
  74721. defines += "#define FINAL_DOWN_SAMPLER";
  74722. }
  74723. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74724. this.luminanceDownSamplePostProcesses.push(postProcess);
  74725. }
  74726. // Create callbacks and add effects
  74727. var lastLuminance = this.luminancePostProcess;
  74728. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74729. var downSampleOffsets = new Array(18);
  74730. pp.onApply = function (effect) {
  74731. if (!lastLuminance) {
  74732. return;
  74733. }
  74734. var id = 0;
  74735. for (var x = -1; x < 2; x++) {
  74736. for (var y = -1; y < 2; y++) {
  74737. downSampleOffsets[id] = x / lastLuminance.width;
  74738. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74739. id += 2;
  74740. }
  74741. }
  74742. effect.setArray2("dsOffsets", downSampleOffsets);
  74743. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74744. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74745. lastLuminance = _this.luminancePostProcess;
  74746. }
  74747. else {
  74748. lastLuminance = pp;
  74749. }
  74750. };
  74751. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74752. pp.onAfterRender = function (effect) {
  74753. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74754. 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);
  74755. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74756. };
  74757. }
  74758. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74759. });
  74760. };
  74761. // Create HDR post-process
  74762. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74763. var _this = this;
  74764. this.hdrPostProcess = new BABYLON.PostProcess("HDR", "standard", ["averageLuminance"], ["textureAdderSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74765. var outputLiminance = 1;
  74766. var time = 0;
  74767. var lastTime = 0;
  74768. this.hdrPostProcess.onApply = function (effect) {
  74769. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74770. time += scene.getEngine().getDeltaTime();
  74771. if (outputLiminance < 0) {
  74772. outputLiminance = _this._hdrCurrentLuminance;
  74773. }
  74774. else {
  74775. var dt = (lastTime - time) / 1000.0;
  74776. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74777. outputLiminance += _this.hdrDecreaseRate * dt;
  74778. }
  74779. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74780. outputLiminance -= _this.hdrIncreaseRate * dt;
  74781. }
  74782. else {
  74783. outputLiminance = _this._hdrCurrentLuminance;
  74784. }
  74785. }
  74786. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74787. effect.setFloat("averageLuminance", outputLiminance);
  74788. lastTime = time;
  74789. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74790. };
  74791. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74792. };
  74793. // Create lens flare post-process
  74794. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74795. var _this = this;
  74796. this.lensFlarePostProcess = new BABYLON.PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth", "resolution", "distortionStrength"], ["lensColorSampler"], ratio / 2, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74797. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74798. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74799. this.lensFlareComposePostProcess = new BABYLON.PostProcess("HDRLensFlareCompose", "standard", ["lensStarMatrix"], ["otherSampler", "lensDirtSampler", "lensStarSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE_COMPOSE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74800. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74801. var resolution = new BABYLON.Vector2(0, 0);
  74802. // Lens flare
  74803. this.lensFlarePostProcess.onApply = function (effect) {
  74804. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74805. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74806. effect.setFloat("strength", _this.lensFlareStrength);
  74807. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74808. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74809. // Shift
  74810. resolution.x = _this.lensFlarePostProcess.width;
  74811. resolution.y = _this.lensFlarePostProcess.height;
  74812. effect.setVector2("resolution", resolution);
  74813. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74814. };
  74815. // Compose
  74816. var scaleBias1 = BABYLON.Matrix.FromValues(2.0, 0.0, -1.0, 0.0, 0.0, 2.0, -1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  74817. var scaleBias2 = BABYLON.Matrix.FromValues(0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  74818. this.lensFlareComposePostProcess.onApply = function (effect) {
  74819. if (!_this._scene.activeCamera) {
  74820. return;
  74821. }
  74822. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74823. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74824. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74825. // Lens start rotation matrix
  74826. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74827. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74828. var camRot = BABYLON.Vector3.Dot(camerax.toVector3(), new BABYLON.Vector3(1.0, 0.0, 0.0)) + BABYLON.Vector3.Dot(cameraz.toVector3(), new BABYLON.Vector3(0.0, 0.0, 1.0));
  74829. camRot *= 4.0;
  74830. var starRotation = BABYLON.Matrix.FromValues(Math.cos(camRot) * 0.5, -Math.sin(camRot), 0.0, 0.0, Math.sin(camRot), Math.cos(camRot) * 0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  74831. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74832. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74833. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74834. };
  74835. };
  74836. // Create depth-of-field post-process
  74837. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74838. var _this = this;
  74839. this.depthOfFieldPostProcess = new BABYLON.PostProcess("HDRDepthOfField", "standard", ["distance"], ["otherSampler", "depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DEPTH_OF_FIELD", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74840. this.depthOfFieldPostProcess.onApply = function (effect) {
  74841. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74842. effect.setTexture("depthSampler", _this._getDepthTexture());
  74843. effect.setFloat("distance", _this.depthOfFieldDistance);
  74844. };
  74845. // Add to pipeline
  74846. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74847. };
  74848. // Create motion blur post-process
  74849. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74850. var _this = this;
  74851. this.motionBlurPostProcess = new BABYLON.PostProcess("HDRMotionBlur", "standard", ["inverseViewProjection", "prevViewProjection", "screenSize", "motionScale", "motionStrength"], ["depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + this.motionBlurSamples.toFixed(1), BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74852. var motionScale = 0;
  74853. var prevViewProjection = BABYLON.Matrix.Identity();
  74854. var invViewProjection = BABYLON.Matrix.Identity();
  74855. var viewProjection = BABYLON.Matrix.Identity();
  74856. var screenSize = BABYLON.Vector2.Zero();
  74857. this.motionBlurPostProcess.onApply = function (effect) {
  74858. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74859. viewProjection.invertToRef(invViewProjection);
  74860. effect.setMatrix("inverseViewProjection", invViewProjection);
  74861. effect.setMatrix("prevViewProjection", prevViewProjection);
  74862. prevViewProjection = viewProjection;
  74863. screenSize.x = _this.motionBlurPostProcess.width;
  74864. screenSize.y = _this.motionBlurPostProcess.height;
  74865. effect.setVector2("screenSize", screenSize);
  74866. motionScale = scene.getEngine().getFps() / 60.0;
  74867. effect.setFloat("motionScale", motionScale);
  74868. effect.setFloat("motionStrength", _this.motionStrength);
  74869. effect.setTexture("depthSampler", _this._getDepthTexture());
  74870. };
  74871. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74872. };
  74873. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74874. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74875. var renderer = this._scene.enableGeometryBufferRenderer();
  74876. return renderer.getGBuffer().textures[0];
  74877. }
  74878. return this._scene.enableDepthRenderer().getDepthMap();
  74879. };
  74880. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74881. for (var i = 0; i < this._cameras.length; i++) {
  74882. var camera = this._cameras[i];
  74883. if (this.originalPostProcess) {
  74884. this.originalPostProcess.dispose(camera);
  74885. }
  74886. if (this.downSampleX4PostProcess) {
  74887. this.downSampleX4PostProcess.dispose(camera);
  74888. }
  74889. if (this.brightPassPostProcess) {
  74890. this.brightPassPostProcess.dispose(camera);
  74891. }
  74892. if (this.textureAdderPostProcess) {
  74893. this.textureAdderPostProcess.dispose(camera);
  74894. }
  74895. if (this.textureAdderFinalPostProcess) {
  74896. this.textureAdderFinalPostProcess.dispose(camera);
  74897. }
  74898. if (this.volumetricLightPostProcess) {
  74899. this.volumetricLightPostProcess.dispose(camera);
  74900. }
  74901. if (this.volumetricLightSmoothXPostProcess) {
  74902. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74903. }
  74904. if (this.volumetricLightSmoothYPostProcess) {
  74905. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74906. }
  74907. if (this.volumetricLightMergePostProces) {
  74908. this.volumetricLightMergePostProces.dispose(camera);
  74909. }
  74910. if (this.volumetricLightFinalPostProcess) {
  74911. this.volumetricLightFinalPostProcess.dispose(camera);
  74912. }
  74913. if (this.lensFlarePostProcess) {
  74914. this.lensFlarePostProcess.dispose(camera);
  74915. }
  74916. if (this.lensFlareComposePostProcess) {
  74917. this.lensFlareComposePostProcess.dispose(camera);
  74918. }
  74919. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74920. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74921. }
  74922. if (this.luminancePostProcess) {
  74923. this.luminancePostProcess.dispose(camera);
  74924. }
  74925. if (this.hdrPostProcess) {
  74926. this.hdrPostProcess.dispose(camera);
  74927. }
  74928. if (this.hdrFinalPostProcess) {
  74929. this.hdrFinalPostProcess.dispose(camera);
  74930. }
  74931. if (this.depthOfFieldPostProcess) {
  74932. this.depthOfFieldPostProcess.dispose(camera);
  74933. }
  74934. if (this.motionBlurPostProcess) {
  74935. this.motionBlurPostProcess.dispose(camera);
  74936. }
  74937. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74938. this.blurHPostProcesses[j].dispose(camera);
  74939. }
  74940. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74941. this.blurVPostProcesses[j].dispose(camera);
  74942. }
  74943. }
  74944. this.originalPostProcess = null;
  74945. this.downSampleX4PostProcess = null;
  74946. this.brightPassPostProcess = null;
  74947. this.textureAdderPostProcess = null;
  74948. this.textureAdderFinalPostProcess = null;
  74949. this.volumetricLightPostProcess = null;
  74950. this.volumetricLightSmoothXPostProcess = null;
  74951. this.volumetricLightSmoothYPostProcess = null;
  74952. this.volumetricLightMergePostProces = null;
  74953. this.volumetricLightFinalPostProcess = null;
  74954. this.lensFlarePostProcess = null;
  74955. this.lensFlareComposePostProcess = null;
  74956. this.luminancePostProcess = null;
  74957. this.hdrPostProcess = null;
  74958. this.hdrFinalPostProcess = null;
  74959. this.depthOfFieldPostProcess = null;
  74960. this.motionBlurPostProcess = null;
  74961. this.luminanceDownSamplePostProcesses = [];
  74962. this.blurHPostProcesses = [];
  74963. this.blurVPostProcesses = [];
  74964. };
  74965. /**
  74966. * Dispose of the pipeline and stop all post processes
  74967. */
  74968. StandardRenderingPipeline.prototype.dispose = function () {
  74969. this._disposePostProcesses();
  74970. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74971. _super.prototype.dispose.call(this);
  74972. };
  74973. /**
  74974. * Serialize the rendering pipeline (Used when exporting)
  74975. * @returns the serialized object
  74976. */
  74977. StandardRenderingPipeline.prototype.serialize = function () {
  74978. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74979. if (this.sourceLight) {
  74980. serializationObject.sourceLightId = this.sourceLight.id;
  74981. }
  74982. serializationObject.customType = "StandardRenderingPipeline";
  74983. return serializationObject;
  74984. };
  74985. /**
  74986. * Parse the serialized pipeline
  74987. * @param source Source pipeline.
  74988. * @param scene The scene to load the pipeline to.
  74989. * @param rootUrl The URL of the serialized pipeline.
  74990. * @returns An instantiated pipeline from the serialized object.
  74991. */
  74992. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74993. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74994. if (source.sourceLightId) {
  74995. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74996. }
  74997. return p;
  74998. };
  74999. // Luminance steps
  75000. StandardRenderingPipeline.LuminanceSteps = 6;
  75001. __decorate([
  75002. BABYLON.serialize()
  75003. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  75004. __decorate([
  75005. BABYLON.serialize()
  75006. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  75007. __decorate([
  75008. BABYLON.serialize()
  75009. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  75010. __decorate([
  75011. BABYLON.serialize()
  75012. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  75013. __decorate([
  75014. BABYLON.serializeAsTexture("lensTexture")
  75015. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  75016. __decorate([
  75017. BABYLON.serialize()
  75018. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  75019. __decorate([
  75020. BABYLON.serialize()
  75021. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  75022. __decorate([
  75023. BABYLON.serialize()
  75024. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  75025. __decorate([
  75026. BABYLON.serialize()
  75027. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  75028. __decorate([
  75029. BABYLON.serialize()
  75030. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  75031. __decorate([
  75032. BABYLON.serialize()
  75033. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  75034. __decorate([
  75035. BABYLON.serializeAsTexture("lensColorTexture")
  75036. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  75037. __decorate([
  75038. BABYLON.serialize()
  75039. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  75040. __decorate([
  75041. BABYLON.serialize()
  75042. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  75043. __decorate([
  75044. BABYLON.serialize()
  75045. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  75046. __decorate([
  75047. BABYLON.serialize()
  75048. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  75049. __decorate([
  75050. BABYLON.serializeAsTexture("lensStarTexture")
  75051. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  75052. __decorate([
  75053. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  75054. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  75055. __decorate([
  75056. BABYLON.serialize()
  75057. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  75058. __decorate([
  75059. BABYLON.serialize()
  75060. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  75061. __decorate([
  75062. BABYLON.serialize()
  75063. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  75064. __decorate([
  75065. BABYLON.serialize()
  75066. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  75067. __decorate([
  75068. BABYLON.serialize()
  75069. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  75070. __decorate([
  75071. BABYLON.serialize()
  75072. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  75073. __decorate([
  75074. BABYLON.serialize()
  75075. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  75076. __decorate([
  75077. BABYLON.serialize()
  75078. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  75079. __decorate([
  75080. BABYLON.serialize()
  75081. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  75082. __decorate([
  75083. BABYLON.serialize()
  75084. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  75085. __decorate([
  75086. BABYLON.serialize()
  75087. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  75088. __decorate([
  75089. BABYLON.serialize()
  75090. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  75091. return StandardRenderingPipeline;
  75092. }(BABYLON.PostProcessRenderPipeline));
  75093. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  75094. })(BABYLON || (BABYLON = {}));
  75095. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  75096. var BABYLON;
  75097. (function (BABYLON) {
  75098. var FxaaPostProcess = /** @class */ (function (_super) {
  75099. __extends(FxaaPostProcess, _super);
  75100. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75101. if (camera === void 0) { camera = null; }
  75102. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75103. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  75104. var defines = _this._getDefines();
  75105. _this.updateEffect(defines);
  75106. _this.onApplyObservable.add(function (effect) {
  75107. var texelSize = _this.texelSize;
  75108. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  75109. });
  75110. return _this;
  75111. }
  75112. FxaaPostProcess.prototype._getDefines = function () {
  75113. var engine = this.getEngine();
  75114. if (!engine) {
  75115. return null;
  75116. }
  75117. var glInfo = engine.getGlInfo();
  75118. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  75119. return "#define MALI 1\n";
  75120. }
  75121. return null;
  75122. };
  75123. return FxaaPostProcess;
  75124. }(BABYLON.PostProcess));
  75125. BABYLON.FxaaPostProcess = FxaaPostProcess;
  75126. })(BABYLON || (BABYLON = {}));
  75127. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  75128. var BABYLON;
  75129. (function (BABYLON) {
  75130. /**
  75131. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  75132. */
  75133. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  75134. __extends(ChromaticAberrationPostProcess, _super);
  75135. /**
  75136. * Creates a new instance ChromaticAberrationPostProcess
  75137. * @param name The name of the effect.
  75138. * @param screenWidth The width of the screen to apply the effect on.
  75139. * @param screenHeight The height of the screen to apply the effect on.
  75140. * @param options The required width/height ratio to downsize to before computing the render pass.
  75141. * @param camera The camera to apply the render pass to.
  75142. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75143. * @param engine The engine which the post process will be applied. (default: current engine)
  75144. * @param reusable If the post process can be reused on the same frame. (default: false)
  75145. * @param textureType Type of textures used when performing the post process. (default: 0)
  75146. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  75147. */
  75148. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75149. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75150. if (blockCompilation === void 0) { blockCompilation = false; }
  75151. var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75152. /**
  75153. * The amount of seperation of rgb channels (default: 30)
  75154. */
  75155. _this.aberrationAmount = 30;
  75156. /**
  75157. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  75158. */
  75159. _this.radialIntensity = 0;
  75160. /**
  75161. * The normilized direction in which the rgb channels should be seperated. If set to 0,0 radial direction will be used. (default: Vector2(0.707,0.707))
  75162. */
  75163. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  75164. /**
  75165. * The center position where the radialIntensity should be around. [0.5,0.5 is center of screen, 1,1 is top right corder] (default: Vector2(0.5 ,0.5))
  75166. */
  75167. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  75168. _this.onApplyObservable.add(function (effect) {
  75169. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  75170. effect.setFloat('screen_width', screenWidth);
  75171. effect.setFloat('screen_height', screenHeight);
  75172. effect.setFloat('radialIntensity', _this.radialIntensity);
  75173. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  75174. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  75175. });
  75176. return _this;
  75177. }
  75178. return ChromaticAberrationPostProcess;
  75179. }(BABYLON.PostProcess));
  75180. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  75181. })(BABYLON || (BABYLON = {}));
  75182. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  75183. var BABYLON;
  75184. (function (BABYLON) {
  75185. /**
  75186. * The GrainPostProcess adds noise to the image at mid luminance levels
  75187. */
  75188. var GrainPostProcess = /** @class */ (function (_super) {
  75189. __extends(GrainPostProcess, _super);
  75190. /**
  75191. * Creates a new instance of @see GrainPostProcess
  75192. * @param name The name of the effect.
  75193. * @param options The required width/height ratio to downsize to before computing the render pass.
  75194. * @param camera The camera to apply the render pass to.
  75195. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75196. * @param engine The engine which the post process will be applied. (default: current engine)
  75197. * @param reusable If the post process can be reused on the same frame. (default: false)
  75198. * @param textureType Type of textures used when performing the post process. (default: 0)
  75199. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  75200. */
  75201. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75202. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75203. if (blockCompilation === void 0) { blockCompilation = false; }
  75204. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75205. /**
  75206. * The intensity of the grain added (default: 30)
  75207. */
  75208. _this.intensity = 30;
  75209. /**
  75210. * If the grain should be randomized on every frame
  75211. */
  75212. _this.animated = false;
  75213. _this.onApplyObservable.add(function (effect) {
  75214. effect.setFloat('intensity', _this.intensity);
  75215. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  75216. });
  75217. return _this;
  75218. }
  75219. return GrainPostProcess;
  75220. }(BABYLON.PostProcess));
  75221. BABYLON.GrainPostProcess = GrainPostProcess;
  75222. })(BABYLON || (BABYLON = {}));
  75223. //# sourceMappingURL=babylon.grainPostProcess.js.map
  75224. var BABYLON;
  75225. (function (BABYLON) {
  75226. /**
  75227. * The SharpenPostProcess applies a sharpen kernel to every pixel
  75228. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75229. */
  75230. var SharpenPostProcess = /** @class */ (function (_super) {
  75231. __extends(SharpenPostProcess, _super);
  75232. /**
  75233. * Creates a new instance ConvolutionPostProcess
  75234. * @param name The name of the effect.
  75235. * @param options The required width/height ratio to downsize to before computing the render pass.
  75236. * @param camera The camera to apply the render pass to.
  75237. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75238. * @param engine The engine which the post process will be applied. (default: current engine)
  75239. * @param reusable If the post process can be reused on the same frame. (default: false)
  75240. * @param textureType Type of textures used when performing the post process. (default: 0)
  75241. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  75242. */
  75243. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75244. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75245. if (blockCompilation === void 0) { blockCompilation = false; }
  75246. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75247. /**
  75248. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75249. */
  75250. _this.colorAmount = 1.0;
  75251. /**
  75252. * How much sharpness should be applied (default: 0.3)
  75253. */
  75254. _this.edgeAmount = 0.3;
  75255. _this.onApply = function (effect) {
  75256. effect.setFloat2("screenSize", _this.width, _this.height);
  75257. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75258. };
  75259. return _this;
  75260. }
  75261. return SharpenPostProcess;
  75262. }(BABYLON.PostProcess));
  75263. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75264. })(BABYLON || (BABYLON = {}));
  75265. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75266. var BABYLON;
  75267. (function (BABYLON) {
  75268. /**
  75269. * The Blur Post Process which blurs an image based on a kernel and direction.
  75270. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75271. */
  75272. var BlurPostProcess = /** @class */ (function (_super) {
  75273. __extends(BlurPostProcess, _super);
  75274. /**
  75275. * Creates a new instance BlurPostProcess
  75276. * @param name The name of the effect.
  75277. * @param direction The direction in which to blur the image.
  75278. * @param kernel The size of the kernel to be used when computing the blur. eg. Size of 3 will blur the center pixel by 2 pixels surrounding it.
  75279. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75280. * @param camera The camera to apply the render pass to.
  75281. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75282. * @param engine The engine which the post process will be applied. (default: current engine)
  75283. * @param reusable If the post process can be reused on the same frame. (default: false)
  75284. * @param textureType Type of textures used when performing the post process. (default: 0)
  75285. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  75286. */
  75287. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75288. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75289. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75290. if (defines === void 0) { defines = ""; }
  75291. if (blockCompilation === void 0) { blockCompilation = false; }
  75292. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["circleOfConfusionSampler"], options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  75293. _this.direction = direction;
  75294. _this.blockCompilation = blockCompilation;
  75295. _this._packedFloat = false;
  75296. _this._staticDefines = "";
  75297. _this._staticDefines = defines;
  75298. _this.onApplyObservable.add(function (effect) {
  75299. if (_this._outputTexture) {
  75300. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75301. }
  75302. else {
  75303. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75304. }
  75305. });
  75306. _this.kernel = kernel;
  75307. return _this;
  75308. }
  75309. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75310. /**
  75311. * Gets the length in pixels of the blur sample region
  75312. */
  75313. get: function () {
  75314. return this._idealKernel;
  75315. },
  75316. /**
  75317. * Sets the length in pixels of the blur sample region
  75318. */
  75319. set: function (v) {
  75320. if (this._idealKernel === v) {
  75321. return;
  75322. }
  75323. v = Math.max(v, 1);
  75324. this._idealKernel = v;
  75325. this._kernel = this._nearestBestKernel(v);
  75326. if (!this.blockCompilation) {
  75327. this._updateParameters();
  75328. }
  75329. },
  75330. enumerable: true,
  75331. configurable: true
  75332. });
  75333. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75334. /**
  75335. * Gets wether or not the blur is unpacking/repacking floats
  75336. */
  75337. get: function () {
  75338. return this._packedFloat;
  75339. },
  75340. /**
  75341. * Sets wether or not the blur needs to unpack/repack floats
  75342. */
  75343. set: function (v) {
  75344. if (this._packedFloat === v) {
  75345. return;
  75346. }
  75347. this._packedFloat = v;
  75348. if (!this.blockCompilation) {
  75349. this._updateParameters();
  75350. }
  75351. },
  75352. enumerable: true,
  75353. configurable: true
  75354. });
  75355. /**
  75356. * Updates the effect with the current post process compile time values and recompiles the shader.
  75357. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75358. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75359. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75360. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  75361. * @param onCompiled Called when the shader has been compiled.
  75362. * @param onError Called if there is an error when compiling a shader.
  75363. */
  75364. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75365. if (defines === void 0) { defines = null; }
  75366. if (uniforms === void 0) { uniforms = null; }
  75367. if (samplers === void 0) { samplers = null; }
  75368. this._updateParameters(onCompiled, onError);
  75369. };
  75370. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75371. // Generate sampling offsets and weights
  75372. var N = this._kernel;
  75373. var centerIndex = (N - 1) / 2;
  75374. // Generate Gaussian sampling weights over kernel
  75375. var offsets = [];
  75376. var weights = [];
  75377. var totalWeight = 0;
  75378. for (var i = 0; i < N; i++) {
  75379. var u = i / (N - 1);
  75380. var w = this._gaussianWeight(u * 2.0 - 1);
  75381. offsets[i] = (i - centerIndex);
  75382. weights[i] = w;
  75383. totalWeight += w;
  75384. }
  75385. // Normalize weights
  75386. for (var i = 0; i < weights.length; i++) {
  75387. weights[i] /= totalWeight;
  75388. }
  75389. // Optimize: combine samples to take advantage of hardware linear sampling
  75390. // Walk from left to center, combining pairs (symmetrically)
  75391. var linearSamplingWeights = [];
  75392. var linearSamplingOffsets = [];
  75393. var linearSamplingMap = [];
  75394. for (var i = 0; i <= centerIndex; i += 2) {
  75395. var j = Math.min(i + 1, Math.floor(centerIndex));
  75396. var singleCenterSample = i === j;
  75397. if (singleCenterSample) {
  75398. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75399. }
  75400. else {
  75401. var sharedCell = j === centerIndex;
  75402. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75403. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75404. if (offsetLinear === 0) {
  75405. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75406. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75407. }
  75408. else {
  75409. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75410. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75411. }
  75412. }
  75413. }
  75414. for (var i = 0; i < linearSamplingMap.length; i++) {
  75415. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75416. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75417. }
  75418. // Replace with optimized
  75419. offsets = linearSamplingOffsets;
  75420. weights = linearSamplingWeights;
  75421. // Generate shaders
  75422. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75423. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75424. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75425. var defines = "";
  75426. defines += this._staticDefines;
  75427. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75428. if (this._staticDefines.indexOf("DOF") != -1) {
  75429. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75430. varyingCount--;
  75431. }
  75432. for (var i = 0; i < varyingCount; i++) {
  75433. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75434. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75435. }
  75436. var depCount = 0;
  75437. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75438. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75439. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75440. depCount++;
  75441. }
  75442. if (this.packedFloat) {
  75443. defines += "#define PACKEDFLOAT 1";
  75444. }
  75445. this.blockCompilation = false;
  75446. _super.prototype.updateEffect.call(this, defines, null, null, {
  75447. varyingCount: varyingCount,
  75448. depCount: depCount
  75449. }, onCompiled, onError);
  75450. };
  75451. /**
  75452. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75453. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75454. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75455. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75456. * The gaps between physical kernels are compensated for in the weighting of the samples
  75457. * @param idealKernel Ideal blur kernel.
  75458. * @return Nearest best kernel.
  75459. */
  75460. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75461. var v = Math.round(idealKernel);
  75462. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75463. var k = _a[_i];
  75464. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75465. return Math.max(k, 3);
  75466. }
  75467. }
  75468. return Math.max(v, 3);
  75469. };
  75470. /**
  75471. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75472. * @param x The point on the Gaussian distribution to sample.
  75473. * @return the value of the Gaussian function at x.
  75474. */
  75475. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75476. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75477. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75478. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75479. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75480. // truncated at around 1.3% of peak strength.
  75481. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75482. var sigma = (1 / 3);
  75483. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75484. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75485. var weight = (1.0 / denominator) * Math.exp(exponent);
  75486. return weight;
  75487. };
  75488. /**
  75489. * Generates a string that can be used as a floating point number in GLSL.
  75490. * @param x Value to print.
  75491. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75492. * @return GLSL float string.
  75493. */
  75494. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75495. if (decimalFigures === void 0) { decimalFigures = 8; }
  75496. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75497. };
  75498. return BlurPostProcess;
  75499. }(BABYLON.PostProcess));
  75500. BABYLON.BlurPostProcess = BlurPostProcess;
  75501. })(BABYLON || (BABYLON = {}));
  75502. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75503. var BABYLON;
  75504. (function (BABYLON) {
  75505. /**
  75506. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75507. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75508. * based on samples that have a large difference in distance than the center pixel.
  75509. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75510. */
  75511. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75512. __extends(DepthOfFieldBlurPostProcess, _super);
  75513. /**
  75514. * Creates a new instance CircleOfConfusionPostProcess
  75515. * @param name The name of the effect.
  75516. * @param scene The scene the effect belongs to.
  75517. * @param direction The direction the blur should be applied.
  75518. * @param kernel The size of the kernel used to blur.
  75519. * @param options The required width/height ratio to downsize to before computing the render pass.
  75520. * @param camera The camera to apply the render pass to.
  75521. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75522. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75523. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75524. * @param engine The engine which the post process will be applied. (default: current engine)
  75525. * @param reusable If the post process can be reused on the same frame. (default: false)
  75526. * @param textureType Type of textures used when performing the post process. (default: 0)
  75527. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  75528. */
  75529. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75530. if (imageToBlur === void 0) { imageToBlur = null; }
  75531. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75532. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75533. if (blockCompilation === void 0) { blockCompilation = false; }
  75534. var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, "#define DOF 1\r\n", blockCompilation) || this;
  75535. _this.direction = direction;
  75536. _this.onApplyObservable.add(function (effect) {
  75537. if (imageToBlur != null) {
  75538. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75539. }
  75540. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75541. if (scene.activeCamera) {
  75542. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75543. }
  75544. });
  75545. return _this;
  75546. }
  75547. return DepthOfFieldBlurPostProcess;
  75548. }(BABYLON.BlurPostProcess));
  75549. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75550. })(BABYLON || (BABYLON = {}));
  75551. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75552. var BABYLON;
  75553. (function (BABYLON) {
  75554. /**
  75555. * Options to be set when merging outputs from the default pipeline.
  75556. */
  75557. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75558. function DepthOfFieldMergePostProcessOptions() {
  75559. }
  75560. return DepthOfFieldMergePostProcessOptions;
  75561. }());
  75562. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75563. /**
  75564. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75565. */
  75566. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75567. __extends(DepthOfFieldMergePostProcess, _super);
  75568. /**
  75569. * Creates a new instance of DepthOfFieldMergePostProcess
  75570. * @param name The name of the effect.
  75571. * @param originalFromInput Post process which's input will be used for the merge.
  75572. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75573. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75574. * @param options The required width/height ratio to downsize to before computing the render pass.
  75575. * @param camera The camera to apply the render pass to.
  75576. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75577. * @param engine The engine which the post process will be applied. (default: current engine)
  75578. * @param reusable If the post process can be reused on the same frame. (default: false)
  75579. * @param textureType Type of textures used when performing the post process. (default: 0)
  75580. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  75581. */
  75582. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75583. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75584. if (blockCompilation === void 0) { blockCompilation = false; }
  75585. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75586. _this.blurSteps = blurSteps;
  75587. _this.onApplyObservable.add(function (effect) {
  75588. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75589. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75590. blurSteps.forEach(function (step, index) {
  75591. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75592. });
  75593. });
  75594. if (!blockCompilation) {
  75595. _this.updateEffect();
  75596. }
  75597. return _this;
  75598. }
  75599. /**
  75600. * Updates the effect with the current post process compile time values and recompiles the shader.
  75601. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75602. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75603. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75604. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  75605. * @param onCompiled Called when the shader has been compiled.
  75606. * @param onError Called if there is an error when compiling a shader.
  75607. */
  75608. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75609. if (defines === void 0) { defines = null; }
  75610. if (uniforms === void 0) { uniforms = null; }
  75611. if (samplers === void 0) { samplers = null; }
  75612. if (!defines) {
  75613. defines = "";
  75614. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75615. }
  75616. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75617. };
  75618. return DepthOfFieldMergePostProcess;
  75619. }(BABYLON.PostProcess));
  75620. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75621. })(BABYLON || (BABYLON = {}));
  75622. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75623. var BABYLON;
  75624. (function (BABYLON) {
  75625. /**
  75626. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75627. */
  75628. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75629. __extends(CircleOfConfusionPostProcess, _super);
  75630. /**
  75631. * Creates a new instance CircleOfConfusionPostProcess
  75632. * @param name The name of the effect.
  75633. * @param depthTexture The depth texture of the scene to compute the circle of confusion. This must be set in order for this to function but may be set after initialization if needed.
  75634. * @param options The required width/height ratio to downsize to before computing the render pass.
  75635. * @param camera The camera to apply the render pass to.
  75636. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75637. * @param engine The engine which the post process will be applied. (default: current engine)
  75638. * @param reusable If the post process can be reused on the same frame. (default: false)
  75639. * @param textureType Type of textures used when performing the post process. (default: 0)
  75640. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  75641. */
  75642. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75643. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75644. if (blockCompilation === void 0) { blockCompilation = false; }
  75645. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75646. /**
  75647. * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
  75648. */
  75649. _this.lensSize = 50;
  75650. /**
  75651. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75652. */
  75653. _this.fStop = 1.4;
  75654. /**
  75655. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75656. */
  75657. _this.focusDistance = 2000;
  75658. /**
  75659. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75660. */
  75661. _this.focalLength = 50;
  75662. _this._depthTexture = null;
  75663. _this._depthTexture = depthTexture;
  75664. _this.onApplyObservable.add(function (effect) {
  75665. if (!_this._depthTexture) {
  75666. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75667. return;
  75668. }
  75669. effect.setTexture("depthSampler", _this._depthTexture);
  75670. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75671. var aperture = _this.lensSize / _this.fStop;
  75672. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75673. effect.setFloat('focusDistance', _this.focusDistance);
  75674. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75675. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75676. });
  75677. return _this;
  75678. }
  75679. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75680. /**
  75681. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  75682. */
  75683. set: function (value) {
  75684. this._depthTexture = value;
  75685. },
  75686. enumerable: true,
  75687. configurable: true
  75688. });
  75689. return CircleOfConfusionPostProcess;
  75690. }(BABYLON.PostProcess));
  75691. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75692. })(BABYLON || (BABYLON = {}));
  75693. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75694. var BABYLON;
  75695. (function (BABYLON) {
  75696. /**
  75697. * Specifies the level of max blur that should be applied when using the depth of field effect
  75698. */
  75699. var DepthOfFieldEffectBlurLevel;
  75700. (function (DepthOfFieldEffectBlurLevel) {
  75701. /**
  75702. * Subtle blur
  75703. */
  75704. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75705. /**
  75706. * Medium blur
  75707. */
  75708. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75709. /**
  75710. * Large blur
  75711. */
  75712. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75713. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75714. ;
  75715. /**
  75716. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75717. */
  75718. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75719. __extends(DepthOfFieldEffect, _super);
  75720. /**
  75721. * Creates a new instance DepthOfFieldEffect
  75722. * @param scene The scene the effect belongs to.
  75723. * @param depthTexture The depth texture of the scene to compute the circle of confusion.This must be set in order for this to function but may be set after initialization if needed.
  75724. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75725. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  75726. */
  75727. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75728. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75729. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75730. if (blockCompilation === void 0) { blockCompilation = false; }
  75731. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75732. return _this._effects;
  75733. }, true) || this;
  75734. /**
  75735. * Internal post processes in depth of field effect
  75736. */
  75737. _this._effects = [];
  75738. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75739. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75740. // Create a pyramid of blurred images (eg. fullSize 1/4 blur, half size 1/2 blur, quarter size 3/4 blur, eith size 4/4 blur)
  75741. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75742. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75743. _this._depthOfFieldBlurY = [];
  75744. _this._depthOfFieldBlurX = [];
  75745. var blurCount = 1;
  75746. var kernelSize = 15;
  75747. switch (blurLevel) {
  75748. case DepthOfFieldEffectBlurLevel.High: {
  75749. blurCount = 3;
  75750. kernelSize = 51;
  75751. break;
  75752. }
  75753. case DepthOfFieldEffectBlurLevel.Medium: {
  75754. blurCount = 2;
  75755. kernelSize = 31;
  75756. break;
  75757. }
  75758. default: {
  75759. kernelSize = 15;
  75760. blurCount = 1;
  75761. break;
  75762. }
  75763. }
  75764. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75765. var ratio = 1.0;
  75766. for (var i = 0; i < blurCount; i++) {
  75767. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75768. blurY.autoClear = false;
  75769. ratio = 0.75 / Math.pow(2, i);
  75770. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75771. blurX.autoClear = false;
  75772. _this._depthOfFieldBlurY.push(blurY);
  75773. _this._depthOfFieldBlurX.push(blurX);
  75774. }
  75775. // Set all post processes on the effect.
  75776. _this._effects = [_this._circleOfConfusion];
  75777. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75778. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75779. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75780. }
  75781. // Merge blurred images with original image based on circleOfConfusion
  75782. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75783. _this._dofMerge.autoClear = false;
  75784. _this._effects.push(_this._dofMerge);
  75785. return _this;
  75786. }
  75787. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75788. get: function () {
  75789. return this._circleOfConfusion.focalLength;
  75790. },
  75791. /**
  75792. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75793. */
  75794. set: function (value) {
  75795. this._circleOfConfusion.focalLength = value;
  75796. },
  75797. enumerable: true,
  75798. configurable: true
  75799. });
  75800. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75801. get: function () {
  75802. return this._circleOfConfusion.fStop;
  75803. },
  75804. /**
  75805. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75806. */
  75807. set: function (value) {
  75808. this._circleOfConfusion.fStop = value;
  75809. },
  75810. enumerable: true,
  75811. configurable: true
  75812. });
  75813. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75814. get: function () {
  75815. return this._circleOfConfusion.focusDistance;
  75816. },
  75817. /**
  75818. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75819. */
  75820. set: function (value) {
  75821. this._circleOfConfusion.focusDistance = value;
  75822. },
  75823. enumerable: true,
  75824. configurable: true
  75825. });
  75826. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75827. get: function () {
  75828. return this._circleOfConfusion.lensSize;
  75829. },
  75830. /**
  75831. * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
  75832. */
  75833. set: function (value) {
  75834. this._circleOfConfusion.lensSize = value;
  75835. },
  75836. enumerable: true,
  75837. configurable: true
  75838. });
  75839. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75840. /**
  75841. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  75842. */
  75843. set: function (value) {
  75844. this._circleOfConfusion.depthTexture = value;
  75845. },
  75846. enumerable: true,
  75847. configurable: true
  75848. });
  75849. /**
  75850. * Disposes each of the internal effects for a given camera.
  75851. * @param camera The camera to dispose the effect on.
  75852. */
  75853. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75854. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75855. this._effects[effectIndex].dispose(camera);
  75856. }
  75857. };
  75858. /**
  75859. * Internal
  75860. */
  75861. DepthOfFieldEffect.prototype._updateEffects = function () {
  75862. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75863. this._effects[effectIndex].updateEffect();
  75864. }
  75865. };
  75866. /**
  75867. * Internal
  75868. * @returns if all the contained post processes are ready.
  75869. */
  75870. DepthOfFieldEffect.prototype._isReady = function () {
  75871. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75872. if (!this._effects[effectIndex].isReady()) {
  75873. return false;
  75874. }
  75875. }
  75876. return true;
  75877. };
  75878. return DepthOfFieldEffect;
  75879. }(BABYLON.PostProcessRenderEffect));
  75880. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75881. })(BABYLON || (BABYLON = {}));
  75882. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75883. var BABYLON;
  75884. (function (BABYLON) {
  75885. /**
  75886. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75887. */
  75888. var BloomMergePostProcess = /** @class */ (function (_super) {
  75889. __extends(BloomMergePostProcess, _super);
  75890. /**
  75891. * Creates a new instance of @see BloomMergePostProcess
  75892. * @param name The name of the effect.
  75893. * @param originalFromInput Post process which's input will be used for the merge.
  75894. * @param blurred Blurred highlights post process which's output will be used.
  75895. * @param weight Weight of the bloom to be added to the original input.
  75896. * @param options The required width/height ratio to downsize to before computing the render pass.
  75897. * @param camera The camera to apply the render pass to.
  75898. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75899. * @param engine The engine which the post process will be applied. (default: current engine)
  75900. * @param reusable If the post process can be reused on the same frame. (default: false)
  75901. * @param textureType Type of textures used when performing the post process. (default: 0)
  75902. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  75903. */
  75904. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75905. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75906. if (blockCompilation === void 0) { blockCompilation = false; }
  75907. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75908. _this.weight = weight;
  75909. _this.onApplyObservable.add(function (effect) {
  75910. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75911. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75912. effect.setFloat("bloomWeight", _this.weight);
  75913. });
  75914. if (!blockCompilation) {
  75915. _this.updateEffect();
  75916. }
  75917. return _this;
  75918. }
  75919. return BloomMergePostProcess;
  75920. }(BABYLON.PostProcess));
  75921. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75922. })(BABYLON || (BABYLON = {}));
  75923. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75924. var BABYLON;
  75925. (function (BABYLON) {
  75926. /**
  75927. * The extract highlights post process sets all pixels to black except pixels above the specified luminance threshold. Used as the first step for a bloom effect.
  75928. */
  75929. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75930. __extends(ExtractHighlightsPostProcess, _super);
  75931. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75932. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75933. if (blockCompilation === void 0) { blockCompilation = false; }
  75934. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75935. /**
  75936. * The luminance threshold, pixels below this value will be set to black.
  75937. */
  75938. _this.threshold = 0.9;
  75939. /**
  75940. * Internal
  75941. */
  75942. _this._exposure = 1;
  75943. /**
  75944. * Post process which has the input texture to be used when performing highlight extraction
  75945. */
  75946. _this._inputPostProcess = null;
  75947. _this.onApplyObservable.add(function (effect) {
  75948. if (_this._inputPostProcess) {
  75949. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75950. }
  75951. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75952. effect.setFloat('exposure', _this._exposure);
  75953. });
  75954. return _this;
  75955. }
  75956. return ExtractHighlightsPostProcess;
  75957. }(BABYLON.PostProcess));
  75958. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75959. })(BABYLON || (BABYLON = {}));
  75960. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75961. var BABYLON;
  75962. (function (BABYLON) {
  75963. /**
  75964. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75965. */
  75966. var BloomEffect = /** @class */ (function (_super) {
  75967. __extends(BloomEffect, _super);
  75968. /**
  75969. * Creates a new instance of @see BloomEffect
  75970. * @param scene The scene the effect belongs to.
  75971. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75972. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75973. * @param bloomWeight The the strength of bloom.
  75974. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75975. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  75976. */
  75977. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75978. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75979. if (blockCompilation === void 0) { blockCompilation = false; }
  75980. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75981. return _this._effects;
  75982. }, true) || this;
  75983. _this.bloomScale = bloomScale;
  75984. /**
  75985. * Internal
  75986. */
  75987. _this._effects = [];
  75988. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75989. _this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  75990. _this._blurX.alwaysForcePOT = true;
  75991. _this._blurX.autoClear = false;
  75992. _this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  75993. _this._blurY.alwaysForcePOT = true;
  75994. _this._blurY.autoClear = false;
  75995. _this.kernel = bloomKernel;
  75996. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75997. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75998. _this._merge.autoClear = false;
  75999. _this._effects.push(_this._merge);
  76000. return _this;
  76001. }
  76002. Object.defineProperty(BloomEffect.prototype, "threshold", {
  76003. /**
  76004. * The luminance threshold to find bright areas of the image to bloom.
  76005. */
  76006. get: function () {
  76007. return this._downscale.threshold;
  76008. },
  76009. set: function (value) {
  76010. this._downscale.threshold = value;
  76011. },
  76012. enumerable: true,
  76013. configurable: true
  76014. });
  76015. Object.defineProperty(BloomEffect.prototype, "weight", {
  76016. /**
  76017. * The strength of the bloom.
  76018. */
  76019. get: function () {
  76020. return this._merge.weight;
  76021. },
  76022. set: function (value) {
  76023. this._merge.weight = value;
  76024. },
  76025. enumerable: true,
  76026. configurable: true
  76027. });
  76028. Object.defineProperty(BloomEffect.prototype, "kernel", {
  76029. /**
  76030. * Specifies the size of the bloom blur kernel, relative to the final output size
  76031. */
  76032. get: function () {
  76033. return this._blurX.kernel / this.bloomScale;
  76034. },
  76035. set: function (value) {
  76036. this._blurX.kernel = value * this.bloomScale;
  76037. this._blurY.kernel = value * this.bloomScale;
  76038. },
  76039. enumerable: true,
  76040. configurable: true
  76041. });
  76042. /**
  76043. * Disposes each of the internal effects for a given camera.
  76044. * @param camera The camera to dispose the effect on.
  76045. */
  76046. BloomEffect.prototype.disposeEffects = function (camera) {
  76047. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76048. this._effects[effectIndex].dispose(camera);
  76049. }
  76050. };
  76051. /**
  76052. * Internal
  76053. */
  76054. BloomEffect.prototype._updateEffects = function () {
  76055. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76056. this._effects[effectIndex].updateEffect();
  76057. }
  76058. };
  76059. /**
  76060. * Internal
  76061. * @returns if all the contained post processes are ready.
  76062. */
  76063. BloomEffect.prototype._isReady = function () {
  76064. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76065. if (!this._effects[effectIndex].isReady()) {
  76066. return false;
  76067. }
  76068. }
  76069. return true;
  76070. };
  76071. return BloomEffect;
  76072. }(BABYLON.PostProcessRenderEffect));
  76073. BABYLON.BloomEffect = BloomEffect;
  76074. })(BABYLON || (BABYLON = {}));
  76075. //# sourceMappingURL=babylon.bloomEffect.js.map
  76076. var BABYLON;
  76077. (function (BABYLON) {
  76078. /**
  76079. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  76080. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  76081. */
  76082. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  76083. __extends(DefaultRenderingPipeline, _super);
  76084. /**
  76085. * @constructor
  76086. * @param {string} name - The rendering pipeline name (default: "")
  76087. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  76088. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  76089. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  76090. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  76091. */
  76092. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  76093. if (name === void 0) { name = ""; }
  76094. if (hdr === void 0) { hdr = true; }
  76095. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76096. if (automaticBuild === void 0) { automaticBuild = true; }
  76097. var _this = _super.call(this, scene.getEngine(), name) || this;
  76098. _this._originalCameras = [];
  76099. /**
  76100. * ID of the sharpen post process,
  76101. */
  76102. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  76103. /**
  76104. * ID of the image processing post process;
  76105. */
  76106. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  76107. /**
  76108. * ID of the Fast Approximate Anti-Aliasing post process;
  76109. */
  76110. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  76111. /**
  76112. * ID of the chromatic aberration post process,
  76113. */
  76114. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  76115. /**
  76116. * ID of the grain post process
  76117. */
  76118. _this.GrainPostProcessId = "GrainPostProcessEffect";
  76119. /**
  76120. * Glow post process which adds a glow to emmisive areas of the image
  76121. */
  76122. _this._glowLayer = null;
  76123. /**
  76124. * Animations which can be used to tweak settings over a period of time
  76125. */
  76126. _this.animations = [];
  76127. _this._imageProcessingConfigurationObserver = null;
  76128. // Values
  76129. _this._sharpenEnabled = false;
  76130. _this._bloomEnabled = false;
  76131. _this._depthOfFieldEnabled = false;
  76132. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  76133. _this._fxaaEnabled = false;
  76134. _this._imageProcessingEnabled = true;
  76135. _this._bloomScale = 0.5;
  76136. _this._chromaticAberrationEnabled = false;
  76137. _this._grainEnabled = false;
  76138. _this._buildAllowed = true;
  76139. _this._resizeObserver = null;
  76140. _this._hardwareScaleLevel = 1.0;
  76141. _this._bloomKernel = 64;
  76142. /**
  76143. * Specifies the weight of the bloom in the final rendering
  76144. */
  76145. _this._bloomWeight = 0.15;
  76146. /**
  76147. * Specifies the luma threshold for the area that will be blurred by the bloom
  76148. */
  76149. _this._bloomThreshold = 0.9;
  76150. _this._samples = 1;
  76151. _this._hasCleared = false;
  76152. _this._prevPostProcess = null;
  76153. _this._prevPrevPostProcess = null;
  76154. _this._cameras = cameras || scene.cameras;
  76155. _this._originalCameras = _this._cameras.slice();
  76156. _this._buildAllowed = automaticBuild;
  76157. // Initialize
  76158. _this._scene = scene;
  76159. var caps = _this._scene.getEngine().getCaps();
  76160. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  76161. // Misc
  76162. if (_this._hdr) {
  76163. if (caps.textureHalfFloatRender) {
  76164. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76165. }
  76166. else if (caps.textureFloatRender) {
  76167. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76168. }
  76169. }
  76170. else {
  76171. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76172. }
  76173. // Attach
  76174. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76175. var engine = _this._scene.getEngine();
  76176. // Create post processes before hand so they can be modified before enabled.
  76177. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  76178. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76179. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  76180. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  76181. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  76182. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76183. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  76184. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76185. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  76186. _this._resizeObserver = engine.onResizeObservable.add(function () {
  76187. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  76188. _this.bloomKernel = _this.bloomKernel;
  76189. });
  76190. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  76191. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  76192. });
  76193. _this._buildPipeline();
  76194. return _this;
  76195. }
  76196. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  76197. get: function () {
  76198. return this._sharpenEnabled;
  76199. },
  76200. /**
  76201. * Enable or disable the sharpen process from the pipeline
  76202. */
  76203. set: function (enabled) {
  76204. if (this._sharpenEnabled === enabled) {
  76205. return;
  76206. }
  76207. this._sharpenEnabled = enabled;
  76208. this._buildPipeline();
  76209. },
  76210. enumerable: true,
  76211. configurable: true
  76212. });
  76213. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  76214. /**
  76215. * Specifies the size of the bloom blur kernel, relative to the final output size
  76216. */
  76217. get: function () {
  76218. return this._bloomKernel;
  76219. },
  76220. set: function (value) {
  76221. this._bloomKernel = value;
  76222. this.bloom.kernel = value / this._hardwareScaleLevel;
  76223. },
  76224. enumerable: true,
  76225. configurable: true
  76226. });
  76227. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  76228. get: function () {
  76229. return this._bloomWeight;
  76230. },
  76231. /**
  76232. * The strength of the bloom.
  76233. */
  76234. set: function (value) {
  76235. if (this._bloomWeight === value) {
  76236. return;
  76237. }
  76238. this.bloom.weight = value;
  76239. this._bloomWeight = value;
  76240. },
  76241. enumerable: true,
  76242. configurable: true
  76243. });
  76244. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76245. get: function () {
  76246. return this._bloomThreshold;
  76247. },
  76248. /**
  76249. * The strength of the bloom.
  76250. */
  76251. set: function (value) {
  76252. if (this._bloomThreshold === value) {
  76253. return;
  76254. }
  76255. this.bloom.threshold = value;
  76256. this._bloomThreshold = value;
  76257. },
  76258. enumerable: true,
  76259. configurable: true
  76260. });
  76261. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76262. get: function () {
  76263. return this._bloomScale;
  76264. },
  76265. /**
  76266. * The scale of the bloom, lower value will provide better performance.
  76267. */
  76268. set: function (value) {
  76269. if (this._bloomScale === value) {
  76270. return;
  76271. }
  76272. this._bloomScale = value;
  76273. // recreate bloom and dispose old as this setting is not dynamic
  76274. this._rebuildBloom();
  76275. this._buildPipeline();
  76276. },
  76277. enumerable: true,
  76278. configurable: true
  76279. });
  76280. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76281. get: function () {
  76282. return this._bloomEnabled;
  76283. },
  76284. /**
  76285. * Enable or disable the bloom from the pipeline
  76286. */
  76287. set: function (enabled) {
  76288. if (this._bloomEnabled === enabled) {
  76289. return;
  76290. }
  76291. this._bloomEnabled = enabled;
  76292. this._buildPipeline();
  76293. },
  76294. enumerable: true,
  76295. configurable: true
  76296. });
  76297. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76298. // recreate bloom and dispose old as this setting is not dynamic
  76299. var oldBloom = this.bloom;
  76300. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76301. this.bloom.threshold = oldBloom.threshold;
  76302. for (var i = 0; i < this._cameras.length; i++) {
  76303. oldBloom.disposeEffects(this._cameras[i]);
  76304. }
  76305. };
  76306. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76307. /**
  76308. * If the depth of field is enabled.
  76309. */
  76310. get: function () {
  76311. return this._depthOfFieldEnabled;
  76312. },
  76313. set: function (enabled) {
  76314. if (this._depthOfFieldEnabled === enabled) {
  76315. return;
  76316. }
  76317. this._depthOfFieldEnabled = enabled;
  76318. this._buildPipeline();
  76319. },
  76320. enumerable: true,
  76321. configurable: true
  76322. });
  76323. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76324. /**
  76325. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76326. */
  76327. get: function () {
  76328. return this._depthOfFieldBlurLevel;
  76329. },
  76330. set: function (value) {
  76331. if (this._depthOfFieldBlurLevel === value) {
  76332. return;
  76333. }
  76334. this._depthOfFieldBlurLevel = value;
  76335. // recreate dof and dispose old as this setting is not dynamic
  76336. var oldDof = this.depthOfField;
  76337. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76338. this.depthOfField.focalLength = oldDof.focalLength;
  76339. this.depthOfField.focusDistance = oldDof.focusDistance;
  76340. this.depthOfField.fStop = oldDof.fStop;
  76341. this.depthOfField.lensSize = oldDof.lensSize;
  76342. for (var i = 0; i < this._cameras.length; i++) {
  76343. oldDof.disposeEffects(this._cameras[i]);
  76344. }
  76345. this._buildPipeline();
  76346. },
  76347. enumerable: true,
  76348. configurable: true
  76349. });
  76350. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76351. get: function () {
  76352. return this._fxaaEnabled;
  76353. },
  76354. /**
  76355. * If the anti aliasing is enabled.
  76356. */
  76357. set: function (enabled) {
  76358. if (this._fxaaEnabled === enabled) {
  76359. return;
  76360. }
  76361. this._fxaaEnabled = enabled;
  76362. this._buildPipeline();
  76363. },
  76364. enumerable: true,
  76365. configurable: true
  76366. });
  76367. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76368. get: function () {
  76369. return this._samples;
  76370. },
  76371. /**
  76372. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76373. */
  76374. set: function (sampleCount) {
  76375. if (this._samples === sampleCount) {
  76376. return;
  76377. }
  76378. this._samples = sampleCount;
  76379. this._buildPipeline();
  76380. },
  76381. enumerable: true,
  76382. configurable: true
  76383. });
  76384. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76385. get: function () {
  76386. return this._imageProcessingEnabled;
  76387. },
  76388. /**
  76389. * If image processing is enabled.
  76390. */
  76391. set: function (enabled) {
  76392. if (this._imageProcessingEnabled === enabled) {
  76393. return;
  76394. }
  76395. this._imageProcessingEnabled = enabled;
  76396. this._buildPipeline();
  76397. },
  76398. enumerable: true,
  76399. configurable: true
  76400. });
  76401. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76402. get: function () {
  76403. return this._glowLayer == null;
  76404. },
  76405. /**
  76406. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76407. */
  76408. set: function (enabled) {
  76409. if (enabled && !this._glowLayer) {
  76410. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76411. }
  76412. else if (!enabled && this._glowLayer) {
  76413. this._glowLayer.dispose();
  76414. this._glowLayer = null;
  76415. }
  76416. },
  76417. enumerable: true,
  76418. configurable: true
  76419. });
  76420. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76421. get: function () {
  76422. return this._chromaticAberrationEnabled;
  76423. },
  76424. /**
  76425. * Enable or disable the chromaticAberration process from the pipeline
  76426. */
  76427. set: function (enabled) {
  76428. if (this._chromaticAberrationEnabled === enabled) {
  76429. return;
  76430. }
  76431. this._chromaticAberrationEnabled = enabled;
  76432. this._buildPipeline();
  76433. },
  76434. enumerable: true,
  76435. configurable: true
  76436. });
  76437. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76438. get: function () {
  76439. return this._grainEnabled;
  76440. },
  76441. /**
  76442. * Enable or disable the grain process from the pipeline
  76443. */
  76444. set: function (enabled) {
  76445. if (this._grainEnabled === enabled) {
  76446. return;
  76447. }
  76448. this._grainEnabled = enabled;
  76449. this._buildPipeline();
  76450. },
  76451. enumerable: true,
  76452. configurable: true
  76453. });
  76454. /**
  76455. * Force the compilation of the entire pipeline.
  76456. */
  76457. DefaultRenderingPipeline.prototype.prepare = function () {
  76458. var previousState = this._buildAllowed;
  76459. this._buildAllowed = true;
  76460. this._buildPipeline();
  76461. this._buildAllowed = previousState;
  76462. };
  76463. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76464. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76465. if (this._hasCleared) {
  76466. postProcess.autoClear = false;
  76467. }
  76468. else {
  76469. postProcess.autoClear = true;
  76470. this._scene.autoClear = false;
  76471. this._hasCleared = true;
  76472. }
  76473. if (!skipTextureSharing) {
  76474. if (this._prevPrevPostProcess) {
  76475. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76476. }
  76477. else {
  76478. postProcess.useOwnOutput();
  76479. }
  76480. if (this._prevPostProcess) {
  76481. this._prevPrevPostProcess = this._prevPostProcess;
  76482. }
  76483. this._prevPostProcess = postProcess;
  76484. }
  76485. };
  76486. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76487. var _this = this;
  76488. if (!this._buildAllowed) {
  76489. return;
  76490. }
  76491. this._scene.autoClear = true;
  76492. var engine = this._scene.getEngine();
  76493. this._disposePostProcesses();
  76494. if (this._cameras !== null) {
  76495. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76496. // get back cameras to be used to reattach pipeline
  76497. this._cameras = this._originalCameras.slice();
  76498. }
  76499. this._reset();
  76500. this._prevPostProcess = null;
  76501. this._prevPrevPostProcess = null;
  76502. this._hasCleared = false;
  76503. if (this.depthOfFieldEnabled) {
  76504. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76505. this.depthOfField.depthTexture = depthTexture;
  76506. if (!this.depthOfField._isReady()) {
  76507. this.depthOfField._updateEffects();
  76508. }
  76509. this.addEffect(this.depthOfField);
  76510. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76511. }
  76512. if (this.bloomEnabled) {
  76513. if (!this.bloom._isReady()) {
  76514. this.bloom._updateEffects();
  76515. }
  76516. this.addEffect(this.bloom);
  76517. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76518. }
  76519. if (this._imageProcessingEnabled) {
  76520. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76521. if (this._hdr) {
  76522. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76523. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76524. }
  76525. else {
  76526. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76527. }
  76528. }
  76529. if (this.sharpenEnabled) {
  76530. if (!this.sharpen.isReady()) {
  76531. this.sharpen.updateEffect();
  76532. }
  76533. this.addEffect(this._sharpenEffect);
  76534. this._setAutoClearAndTextureSharing(this.sharpen);
  76535. }
  76536. if (this.grainEnabled) {
  76537. if (!this.grain.isReady()) {
  76538. this.grain.updateEffect();
  76539. }
  76540. this.addEffect(this._grainEffect);
  76541. this._setAutoClearAndTextureSharing(this.grain);
  76542. }
  76543. if (this.chromaticAberrationEnabled) {
  76544. if (!this.chromaticAberration.isReady()) {
  76545. this.chromaticAberration.updateEffect();
  76546. }
  76547. this.addEffect(this._chromaticAberrationEffect);
  76548. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76549. }
  76550. if (this.fxaaEnabled) {
  76551. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76552. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76553. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76554. }
  76555. if (this._cameras !== null) {
  76556. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76557. }
  76558. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76559. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76560. }
  76561. };
  76562. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76563. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76564. for (var i = 0; i < this._cameras.length; i++) {
  76565. var camera = this._cameras[i];
  76566. if (this.imageProcessing) {
  76567. this.imageProcessing.dispose(camera);
  76568. }
  76569. if (this.fxaa) {
  76570. this.fxaa.dispose(camera);
  76571. }
  76572. // These are created in the constructor and should not be disposed on every pipeline change
  76573. if (disposeNonRecreated) {
  76574. if (this.sharpen) {
  76575. this.sharpen.dispose(camera);
  76576. }
  76577. if (this.depthOfField) {
  76578. this.depthOfField.disposeEffects(camera);
  76579. }
  76580. if (this.bloom) {
  76581. this.bloom.disposeEffects(camera);
  76582. }
  76583. if (this.chromaticAberration) {
  76584. this.chromaticAberration.dispose(camera);
  76585. }
  76586. if (this.grain) {
  76587. this.grain.dispose(camera);
  76588. }
  76589. if (this._glowLayer) {
  76590. this._glowLayer.dispose();
  76591. }
  76592. }
  76593. }
  76594. this.imageProcessing = null;
  76595. this.fxaa = null;
  76596. if (disposeNonRecreated) {
  76597. this.sharpen = null;
  76598. this._sharpenEffect = null;
  76599. this.depthOfField = null;
  76600. this.bloom = null;
  76601. this.chromaticAberration = null;
  76602. this._chromaticAberrationEffect = null;
  76603. this.grain = null;
  76604. this._grainEffect = null;
  76605. this._glowLayer = null;
  76606. }
  76607. };
  76608. /**
  76609. * Dispose of the pipeline and stop all post processes
  76610. */
  76611. DefaultRenderingPipeline.prototype.dispose = function () {
  76612. this._disposePostProcesses(true);
  76613. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76614. this._scene.autoClear = true;
  76615. if (this._resizeObserver) {
  76616. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76617. this._resizeObserver = null;
  76618. }
  76619. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76620. _super.prototype.dispose.call(this);
  76621. };
  76622. /**
  76623. * Serialize the rendering pipeline (Used when exporting)
  76624. * @returns the serialized object
  76625. */
  76626. DefaultRenderingPipeline.prototype.serialize = function () {
  76627. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76628. serializationObject.customType = "DefaultRenderingPipeline";
  76629. return serializationObject;
  76630. };
  76631. /**
  76632. * Parse the serialized pipeline
  76633. * @param source Source pipeline.
  76634. * @param scene The scene to load the pipeline to.
  76635. * @param rootUrl The URL of the serialized pipeline.
  76636. * @returns An instantiated pipeline from the serialized object.
  76637. */
  76638. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76639. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76640. };
  76641. __decorate([
  76642. BABYLON.serialize()
  76643. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76644. __decorate([
  76645. BABYLON.serialize()
  76646. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76647. __decorate([
  76648. BABYLON.serialize()
  76649. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76650. __decorate([
  76651. BABYLON.serialize()
  76652. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76653. __decorate([
  76654. BABYLON.serialize()
  76655. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76656. __decorate([
  76657. BABYLON.serialize()
  76658. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76659. __decorate([
  76660. BABYLON.serialize()
  76661. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76662. __decorate([
  76663. BABYLON.serialize()
  76664. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76665. __decorate([
  76666. BABYLON.serialize()
  76667. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76668. __decorate([
  76669. BABYLON.serialize()
  76670. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76671. __decorate([
  76672. BABYLON.serialize()
  76673. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76674. __decorate([
  76675. BABYLON.serialize()
  76676. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76677. __decorate([
  76678. BABYLON.serialize()
  76679. ], DefaultRenderingPipeline.prototype, "samples", null);
  76680. __decorate([
  76681. BABYLON.serialize()
  76682. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76683. __decorate([
  76684. BABYLON.serialize()
  76685. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76686. __decorate([
  76687. BABYLON.serialize()
  76688. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76689. __decorate([
  76690. BABYLON.serialize()
  76691. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76692. return DefaultRenderingPipeline;
  76693. }(BABYLON.PostProcessRenderPipeline));
  76694. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76695. })(BABYLON || (BABYLON = {}));
  76696. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76697. var BABYLON;
  76698. (function (BABYLON) {
  76699. /**
  76700. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76701. */
  76702. var GeometryBufferRenderer = /** @class */ (function () {
  76703. /**
  76704. * Creates a new G Buffer for the scene
  76705. * @param scene The scene the buffer belongs to
  76706. * @param ratio How big is the buffer related to the main canvas.
  76707. */
  76708. function GeometryBufferRenderer(scene, ratio) {
  76709. if (ratio === void 0) { ratio = 1; }
  76710. this._enablePosition = false;
  76711. this._scene = scene;
  76712. this._ratio = ratio;
  76713. // Render target
  76714. this._createRenderTargets();
  76715. }
  76716. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76717. /**
  76718. * Set the render list (meshes to be rendered) used in the G buffer.
  76719. */
  76720. set: function (meshes) {
  76721. this._multiRenderTarget.renderList = meshes;
  76722. },
  76723. enumerable: true,
  76724. configurable: true
  76725. });
  76726. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76727. /**
  76728. * Gets wether or not G buffer are supported by the running hardware.
  76729. * This requires draw buffer supports
  76730. */
  76731. get: function () {
  76732. return this._multiRenderTarget.isSupported;
  76733. },
  76734. enumerable: true,
  76735. configurable: true
  76736. });
  76737. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76738. /**
  76739. * Gets wether or not position are enabled for the G buffer.
  76740. */
  76741. get: function () {
  76742. return this._enablePosition;
  76743. },
  76744. /**
  76745. * Sets wether or not position are enabled for the G buffer.
  76746. */
  76747. set: function (enable) {
  76748. this._enablePosition = enable;
  76749. this.dispose();
  76750. this._createRenderTargets();
  76751. },
  76752. enumerable: true,
  76753. configurable: true
  76754. });
  76755. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76756. /**
  76757. * Gets the scene associated with the buffer.
  76758. */
  76759. get: function () {
  76760. return this._scene;
  76761. },
  76762. enumerable: true,
  76763. configurable: true
  76764. });
  76765. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76766. /**
  76767. * Gets the ratio used by the buffer during its creation.
  76768. * How big is the buffer related to the main canvas.
  76769. */
  76770. get: function () {
  76771. return this._ratio;
  76772. },
  76773. enumerable: true,
  76774. configurable: true
  76775. });
  76776. /**
  76777. * Checks wether everything is ready to render a submesh to the G buffer.
  76778. * @param subMesh the submesh to check readiness for
  76779. * @param useInstances is the mesh drawn using instance or not
  76780. * @returns true if ready otherwise false
  76781. */
  76782. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76783. var material = subMesh.getMaterial();
  76784. if (material && material.disableDepthWrite) {
  76785. return false;
  76786. }
  76787. var defines = [];
  76788. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76789. var mesh = subMesh.getMesh();
  76790. // Alpha test
  76791. if (material && material.needAlphaTesting()) {
  76792. defines.push("#define ALPHATEST");
  76793. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76794. attribs.push(BABYLON.VertexBuffer.UVKind);
  76795. defines.push("#define UV1");
  76796. }
  76797. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76798. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76799. defines.push("#define UV2");
  76800. }
  76801. }
  76802. // Buffers
  76803. if (this._enablePosition) {
  76804. defines.push("#define POSITION");
  76805. }
  76806. // Bones
  76807. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76808. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76809. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76810. if (mesh.numBoneInfluencers > 4) {
  76811. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76812. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76813. }
  76814. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76815. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76816. }
  76817. else {
  76818. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76819. }
  76820. // Instances
  76821. if (useInstances) {
  76822. defines.push("#define INSTANCES");
  76823. attribs.push("world0");
  76824. attribs.push("world1");
  76825. attribs.push("world2");
  76826. attribs.push("world3");
  76827. }
  76828. // Get correct effect
  76829. var join = defines.join("\n");
  76830. if (this._cachedDefines !== join) {
  76831. this._cachedDefines = join;
  76832. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76833. }
  76834. return this._effect.isReady();
  76835. };
  76836. /**
  76837. * Gets the current underlying G Buffer.
  76838. * @returns the buffer
  76839. */
  76840. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76841. return this._multiRenderTarget;
  76842. };
  76843. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76844. /**
  76845. * Gets the number of samples used to render the buffer (anti aliasing).
  76846. */
  76847. get: function () {
  76848. return this._multiRenderTarget.samples;
  76849. },
  76850. /**
  76851. * Sets the number of samples used to render the buffer (anti aliasing).
  76852. */
  76853. set: function (value) {
  76854. this._multiRenderTarget.samples = value;
  76855. },
  76856. enumerable: true,
  76857. configurable: true
  76858. });
  76859. /**
  76860. * Disposes the renderer and frees up associated resources.
  76861. */
  76862. GeometryBufferRenderer.prototype.dispose = function () {
  76863. this.getGBuffer().dispose();
  76864. };
  76865. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76866. var _this = this;
  76867. var engine = this._scene.getEngine();
  76868. var count = this._enablePosition ? 3 : 2;
  76869. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true, defaultType: BABYLON.Engine.TEXTURETYPE_FLOAT });
  76870. if (!this.isSupported) {
  76871. return;
  76872. }
  76873. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76874. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76875. this._multiRenderTarget.refreshRate = 1;
  76876. this._multiRenderTarget.renderParticles = false;
  76877. this._multiRenderTarget.renderList = null;
  76878. // set default depth value to 1.0 (far away)
  76879. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76880. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76881. });
  76882. // Custom render function
  76883. var renderSubMesh = function (subMesh) {
  76884. var mesh = subMesh.getRenderingMesh();
  76885. var scene = _this._scene;
  76886. var engine = scene.getEngine();
  76887. var material = subMesh.getMaterial();
  76888. if (!material) {
  76889. return;
  76890. }
  76891. // Culling
  76892. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76893. // Managing instances
  76894. var batch = mesh._getInstancesRenderList(subMesh._id);
  76895. if (batch.mustReturn) {
  76896. return;
  76897. }
  76898. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76899. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76900. engine.enableEffect(_this._effect);
  76901. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76902. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76903. _this._effect.setMatrix("view", scene.getViewMatrix());
  76904. // Alpha test
  76905. if (material && material.needAlphaTesting()) {
  76906. var alphaTexture = material.getAlphaTestTexture();
  76907. if (alphaTexture) {
  76908. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76909. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76910. }
  76911. }
  76912. // Bones
  76913. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76914. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76915. }
  76916. // Draw
  76917. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76918. }
  76919. };
  76920. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76921. var index;
  76922. if (depthOnlySubMeshes.length) {
  76923. engine.setColorWrite(false);
  76924. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76925. renderSubMesh(depthOnlySubMeshes.data[index]);
  76926. }
  76927. engine.setColorWrite(true);
  76928. }
  76929. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76930. renderSubMesh(opaqueSubMeshes.data[index]);
  76931. }
  76932. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76933. renderSubMesh(alphaTestSubMeshes.data[index]);
  76934. }
  76935. };
  76936. };
  76937. return GeometryBufferRenderer;
  76938. }());
  76939. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76940. })(BABYLON || (BABYLON = {}));
  76941. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76942. var BABYLON;
  76943. (function (BABYLON) {
  76944. var RefractionPostProcess = /** @class */ (function (_super) {
  76945. __extends(RefractionPostProcess, _super);
  76946. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  76947. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  76948. _this.color = color;
  76949. _this.depth = depth;
  76950. _this.colorLevel = colorLevel;
  76951. _this._ownRefractionTexture = true;
  76952. _this.onActivateObservable.add(function (cam) {
  76953. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  76954. });
  76955. _this.onApplyObservable.add(function (effect) {
  76956. effect.setColor3("baseColor", _this.color);
  76957. effect.setFloat("depth", _this.depth);
  76958. effect.setFloat("colorLevel", _this.colorLevel);
  76959. effect.setTexture("refractionSampler", _this._refTexture);
  76960. });
  76961. return _this;
  76962. }
  76963. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  76964. /**
  76965. * Gets or sets the refraction texture
  76966. * Please note that you are responsible for disposing the texture if you set it manually
  76967. */
  76968. get: function () {
  76969. return this._refTexture;
  76970. },
  76971. set: function (value) {
  76972. if (this._refTexture && this._ownRefractionTexture) {
  76973. this._refTexture.dispose();
  76974. }
  76975. this._refTexture = value;
  76976. this._ownRefractionTexture = false;
  76977. },
  76978. enumerable: true,
  76979. configurable: true
  76980. });
  76981. // Methods
  76982. RefractionPostProcess.prototype.dispose = function (camera) {
  76983. if (this._refTexture && this._ownRefractionTexture) {
  76984. this._refTexture.dispose();
  76985. this._refTexture = null;
  76986. }
  76987. _super.prototype.dispose.call(this, camera);
  76988. };
  76989. return RefractionPostProcess;
  76990. }(BABYLON.PostProcess));
  76991. BABYLON.RefractionPostProcess = RefractionPostProcess;
  76992. })(BABYLON || (BABYLON = {}));
  76993. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  76994. var BABYLON;
  76995. (function (BABYLON) {
  76996. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  76997. __extends(BlackAndWhitePostProcess, _super);
  76998. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  76999. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  77000. _this.degree = 1;
  77001. _this.onApplyObservable.add(function (effect) {
  77002. effect.setFloat("degree", _this.degree);
  77003. });
  77004. return _this;
  77005. }
  77006. return BlackAndWhitePostProcess;
  77007. }(BABYLON.PostProcess));
  77008. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  77009. })(BABYLON || (BABYLON = {}));
  77010. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  77011. var BABYLON;
  77012. (function (BABYLON) {
  77013. /**
  77014. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  77015. * input texture to perform effects such as edge detection or sharpening
  77016. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  77017. */
  77018. var ConvolutionPostProcess = /** @class */ (function (_super) {
  77019. __extends(ConvolutionPostProcess, _super);
  77020. /**
  77021. * Creates a new instance ConvolutionPostProcess
  77022. * @param name The name of the effect.
  77023. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  77024. * @param options The required width/height ratio to downsize to before computing the render pass.
  77025. * @param camera The camera to apply the render pass to.
  77026. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77027. * @param engine The engine which the post process will be applied. (default: current engine)
  77028. * @param reusable If the post process can be reused on the same frame. (default: false)
  77029. * @param textureType Type of textures used when performing the post process. (default: 0)
  77030. */
  77031. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  77032. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77033. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77034. _this.kernel = kernel;
  77035. _this.onApply = function (effect) {
  77036. effect.setFloat2("screenSize", _this.width, _this.height);
  77037. effect.setArray("kernel", _this.kernel);
  77038. };
  77039. return _this;
  77040. }
  77041. // Statics
  77042. /**
  77043. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77044. */
  77045. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  77046. /**
  77047. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77048. */
  77049. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  77050. /**
  77051. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77052. */
  77053. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  77054. /**
  77055. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77056. */
  77057. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  77058. /**
  77059. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77060. */
  77061. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  77062. /**
  77063. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77064. */
  77065. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  77066. return ConvolutionPostProcess;
  77067. }(BABYLON.PostProcess));
  77068. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  77069. })(BABYLON || (BABYLON = {}));
  77070. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  77071. var BABYLON;
  77072. (function (BABYLON) {
  77073. var FilterPostProcess = /** @class */ (function (_super) {
  77074. __extends(FilterPostProcess, _super);
  77075. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  77076. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  77077. _this.kernelMatrix = kernelMatrix;
  77078. _this.onApply = function (effect) {
  77079. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  77080. };
  77081. return _this;
  77082. }
  77083. return FilterPostProcess;
  77084. }(BABYLON.PostProcess));
  77085. BABYLON.FilterPostProcess = FilterPostProcess;
  77086. })(BABYLON || (BABYLON = {}));
  77087. //# sourceMappingURL=babylon.filterPostProcess.js.map
  77088. var BABYLON;
  77089. (function (BABYLON) {
  77090. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  77091. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  77092. __extends(VolumetricLightScatteringPostProcess, _super);
  77093. /**
  77094. * @constructor
  77095. * @param {string} name - The post-process name
  77096. * @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)
  77097. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  77098. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  77099. * @param {number} samples - The post-process quality, default 100
  77100. * @param {number} samplingMode - The post-process filtering mode
  77101. * @param {BABYLON.Engine} engine - The babylon engine
  77102. * @param {boolean} reusable - If the post-process is reusable
  77103. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  77104. */
  77105. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  77106. if (samples === void 0) { samples = 100; }
  77107. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77108. var _this = _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples) || this;
  77109. _this._screenCoordinates = BABYLON.Vector2.Zero();
  77110. /**
  77111. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  77112. */
  77113. _this.customMeshPosition = BABYLON.Vector3.Zero();
  77114. /**
  77115. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  77116. */
  77117. _this.useCustomMeshPosition = false;
  77118. /**
  77119. * If the post-process should inverse the light scattering direction
  77120. */
  77121. _this.invert = true;
  77122. /**
  77123. * Array containing the excluded meshes not rendered in the internal pass
  77124. */
  77125. _this.excludedMeshes = new Array();
  77126. /**
  77127. * Controls the overall intensity of the post-process
  77128. */
  77129. _this.exposure = 0.3;
  77130. /**
  77131. * Dissipates each sample's contribution in range [0, 1]
  77132. */
  77133. _this.decay = 0.96815;
  77134. /**
  77135. * Controls the overall intensity of each sample
  77136. */
  77137. _this.weight = 0.58767;
  77138. /**
  77139. * Controls the density of each sample
  77140. */
  77141. _this.density = 0.926;
  77142. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  77143. engine = scene.getEngine();
  77144. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  77145. // Configure mesh
  77146. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  77147. // Configure
  77148. _this._createPass(scene, ratio.passRatio || ratio);
  77149. _this.onActivate = function (camera) {
  77150. if (!_this.isSupported) {
  77151. _this.dispose(camera);
  77152. }
  77153. _this.onActivate = null;
  77154. };
  77155. _this.onApplyObservable.add(function (effect) {
  77156. _this._updateMeshScreenCoordinates(scene);
  77157. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  77158. effect.setFloat("exposure", _this.exposure);
  77159. effect.setFloat("decay", _this.decay);
  77160. effect.setFloat("weight", _this.weight);
  77161. effect.setFloat("density", _this.density);
  77162. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  77163. });
  77164. return _this;
  77165. }
  77166. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  77167. get: function () {
  77168. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77169. return false;
  77170. },
  77171. set: function (useDiffuseColor) {
  77172. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77173. },
  77174. enumerable: true,
  77175. configurable: true
  77176. });
  77177. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  77178. return "VolumetricLightScatteringPostProcess";
  77179. };
  77180. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  77181. var mesh = subMesh.getMesh();
  77182. // Render this.mesh as default
  77183. if (mesh === this.mesh && mesh.material) {
  77184. return mesh.material.isReady(mesh);
  77185. }
  77186. var defines = [];
  77187. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77188. var material = subMesh.getMaterial();
  77189. // Alpha test
  77190. if (material) {
  77191. if (material.needAlphaTesting()) {
  77192. defines.push("#define ALPHATEST");
  77193. }
  77194. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77195. attribs.push(BABYLON.VertexBuffer.UVKind);
  77196. defines.push("#define UV1");
  77197. }
  77198. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77199. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77200. defines.push("#define UV2");
  77201. }
  77202. }
  77203. // Bones
  77204. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77205. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77206. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77207. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77208. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  77209. }
  77210. else {
  77211. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77212. }
  77213. // Instances
  77214. if (useInstances) {
  77215. defines.push("#define INSTANCES");
  77216. attribs.push("world0");
  77217. attribs.push("world1");
  77218. attribs.push("world2");
  77219. attribs.push("world3");
  77220. }
  77221. // Get correct effect
  77222. var join = defines.join("\n");
  77223. if (this._cachedDefines !== join) {
  77224. this._cachedDefines = join;
  77225. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  77226. }
  77227. return this._volumetricLightScatteringPass.isReady();
  77228. };
  77229. /**
  77230. * Sets the new light position for light scattering effect
  77231. * @param {BABYLON.Vector3} The new custom light position
  77232. */
  77233. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  77234. this.customMeshPosition = position;
  77235. };
  77236. /**
  77237. * Returns the light position for light scattering effect
  77238. * @return {BABYLON.Vector3} The custom light position
  77239. */
  77240. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  77241. return this.customMeshPosition;
  77242. };
  77243. /**
  77244. * Disposes the internal assets and detaches the post-process from the camera
  77245. */
  77246. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  77247. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  77248. if (rttIndex !== -1) {
  77249. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  77250. }
  77251. this._volumetricLightScatteringRTT.dispose();
  77252. _super.prototype.dispose.call(this, camera);
  77253. };
  77254. /**
  77255. * Returns the render target texture used by the post-process
  77256. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  77257. */
  77258. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  77259. return this._volumetricLightScatteringRTT;
  77260. };
  77261. // Private methods
  77262. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  77263. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  77264. return true;
  77265. }
  77266. return false;
  77267. };
  77268. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  77269. var _this = this;
  77270. var engine = scene.getEngine();
  77271. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  77272. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77273. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77274. this._volumetricLightScatteringRTT.renderList = null;
  77275. this._volumetricLightScatteringRTT.renderParticles = false;
  77276. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  77277. var camera = this.getCamera();
  77278. if (camera) {
  77279. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77280. }
  77281. else {
  77282. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77283. }
  77284. // Custom render function for submeshes
  77285. var renderSubMesh = function (subMesh) {
  77286. var mesh = subMesh.getRenderingMesh();
  77287. if (_this._meshExcluded(mesh)) {
  77288. return;
  77289. }
  77290. var material = subMesh.getMaterial();
  77291. if (!material) {
  77292. return;
  77293. }
  77294. var scene = mesh.getScene();
  77295. var engine = scene.getEngine();
  77296. // Culling
  77297. engine.setState(material.backFaceCulling);
  77298. // Managing instances
  77299. var batch = mesh._getInstancesRenderList(subMesh._id);
  77300. if (batch.mustReturn) {
  77301. return;
  77302. }
  77303. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77304. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  77305. var effect = _this._volumetricLightScatteringPass;
  77306. if (mesh === _this.mesh) {
  77307. if (subMesh.effect) {
  77308. effect = subMesh.effect;
  77309. }
  77310. else {
  77311. effect = material.getEffect();
  77312. }
  77313. }
  77314. engine.enableEffect(effect);
  77315. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  77316. if (mesh === _this.mesh) {
  77317. material.bind(mesh.getWorldMatrix(), mesh);
  77318. }
  77319. else {
  77320. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  77321. // Alpha test
  77322. if (material && material.needAlphaTesting()) {
  77323. var alphaTexture = material.getAlphaTestTexture();
  77324. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  77325. if (alphaTexture) {
  77326. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77327. }
  77328. }
  77329. // Bones
  77330. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77331. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77332. }
  77333. }
  77334. // Draw
  77335. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  77336. }
  77337. };
  77338. // Render target texture callbacks
  77339. var savedSceneClearColor;
  77340. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  77341. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  77342. savedSceneClearColor = scene.clearColor;
  77343. scene.clearColor = sceneClearColor;
  77344. });
  77345. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  77346. scene.clearColor = savedSceneClearColor;
  77347. });
  77348. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77349. var engine = scene.getEngine();
  77350. var index;
  77351. if (depthOnlySubMeshes.length) {
  77352. engine.setColorWrite(false);
  77353. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77354. renderSubMesh(depthOnlySubMeshes.data[index]);
  77355. }
  77356. engine.setColorWrite(true);
  77357. }
  77358. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77359. renderSubMesh(opaqueSubMeshes.data[index]);
  77360. }
  77361. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77362. renderSubMesh(alphaTestSubMeshes.data[index]);
  77363. }
  77364. if (transparentSubMeshes.length) {
  77365. // Sort sub meshes
  77366. for (index = 0; index < transparentSubMeshes.length; index++) {
  77367. var submesh = transparentSubMeshes.data[index];
  77368. var boundingInfo = submesh.getBoundingInfo();
  77369. if (boundingInfo && scene.activeCamera) {
  77370. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  77371. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  77372. }
  77373. }
  77374. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  77375. sortedArray.sort(function (a, b) {
  77376. // Alpha index first
  77377. if (a._alphaIndex > b._alphaIndex) {
  77378. return 1;
  77379. }
  77380. if (a._alphaIndex < b._alphaIndex) {
  77381. return -1;
  77382. }
  77383. // Then distance to camera
  77384. if (a._distanceToCamera < b._distanceToCamera) {
  77385. return 1;
  77386. }
  77387. if (a._distanceToCamera > b._distanceToCamera) {
  77388. return -1;
  77389. }
  77390. return 0;
  77391. });
  77392. // Render sub meshes
  77393. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  77394. for (index = 0; index < sortedArray.length; index++) {
  77395. renderSubMesh(sortedArray[index]);
  77396. }
  77397. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77398. }
  77399. };
  77400. };
  77401. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  77402. var transform = scene.getTransformMatrix();
  77403. var meshPosition;
  77404. if (this.useCustomMeshPosition) {
  77405. meshPosition = this.customMeshPosition;
  77406. }
  77407. else if (this.attachedNode) {
  77408. meshPosition = this.attachedNode.position;
  77409. }
  77410. else {
  77411. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  77412. }
  77413. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  77414. this._screenCoordinates.x = pos.x / this._viewPort.width;
  77415. this._screenCoordinates.y = pos.y / this._viewPort.height;
  77416. if (this.invert)
  77417. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  77418. };
  77419. // Static methods
  77420. /**
  77421. * Creates a default mesh for the Volumeric Light Scattering post-process
  77422. * @param {string} The mesh name
  77423. * @param {BABYLON.Scene} The scene where to create the mesh
  77424. * @return {BABYLON.Mesh} the default mesh
  77425. */
  77426. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  77427. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  77428. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  77429. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  77430. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  77431. mesh.material = material;
  77432. return mesh;
  77433. };
  77434. __decorate([
  77435. BABYLON.serializeAsVector3()
  77436. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  77437. __decorate([
  77438. BABYLON.serialize()
  77439. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  77440. __decorate([
  77441. BABYLON.serialize()
  77442. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  77443. __decorate([
  77444. BABYLON.serializeAsMeshReference()
  77445. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  77446. __decorate([
  77447. BABYLON.serialize()
  77448. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  77449. __decorate([
  77450. BABYLON.serialize()
  77451. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  77452. __decorate([
  77453. BABYLON.serialize()
  77454. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  77455. __decorate([
  77456. BABYLON.serialize()
  77457. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  77458. __decorate([
  77459. BABYLON.serialize()
  77460. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  77461. return VolumetricLightScatteringPostProcess;
  77462. }(BABYLON.PostProcess));
  77463. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  77464. })(BABYLON || (BABYLON = {}));
  77465. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  77466. //
  77467. // This post-process allows the modification of rendered colors by using
  77468. // a 'look-up table' (LUT). This effect is also called Color Grading.
  77469. //
  77470. // The object needs to be provided an url to a texture containing the color
  77471. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  77472. // Use an image editing software to tweak the LUT to match your needs.
  77473. //
  77474. // For an example of a color LUT, see here:
  77475. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  77476. // For explanations on color grading, see here:
  77477. // http://udn.epicgames.com/Three/ColorGrading.html
  77478. //
  77479. var BABYLON;
  77480. (function (BABYLON) {
  77481. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  77482. __extends(ColorCorrectionPostProcess, _super);
  77483. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  77484. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  77485. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77486. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  77487. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77488. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77489. _this.onApply = function (effect) {
  77490. effect.setTexture("colorTable", _this._colorTableTexture);
  77491. };
  77492. return _this;
  77493. }
  77494. return ColorCorrectionPostProcess;
  77495. }(BABYLON.PostProcess));
  77496. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  77497. })(BABYLON || (BABYLON = {}));
  77498. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  77499. var BABYLON;
  77500. (function (BABYLON) {
  77501. /** Defines operator used for tonemapping */
  77502. var TonemappingOperator;
  77503. (function (TonemappingOperator) {
  77504. /** Hable */
  77505. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  77506. /** Reinhard */
  77507. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  77508. /** HejiDawson */
  77509. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  77510. /** Photographic */
  77511. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  77512. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  77513. ;
  77514. /**
  77515. * Defines a post process to apply tone mapping
  77516. */
  77517. var TonemapPostProcess = /** @class */ (function (_super) {
  77518. __extends(TonemapPostProcess, _super);
  77519. /**
  77520. * Creates a new TonemapPostProcess
  77521. * @param name defines the name of the postprocess
  77522. * @param _operator defines the operator to use
  77523. * @param exposureAdjustment defines the required exposure adjustement
  77524. * @param camera defines the camera to use (can be null)
  77525. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  77526. * @param engine defines the hosting engine (can be ignore if camera is set)
  77527. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  77528. */
  77529. function TonemapPostProcess(name, _operator,
  77530. /** Defines the required exposure adjustement */
  77531. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  77532. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77533. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77534. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  77535. _this._operator = _operator;
  77536. _this.exposureAdjustment = exposureAdjustment;
  77537. var defines = "#define ";
  77538. if (_this._operator === TonemappingOperator.Hable)
  77539. defines += "HABLE_TONEMAPPING";
  77540. else if (_this._operator === TonemappingOperator.Reinhard)
  77541. defines += "REINHARD_TONEMAPPING";
  77542. else if (_this._operator === TonemappingOperator.HejiDawson)
  77543. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  77544. else if (_this._operator === TonemappingOperator.Photographic)
  77545. defines += "PHOTOGRAPHIC_TONEMAPPING";
  77546. //sadly a second call to create the effect.
  77547. _this.updateEffect(defines);
  77548. _this.onApply = function (effect) {
  77549. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  77550. };
  77551. return _this;
  77552. }
  77553. return TonemapPostProcess;
  77554. }(BABYLON.PostProcess));
  77555. BABYLON.TonemapPostProcess = TonemapPostProcess;
  77556. })(BABYLON || (BABYLON = {}));
  77557. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  77558. var BABYLON;
  77559. (function (BABYLON) {
  77560. var DisplayPassPostProcess = /** @class */ (function (_super) {
  77561. __extends(DisplayPassPostProcess, _super);
  77562. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  77563. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  77564. }
  77565. return DisplayPassPostProcess;
  77566. }(BABYLON.PostProcess));
  77567. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  77568. })(BABYLON || (BABYLON = {}));
  77569. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  77570. var BABYLON;
  77571. (function (BABYLON) {
  77572. var HighlightsPostProcess = /** @class */ (function (_super) {
  77573. __extends(HighlightsPostProcess, _super);
  77574. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77575. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77576. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77577. }
  77578. return HighlightsPostProcess;
  77579. }(BABYLON.PostProcess));
  77580. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  77581. })(BABYLON || (BABYLON = {}));
  77582. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  77583. var BABYLON;
  77584. (function (BABYLON) {
  77585. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  77586. __extends(ImageProcessingPostProcess, _super);
  77587. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  77588. if (camera === void 0) { camera = null; }
  77589. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77590. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  77591. _this._fromLinearSpace = true;
  77592. /**
  77593. * Defines cache preventing GC.
  77594. */
  77595. _this._defines = {
  77596. IMAGEPROCESSING: false,
  77597. VIGNETTE: false,
  77598. VIGNETTEBLENDMODEMULTIPLY: false,
  77599. VIGNETTEBLENDMODEOPAQUE: false,
  77600. TONEMAPPING: false,
  77601. CONTRAST: false,
  77602. COLORCURVES: false,
  77603. COLORGRADING: false,
  77604. COLORGRADING3D: false,
  77605. FROMLINEARSPACE: false,
  77606. SAMPLER3DGREENDEPTH: false,
  77607. SAMPLER3DBGRMAP: false,
  77608. IMAGEPROCESSINGPOSTPROCESS: false,
  77609. EXPOSURE: false,
  77610. };
  77611. // Setup the configuration as forced by the constructor. This would then not force the
  77612. // scene materials output in linear space and let untouched the default forward pass.
  77613. if (imageProcessingConfiguration) {
  77614. imageProcessingConfiguration.applyByPostProcess = true;
  77615. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  77616. // This will cause the shader to be compiled
  77617. _this.fromLinearSpace = false;
  77618. }
  77619. // Setup the default processing configuration to the scene.
  77620. else {
  77621. _this._attachImageProcessingConfiguration(null, true);
  77622. _this.imageProcessingConfiguration.applyByPostProcess = true;
  77623. }
  77624. _this.onApply = function (effect) {
  77625. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  77626. };
  77627. return _this;
  77628. }
  77629. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  77630. /**
  77631. * Gets the image processing configuration used either in this material.
  77632. */
  77633. get: function () {
  77634. return this._imageProcessingConfiguration;
  77635. },
  77636. /**
  77637. * Sets the Default image processing configuration used either in the this material.
  77638. *
  77639. * If sets to null, the scene one is in use.
  77640. */
  77641. set: function (value) {
  77642. this._attachImageProcessingConfiguration(value);
  77643. },
  77644. enumerable: true,
  77645. configurable: true
  77646. });
  77647. /**
  77648. * Attaches a new image processing configuration to the PBR Material.
  77649. * @param configuration
  77650. */
  77651. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  77652. var _this = this;
  77653. if (doNotBuild === void 0) { doNotBuild = false; }
  77654. if (configuration === this._imageProcessingConfiguration) {
  77655. return;
  77656. }
  77657. // Detaches observer.
  77658. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77659. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77660. }
  77661. // Pick the scene configuration if needed.
  77662. if (!configuration) {
  77663. var scene = null;
  77664. var engine = this.getEngine();
  77665. var camera = this.getCamera();
  77666. if (camera) {
  77667. scene = camera.getScene();
  77668. }
  77669. else if (engine && engine.scenes) {
  77670. var scenes = engine.scenes;
  77671. scene = scenes[scenes.length - 1];
  77672. }
  77673. else {
  77674. scene = BABYLON.Engine.LastCreatedScene;
  77675. }
  77676. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  77677. }
  77678. else {
  77679. this._imageProcessingConfiguration = configuration;
  77680. }
  77681. // Attaches observer.
  77682. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77683. _this._updateParameters();
  77684. });
  77685. // Ensure the effect will be rebuilt.
  77686. if (!doNotBuild) {
  77687. this._updateParameters();
  77688. }
  77689. };
  77690. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  77691. /**
  77692. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77693. */
  77694. get: function () {
  77695. return this.imageProcessingConfiguration.colorCurves;
  77696. },
  77697. /**
  77698. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77699. */
  77700. set: function (value) {
  77701. this.imageProcessingConfiguration.colorCurves = value;
  77702. },
  77703. enumerable: true,
  77704. configurable: true
  77705. });
  77706. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  77707. /**
  77708. * Gets wether the color curves effect is enabled.
  77709. */
  77710. get: function () {
  77711. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77712. },
  77713. /**
  77714. * Sets wether the color curves effect is enabled.
  77715. */
  77716. set: function (value) {
  77717. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  77718. },
  77719. enumerable: true,
  77720. configurable: true
  77721. });
  77722. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  77723. /**
  77724. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77725. */
  77726. get: function () {
  77727. return this.imageProcessingConfiguration.colorGradingTexture;
  77728. },
  77729. /**
  77730. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77731. */
  77732. set: function (value) {
  77733. this.imageProcessingConfiguration.colorGradingTexture = value;
  77734. },
  77735. enumerable: true,
  77736. configurable: true
  77737. });
  77738. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  77739. /**
  77740. * Gets wether the color grading effect is enabled.
  77741. */
  77742. get: function () {
  77743. return this.imageProcessingConfiguration.colorGradingEnabled;
  77744. },
  77745. /**
  77746. * Gets wether the color grading effect is enabled.
  77747. */
  77748. set: function (value) {
  77749. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77750. },
  77751. enumerable: true,
  77752. configurable: true
  77753. });
  77754. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  77755. /**
  77756. * Gets exposure used in the effect.
  77757. */
  77758. get: function () {
  77759. return this.imageProcessingConfiguration.exposure;
  77760. },
  77761. /**
  77762. * Sets exposure used in the effect.
  77763. */
  77764. set: function (value) {
  77765. this.imageProcessingConfiguration.exposure = value;
  77766. },
  77767. enumerable: true,
  77768. configurable: true
  77769. });
  77770. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  77771. /**
  77772. * Gets wether tonemapping is enabled or not.
  77773. */
  77774. get: function () {
  77775. return this._imageProcessingConfiguration.toneMappingEnabled;
  77776. },
  77777. /**
  77778. * Sets wether tonemapping is enabled or not
  77779. */
  77780. set: function (value) {
  77781. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77782. },
  77783. enumerable: true,
  77784. configurable: true
  77785. });
  77786. ;
  77787. ;
  77788. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  77789. /**
  77790. * Gets contrast used in the effect.
  77791. */
  77792. get: function () {
  77793. return this.imageProcessingConfiguration.contrast;
  77794. },
  77795. /**
  77796. * Sets contrast used in the effect.
  77797. */
  77798. set: function (value) {
  77799. this.imageProcessingConfiguration.contrast = value;
  77800. },
  77801. enumerable: true,
  77802. configurable: true
  77803. });
  77804. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  77805. /**
  77806. * Gets Vignette stretch size.
  77807. */
  77808. get: function () {
  77809. return this.imageProcessingConfiguration.vignetteStretch;
  77810. },
  77811. /**
  77812. * Sets Vignette stretch size.
  77813. */
  77814. set: function (value) {
  77815. this.imageProcessingConfiguration.vignetteStretch = value;
  77816. },
  77817. enumerable: true,
  77818. configurable: true
  77819. });
  77820. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  77821. /**
  77822. * Gets Vignette centre X Offset.
  77823. */
  77824. get: function () {
  77825. return this.imageProcessingConfiguration.vignetteCentreX;
  77826. },
  77827. /**
  77828. * Sets Vignette centre X Offset.
  77829. */
  77830. set: function (value) {
  77831. this.imageProcessingConfiguration.vignetteCentreX = value;
  77832. },
  77833. enumerable: true,
  77834. configurable: true
  77835. });
  77836. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  77837. /**
  77838. * Gets Vignette centre Y Offset.
  77839. */
  77840. get: function () {
  77841. return this.imageProcessingConfiguration.vignetteCentreY;
  77842. },
  77843. /**
  77844. * Sets Vignette centre Y Offset.
  77845. */
  77846. set: function (value) {
  77847. this.imageProcessingConfiguration.vignetteCentreY = value;
  77848. },
  77849. enumerable: true,
  77850. configurable: true
  77851. });
  77852. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  77853. /**
  77854. * Gets Vignette weight or intensity of the vignette effect.
  77855. */
  77856. get: function () {
  77857. return this.imageProcessingConfiguration.vignetteWeight;
  77858. },
  77859. /**
  77860. * Sets Vignette weight or intensity of the vignette effect.
  77861. */
  77862. set: function (value) {
  77863. this.imageProcessingConfiguration.vignetteWeight = value;
  77864. },
  77865. enumerable: true,
  77866. configurable: true
  77867. });
  77868. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  77869. /**
  77870. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77871. * if vignetteEnabled is set to true.
  77872. */
  77873. get: function () {
  77874. return this.imageProcessingConfiguration.vignetteColor;
  77875. },
  77876. /**
  77877. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77878. * if vignetteEnabled is set to true.
  77879. */
  77880. set: function (value) {
  77881. this.imageProcessingConfiguration.vignetteColor = value;
  77882. },
  77883. enumerable: true,
  77884. configurable: true
  77885. });
  77886. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  77887. /**
  77888. * Gets Camera field of view used by the Vignette effect.
  77889. */
  77890. get: function () {
  77891. return this.imageProcessingConfiguration.vignetteCameraFov;
  77892. },
  77893. /**
  77894. * Sets Camera field of view used by the Vignette effect.
  77895. */
  77896. set: function (value) {
  77897. this.imageProcessingConfiguration.vignetteCameraFov = value;
  77898. },
  77899. enumerable: true,
  77900. configurable: true
  77901. });
  77902. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  77903. /**
  77904. * Gets the vignette blend mode allowing different kind of effect.
  77905. */
  77906. get: function () {
  77907. return this.imageProcessingConfiguration.vignetteBlendMode;
  77908. },
  77909. /**
  77910. * Sets the vignette blend mode allowing different kind of effect.
  77911. */
  77912. set: function (value) {
  77913. this.imageProcessingConfiguration.vignetteBlendMode = value;
  77914. },
  77915. enumerable: true,
  77916. configurable: true
  77917. });
  77918. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  77919. /**
  77920. * Gets wether the vignette effect is enabled.
  77921. */
  77922. get: function () {
  77923. return this.imageProcessingConfiguration.vignetteEnabled;
  77924. },
  77925. /**
  77926. * Sets wether the vignette effect is enabled.
  77927. */
  77928. set: function (value) {
  77929. this.imageProcessingConfiguration.vignetteEnabled = value;
  77930. },
  77931. enumerable: true,
  77932. configurable: true
  77933. });
  77934. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  77935. /**
  77936. * Gets wether the input of the processing is in Gamma or Linear Space.
  77937. */
  77938. get: function () {
  77939. return this._fromLinearSpace;
  77940. },
  77941. /**
  77942. * Sets wether the input of the processing is in Gamma or Linear Space.
  77943. */
  77944. set: function (value) {
  77945. if (this._fromLinearSpace === value) {
  77946. return;
  77947. }
  77948. this._fromLinearSpace = value;
  77949. this._updateParameters();
  77950. },
  77951. enumerable: true,
  77952. configurable: true
  77953. });
  77954. ImageProcessingPostProcess.prototype.getClassName = function () {
  77955. return "ImageProcessingPostProcess";
  77956. };
  77957. ImageProcessingPostProcess.prototype._updateParameters = function () {
  77958. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  77959. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  77960. var defines = "";
  77961. for (var define in this._defines) {
  77962. if (this._defines[define]) {
  77963. defines += "#define " + define + ";\r\n";
  77964. }
  77965. }
  77966. var samplers = ["textureSampler"];
  77967. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  77968. var uniforms = ["scale"];
  77969. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  77970. this.updateEffect(defines, uniforms, samplers);
  77971. };
  77972. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  77973. _super.prototype.dispose.call(this, camera);
  77974. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77975. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77976. }
  77977. this.imageProcessingConfiguration.applyByPostProcess = false;
  77978. };
  77979. __decorate([
  77980. BABYLON.serialize()
  77981. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  77982. return ImageProcessingPostProcess;
  77983. }(BABYLON.PostProcess));
  77984. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  77985. })(BABYLON || (BABYLON = {}));
  77986. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  77987. var BABYLON;
  77988. (function (BABYLON) {
  77989. /**
  77990. * Class used to store bone information
  77991. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  77992. */
  77993. var Bone = /** @class */ (function (_super) {
  77994. __extends(Bone, _super);
  77995. /**
  77996. * Create a new bone
  77997. * @param name defines the bone name
  77998. * @param skeleton defines the parent skeleton
  77999. * @param parentBone defines the parent (can be null if the bone is the root)
  78000. * @param localMatrix defines the local matrix
  78001. * @param restPose defines the rest pose matrix
  78002. * @param baseMatrix defines the base matrix
  78003. * @param index defines index of the bone in the hiearchy
  78004. */
  78005. function Bone(
  78006. /**
  78007. * defines the bone name
  78008. */
  78009. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  78010. if (parentBone === void 0) { parentBone = null; }
  78011. if (localMatrix === void 0) { localMatrix = null; }
  78012. if (restPose === void 0) { restPose = null; }
  78013. if (baseMatrix === void 0) { baseMatrix = null; }
  78014. if (index === void 0) { index = null; }
  78015. var _this = _super.call(this, name, skeleton.getScene()) || this;
  78016. _this.name = name;
  78017. /**
  78018. * Gets the list of child bones
  78019. */
  78020. _this.children = new Array();
  78021. /** Gets the animations associated with this bone */
  78022. _this.animations = new Array();
  78023. /**
  78024. * @hidden Internal only
  78025. * Set this value to map this bone to a different index in the transform matrices
  78026. * Set this value to -1 to exclude the bone from the transform matrices
  78027. */
  78028. _this._index = null;
  78029. _this._absoluteTransform = new BABYLON.Matrix();
  78030. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  78031. _this._scalingDeterminant = 1;
  78032. _this._worldTransform = new BABYLON.Matrix();
  78033. _this._needToDecompose = true;
  78034. _this._needToCompose = false;
  78035. _this._skeleton = skeleton;
  78036. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  78037. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  78038. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  78039. _this._index = index;
  78040. skeleton.bones.push(_this);
  78041. _this.setParent(parentBone, false);
  78042. if (baseMatrix || localMatrix) {
  78043. _this._updateDifferenceMatrix();
  78044. }
  78045. return _this;
  78046. }
  78047. Object.defineProperty(Bone.prototype, "_matrix", {
  78048. /** @hidden */
  78049. get: function () {
  78050. this._compose();
  78051. return this._localMatrix;
  78052. },
  78053. /** @hidden */
  78054. set: function (value) {
  78055. this._localMatrix.copyFrom(value);
  78056. this._needToDecompose = true;
  78057. },
  78058. enumerable: true,
  78059. configurable: true
  78060. });
  78061. // Members
  78062. /**
  78063. * Gets the parent skeleton
  78064. * @returns a skeleton
  78065. */
  78066. Bone.prototype.getSkeleton = function () {
  78067. return this._skeleton;
  78068. };
  78069. /**
  78070. * Gets parent bone
  78071. * @returns a bone or null if the bone is the root of the bone hierarchy
  78072. */
  78073. Bone.prototype.getParent = function () {
  78074. return this._parent;
  78075. };
  78076. /**
  78077. * Sets the parent bone
  78078. * @param parent defines the parent (can be null if the bone is the root)
  78079. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78080. */
  78081. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  78082. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78083. if (this._parent === parent) {
  78084. return;
  78085. }
  78086. if (this._parent) {
  78087. var index = this._parent.children.indexOf(this);
  78088. if (index !== -1) {
  78089. this._parent.children.splice(index, 1);
  78090. }
  78091. }
  78092. this._parent = parent;
  78093. if (this._parent) {
  78094. this._parent.children.push(this);
  78095. }
  78096. if (updateDifferenceMatrix) {
  78097. this._updateDifferenceMatrix();
  78098. }
  78099. this.markAsDirty();
  78100. };
  78101. /**
  78102. * Gets the local matrix
  78103. * @returns a matrix
  78104. */
  78105. Bone.prototype.getLocalMatrix = function () {
  78106. this._compose();
  78107. return this._localMatrix;
  78108. };
  78109. /**
  78110. * Gets the base matrix (initial matrix which remains unchanged)
  78111. * @returns a matrix
  78112. */
  78113. Bone.prototype.getBaseMatrix = function () {
  78114. return this._baseMatrix;
  78115. };
  78116. /**
  78117. * Gets the rest pose matrix
  78118. * @returns a matrix
  78119. */
  78120. Bone.prototype.getRestPose = function () {
  78121. return this._restPose;
  78122. };
  78123. /**
  78124. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  78125. */
  78126. Bone.prototype.getWorldMatrix = function () {
  78127. return this._worldTransform;
  78128. };
  78129. /**
  78130. * Sets the local matrix to rest pose matrix
  78131. */
  78132. Bone.prototype.returnToRest = function () {
  78133. this.updateMatrix(this._restPose.clone());
  78134. };
  78135. /**
  78136. * Gets the inverse of the absolute transform matrix.
  78137. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  78138. * @returns a matrix
  78139. */
  78140. Bone.prototype.getInvertedAbsoluteTransform = function () {
  78141. return this._invertedAbsoluteTransform;
  78142. };
  78143. /**
  78144. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  78145. * @returns a matrix
  78146. */
  78147. Bone.prototype.getAbsoluteTransform = function () {
  78148. return this._absoluteTransform;
  78149. };
  78150. Object.defineProperty(Bone.prototype, "position", {
  78151. // Properties (matches AbstractMesh properties)
  78152. /** Gets or sets current position (in local space) */
  78153. get: function () {
  78154. this._decompose();
  78155. return this._localPosition;
  78156. },
  78157. set: function (newPosition) {
  78158. this._decompose();
  78159. this._localPosition.copyFrom(newPosition);
  78160. this._markAsDirtyAndCompose();
  78161. },
  78162. enumerable: true,
  78163. configurable: true
  78164. });
  78165. Object.defineProperty(Bone.prototype, "rotation", {
  78166. /** Gets or sets current rotation (in local space) */
  78167. get: function () {
  78168. return this.getRotation();
  78169. },
  78170. set: function (newRotation) {
  78171. this.setRotation(newRotation);
  78172. },
  78173. enumerable: true,
  78174. configurable: true
  78175. });
  78176. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  78177. /** Gets or sets current rotation quaternion (in local space) */
  78178. get: function () {
  78179. this._decompose();
  78180. return this._localRotation;
  78181. },
  78182. set: function (newRotation) {
  78183. this.setRotationQuaternion(newRotation);
  78184. },
  78185. enumerable: true,
  78186. configurable: true
  78187. });
  78188. Object.defineProperty(Bone.prototype, "scaling", {
  78189. /** Gets or sets current scaling (in local space) */
  78190. get: function () {
  78191. return this.getScale();
  78192. },
  78193. set: function (newScaling) {
  78194. this.setScale(newScaling);
  78195. },
  78196. enumerable: true,
  78197. configurable: true
  78198. });
  78199. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  78200. /**
  78201. * Gets the animation properties override
  78202. */
  78203. get: function () {
  78204. return this._skeleton.animationPropertiesOverride;
  78205. },
  78206. enumerable: true,
  78207. configurable: true
  78208. });
  78209. // Methods
  78210. Bone.prototype._decompose = function () {
  78211. if (!this._needToDecompose) {
  78212. return;
  78213. }
  78214. this._needToDecompose = false;
  78215. if (!this._localScaling) {
  78216. this._localScaling = BABYLON.Vector3.Zero();
  78217. this._localRotation = BABYLON.Quaternion.Zero();
  78218. this._localPosition = BABYLON.Vector3.Zero();
  78219. }
  78220. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  78221. };
  78222. Bone.prototype._compose = function () {
  78223. if (!this._needToCompose) {
  78224. return;
  78225. }
  78226. this._needToCompose = false;
  78227. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  78228. };
  78229. /**
  78230. * Update the base and local matrices
  78231. * @param matrix defines the new base or local matrix
  78232. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78233. * @param updateLocalMatrix defines if the local matrix should be updated
  78234. */
  78235. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  78236. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78237. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  78238. this._baseMatrix.copyFrom(matrix);
  78239. if (updateDifferenceMatrix) {
  78240. this._updateDifferenceMatrix();
  78241. }
  78242. if (updateLocalMatrix) {
  78243. this._localMatrix.copyFrom(matrix);
  78244. this._markAsDirtyAndDecompose();
  78245. }
  78246. else {
  78247. this.markAsDirty();
  78248. }
  78249. };
  78250. /** @hidden */
  78251. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  78252. if (updateChildren === void 0) { updateChildren = true; }
  78253. if (!rootMatrix) {
  78254. rootMatrix = this._baseMatrix;
  78255. }
  78256. if (this._parent) {
  78257. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78258. }
  78259. else {
  78260. this._absoluteTransform.copyFrom(rootMatrix);
  78261. }
  78262. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  78263. if (updateChildren) {
  78264. for (var index = 0; index < this.children.length; index++) {
  78265. this.children[index]._updateDifferenceMatrix();
  78266. }
  78267. }
  78268. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  78269. };
  78270. /**
  78271. * Flag the bone as dirty (Forcing it to update everything)
  78272. */
  78273. Bone.prototype.markAsDirty = function () {
  78274. this._currentRenderId++;
  78275. this._childRenderId++;
  78276. this._skeleton._markAsDirty();
  78277. };
  78278. Bone.prototype._markAsDirtyAndCompose = function () {
  78279. this.markAsDirty();
  78280. this._needToCompose = true;
  78281. };
  78282. Bone.prototype._markAsDirtyAndDecompose = function () {
  78283. this.markAsDirty();
  78284. this._needToDecompose = true;
  78285. };
  78286. /**
  78287. * Copy an animation range from another bone
  78288. * @param source defines the source bone
  78289. * @param rangeName defines the range name to copy
  78290. * @param frameOffset defines the frame offset
  78291. * @param rescaleAsRequired defines if rescaling must be applied if required
  78292. * @param skelDimensionsRatio defines the scaling ratio
  78293. * @returns true if operation was successful
  78294. */
  78295. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  78296. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  78297. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  78298. // all animation may be coming from a library skeleton, so may need to create animation
  78299. if (this.animations.length === 0) {
  78300. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  78301. this.animations[0].setKeys([]);
  78302. }
  78303. // get animation info / verify there is such a range from the source bone
  78304. var sourceRange = source.animations[0].getRange(rangeName);
  78305. if (!sourceRange) {
  78306. return false;
  78307. }
  78308. var from = sourceRange.from;
  78309. var to = sourceRange.to;
  78310. var sourceKeys = source.animations[0].getKeys();
  78311. // rescaling prep
  78312. var sourceBoneLength = source.length;
  78313. var sourceParent = source.getParent();
  78314. var parent = this.getParent();
  78315. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  78316. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  78317. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  78318. var destKeys = this.animations[0].getKeys();
  78319. // loop vars declaration
  78320. var orig;
  78321. var origTranslation;
  78322. var mat;
  78323. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  78324. orig = sourceKeys[key];
  78325. if (orig.frame >= from && orig.frame <= to) {
  78326. if (rescaleAsRequired) {
  78327. mat = orig.value.clone();
  78328. // scale based on parent ratio, when bone has parent
  78329. if (parentScalingReqd) {
  78330. origTranslation = mat.getTranslation();
  78331. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  78332. // scale based on skeleton dimension ratio when root bone, and value is passed
  78333. }
  78334. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  78335. origTranslation = mat.getTranslation();
  78336. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  78337. // use original when root bone, and no data for skelDimensionsRatio
  78338. }
  78339. else {
  78340. mat = orig.value;
  78341. }
  78342. }
  78343. else {
  78344. mat = orig.value;
  78345. }
  78346. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  78347. }
  78348. }
  78349. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  78350. return true;
  78351. };
  78352. /**
  78353. * Translate the bone in local or world space
  78354. * @param vec The amount to translate the bone
  78355. * @param space The space that the translation is in
  78356. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78357. */
  78358. Bone.prototype.translate = function (vec, space, mesh) {
  78359. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78360. var lm = this.getLocalMatrix();
  78361. if (space == BABYLON.Space.LOCAL) {
  78362. lm.m[12] += vec.x;
  78363. lm.m[13] += vec.y;
  78364. lm.m[14] += vec.z;
  78365. }
  78366. else {
  78367. var wm = null;
  78368. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78369. if (mesh) {
  78370. wm = mesh.getWorldMatrix();
  78371. }
  78372. this._skeleton.computeAbsoluteTransforms();
  78373. var tmat = Bone._tmpMats[0];
  78374. var tvec = Bone._tmpVecs[0];
  78375. if (this._parent) {
  78376. if (mesh && wm) {
  78377. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78378. tmat.multiplyToRef(wm, tmat);
  78379. }
  78380. else {
  78381. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78382. }
  78383. }
  78384. tmat.m[12] = 0;
  78385. tmat.m[13] = 0;
  78386. tmat.m[14] = 0;
  78387. tmat.invert();
  78388. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  78389. lm.m[12] += tvec.x;
  78390. lm.m[13] += tvec.y;
  78391. lm.m[14] += tvec.z;
  78392. }
  78393. this._markAsDirtyAndDecompose();
  78394. };
  78395. /**
  78396. * Set the postion of the bone in local or world space
  78397. * @param position The position to set the bone
  78398. * @param space The space that the position is in
  78399. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78400. */
  78401. Bone.prototype.setPosition = function (position, space, mesh) {
  78402. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78403. var lm = this.getLocalMatrix();
  78404. if (space == BABYLON.Space.LOCAL) {
  78405. lm.m[12] = position.x;
  78406. lm.m[13] = position.y;
  78407. lm.m[14] = position.z;
  78408. }
  78409. else {
  78410. var wm = null;
  78411. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78412. if (mesh) {
  78413. wm = mesh.getWorldMatrix();
  78414. }
  78415. this._skeleton.computeAbsoluteTransforms();
  78416. var tmat = Bone._tmpMats[0];
  78417. var vec = Bone._tmpVecs[0];
  78418. if (this._parent) {
  78419. if (mesh && wm) {
  78420. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78421. tmat.multiplyToRef(wm, tmat);
  78422. }
  78423. else {
  78424. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78425. }
  78426. }
  78427. tmat.invert();
  78428. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  78429. lm.m[12] = vec.x;
  78430. lm.m[13] = vec.y;
  78431. lm.m[14] = vec.z;
  78432. }
  78433. this._markAsDirtyAndDecompose();
  78434. };
  78435. /**
  78436. * Set the absolute position of the bone (world space)
  78437. * @param position The position to set the bone
  78438. * @param mesh The mesh that this bone is attached to
  78439. */
  78440. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  78441. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  78442. };
  78443. /**
  78444. * Scale the bone on the x, y and z axes (in local space)
  78445. * @param x The amount to scale the bone on the x axis
  78446. * @param y The amount to scale the bone on the y axis
  78447. * @param z The amount to scale the bone on the z axis
  78448. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  78449. */
  78450. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  78451. if (scaleChildren === void 0) { scaleChildren = false; }
  78452. var locMat = this.getLocalMatrix();
  78453. // Apply new scaling on top of current local matrix
  78454. var scaleMat = Bone._tmpMats[0];
  78455. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  78456. scaleMat.multiplyToRef(locMat, locMat);
  78457. // Invert scaling matrix and apply the inverse to all children
  78458. scaleMat.invert();
  78459. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  78460. var child = _a[_i];
  78461. var cm = child.getLocalMatrix();
  78462. cm.multiplyToRef(scaleMat, cm);
  78463. cm.m[12] *= x;
  78464. cm.m[13] *= y;
  78465. cm.m[14] *= z;
  78466. child._markAsDirtyAndDecompose();
  78467. }
  78468. this._markAsDirtyAndDecompose();
  78469. if (scaleChildren) {
  78470. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  78471. var child = _c[_b];
  78472. child.scale(x, y, z, scaleChildren);
  78473. }
  78474. }
  78475. };
  78476. /**
  78477. * Set the bone scaling in local space
  78478. * @param scale defines the scaling vector
  78479. */
  78480. Bone.prototype.setScale = function (scale) {
  78481. this._decompose();
  78482. this._localScaling.copyFrom(scale);
  78483. this._markAsDirtyAndCompose();
  78484. };
  78485. /**
  78486. * Gets the current scaling in local space
  78487. * @returns the current scaling vector
  78488. */
  78489. Bone.prototype.getScale = function () {
  78490. this._decompose();
  78491. return this._localScaling;
  78492. };
  78493. /**
  78494. * Gets the current scaling in local space and stores it in a target vector
  78495. * @param result defines the target vector
  78496. */
  78497. Bone.prototype.getScaleToRef = function (result) {
  78498. this._decompose();
  78499. result.copyFrom(this._localScaling);
  78500. };
  78501. /**
  78502. * Set the yaw, pitch, and roll of the bone in local or world space
  78503. * @param yaw The rotation of the bone on the y axis
  78504. * @param pitch The rotation of the bone on the x axis
  78505. * @param roll The rotation of the bone on the z axis
  78506. * @param space The space that the axes of rotation are in
  78507. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78508. */
  78509. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  78510. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78511. if (space === BABYLON.Space.LOCAL) {
  78512. var quat = Bone._tmpQuat;
  78513. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  78514. this.setRotationQuaternion(quat, space, mesh);
  78515. return;
  78516. }
  78517. var rotMatInv = Bone._tmpMats[0];
  78518. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78519. return;
  78520. }
  78521. var rotMat = Bone._tmpMats[1];
  78522. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  78523. rotMatInv.multiplyToRef(rotMat, rotMat);
  78524. this._rotateWithMatrix(rotMat, space, mesh);
  78525. };
  78526. /**
  78527. * Add a rotation to the bone on an axis in local or world space
  78528. * @param axis The axis to rotate the bone on
  78529. * @param amount The amount to rotate the bone
  78530. * @param space The space that the axis is in
  78531. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78532. */
  78533. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  78534. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78535. var rmat = Bone._tmpMats[0];
  78536. rmat.m[12] = 0;
  78537. rmat.m[13] = 0;
  78538. rmat.m[14] = 0;
  78539. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  78540. this._rotateWithMatrix(rmat, space, mesh);
  78541. };
  78542. /**
  78543. * Set the rotation of the bone to a particular axis angle in local or world space
  78544. * @param axis The axis to rotate the bone on
  78545. * @param angle The angle that the bone should be rotated to
  78546. * @param space The space that the axis is in
  78547. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78548. */
  78549. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  78550. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78551. if (space === BABYLON.Space.LOCAL) {
  78552. var quat = Bone._tmpQuat;
  78553. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  78554. this.setRotationQuaternion(quat, space, mesh);
  78555. return;
  78556. }
  78557. var rotMatInv = Bone._tmpMats[0];
  78558. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78559. return;
  78560. }
  78561. var rotMat = Bone._tmpMats[1];
  78562. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  78563. rotMatInv.multiplyToRef(rotMat, rotMat);
  78564. this._rotateWithMatrix(rotMat, space, mesh);
  78565. };
  78566. /**
  78567. * Set the euler rotation of the bone in local of world space
  78568. * @param rotation The euler rotation that the bone should be set to
  78569. * @param space The space that the rotation is in
  78570. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78571. */
  78572. Bone.prototype.setRotation = function (rotation, space, mesh) {
  78573. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78574. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  78575. };
  78576. /**
  78577. * Set the quaternion rotation of the bone in local of world space
  78578. * @param quat The quaternion rotation that the bone should be set to
  78579. * @param space The space that the rotation is in
  78580. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78581. */
  78582. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  78583. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78584. if (space === BABYLON.Space.LOCAL) {
  78585. this._decompose();
  78586. this._localRotation.copyFrom(quat);
  78587. this._markAsDirtyAndCompose();
  78588. return;
  78589. }
  78590. var rotMatInv = Bone._tmpMats[0];
  78591. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78592. return;
  78593. }
  78594. var rotMat = Bone._tmpMats[1];
  78595. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  78596. rotMatInv.multiplyToRef(rotMat, rotMat);
  78597. this._rotateWithMatrix(rotMat, space, mesh);
  78598. };
  78599. /**
  78600. * Set the rotation matrix of the bone in local of world space
  78601. * @param rotMat The rotation matrix that the bone should be set to
  78602. * @param space The space that the rotation is in
  78603. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78604. */
  78605. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  78606. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78607. if (space === BABYLON.Space.LOCAL) {
  78608. var quat = Bone._tmpQuat;
  78609. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  78610. this.setRotationQuaternion(quat, space, mesh);
  78611. return;
  78612. }
  78613. var rotMatInv = Bone._tmpMats[0];
  78614. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78615. return;
  78616. }
  78617. var rotMat2 = Bone._tmpMats[1];
  78618. rotMat2.copyFrom(rotMat);
  78619. rotMatInv.multiplyToRef(rotMat, rotMat2);
  78620. this._rotateWithMatrix(rotMat2, space, mesh);
  78621. };
  78622. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  78623. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78624. var lmat = this.getLocalMatrix();
  78625. var lx = lmat.m[12];
  78626. var ly = lmat.m[13];
  78627. var lz = lmat.m[14];
  78628. var parent = this.getParent();
  78629. var parentScale = Bone._tmpMats[3];
  78630. var parentScaleInv = Bone._tmpMats[4];
  78631. if (parent && space == BABYLON.Space.WORLD) {
  78632. if (mesh) {
  78633. parentScale.copyFrom(mesh.getWorldMatrix());
  78634. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  78635. }
  78636. else {
  78637. parentScale.copyFrom(parent.getAbsoluteTransform());
  78638. }
  78639. parentScaleInv.copyFrom(parentScale);
  78640. parentScaleInv.invert();
  78641. lmat.multiplyToRef(parentScale, lmat);
  78642. lmat.multiplyToRef(rmat, lmat);
  78643. lmat.multiplyToRef(parentScaleInv, lmat);
  78644. }
  78645. else {
  78646. if (space == BABYLON.Space.WORLD && mesh) {
  78647. parentScale.copyFrom(mesh.getWorldMatrix());
  78648. parentScaleInv.copyFrom(parentScale);
  78649. parentScaleInv.invert();
  78650. lmat.multiplyToRef(parentScale, lmat);
  78651. lmat.multiplyToRef(rmat, lmat);
  78652. lmat.multiplyToRef(parentScaleInv, lmat);
  78653. }
  78654. else {
  78655. lmat.multiplyToRef(rmat, lmat);
  78656. }
  78657. }
  78658. lmat.m[12] = lx;
  78659. lmat.m[13] = ly;
  78660. lmat.m[14] = lz;
  78661. this.computeAbsoluteTransforms();
  78662. this._markAsDirtyAndDecompose();
  78663. };
  78664. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  78665. var scaleMatrix = Bone._tmpMats[2];
  78666. rotMatInv.copyFrom(this.getAbsoluteTransform());
  78667. if (mesh) {
  78668. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  78669. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  78670. }
  78671. rotMatInv.invert();
  78672. if (isNaN(rotMatInv.m[0])) {
  78673. // Matrix failed to invert.
  78674. // This can happen if scale is zero for example.
  78675. return false;
  78676. }
  78677. scaleMatrix.m[0] *= this._scalingDeterminant;
  78678. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  78679. return true;
  78680. };
  78681. /**
  78682. * Get the position of the bone in local or world space
  78683. * @param space The space that the returned position is in
  78684. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78685. * @returns The position of the bone
  78686. */
  78687. Bone.prototype.getPosition = function (space, mesh) {
  78688. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78689. if (mesh === void 0) { mesh = null; }
  78690. var pos = BABYLON.Vector3.Zero();
  78691. this.getPositionToRef(space, mesh, pos);
  78692. return pos;
  78693. };
  78694. /**
  78695. * Copy the position of the bone to a vector3 in local or world space
  78696. * @param space The space that the returned position is in
  78697. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78698. * @param result The vector3 to copy the position to
  78699. */
  78700. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  78701. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78702. if (space == BABYLON.Space.LOCAL) {
  78703. var lm = this.getLocalMatrix();
  78704. result.x = lm.m[12];
  78705. result.y = lm.m[13];
  78706. result.z = lm.m[14];
  78707. }
  78708. else {
  78709. var wm = null;
  78710. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78711. if (mesh) {
  78712. wm = mesh.getWorldMatrix();
  78713. }
  78714. this._skeleton.computeAbsoluteTransforms();
  78715. var tmat = Bone._tmpMats[0];
  78716. if (mesh && wm) {
  78717. tmat.copyFrom(this.getAbsoluteTransform());
  78718. tmat.multiplyToRef(wm, tmat);
  78719. }
  78720. else {
  78721. tmat = this.getAbsoluteTransform();
  78722. }
  78723. result.x = tmat.m[12];
  78724. result.y = tmat.m[13];
  78725. result.z = tmat.m[14];
  78726. }
  78727. };
  78728. /**
  78729. * Get the absolute position of the bone (world space)
  78730. * @param mesh The mesh that this bone is attached to
  78731. * @returns The absolute position of the bone
  78732. */
  78733. Bone.prototype.getAbsolutePosition = function (mesh) {
  78734. if (mesh === void 0) { mesh = null; }
  78735. var pos = BABYLON.Vector3.Zero();
  78736. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  78737. return pos;
  78738. };
  78739. /**
  78740. * Copy the absolute position of the bone (world space) to the result param
  78741. * @param mesh The mesh that this bone is attached to
  78742. * @param result The vector3 to copy the absolute position to
  78743. */
  78744. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  78745. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  78746. };
  78747. /**
  78748. * Compute the absolute transforms of this bone and its children
  78749. */
  78750. Bone.prototype.computeAbsoluteTransforms = function () {
  78751. this._compose();
  78752. if (this._parent) {
  78753. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78754. }
  78755. else {
  78756. this._absoluteTransform.copyFrom(this._localMatrix);
  78757. var poseMatrix = this._skeleton.getPoseMatrix();
  78758. if (poseMatrix) {
  78759. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  78760. }
  78761. }
  78762. var children = this.children;
  78763. var len = children.length;
  78764. for (var i = 0; i < len; i++) {
  78765. children[i].computeAbsoluteTransforms();
  78766. }
  78767. };
  78768. /**
  78769. * Get the world direction from an axis that is in the local space of the bone
  78770. * @param localAxis The local direction that is used to compute the world direction
  78771. * @param mesh The mesh that this bone is attached to
  78772. * @returns The world direction
  78773. */
  78774. Bone.prototype.getDirection = function (localAxis, mesh) {
  78775. if (mesh === void 0) { mesh = null; }
  78776. var result = BABYLON.Vector3.Zero();
  78777. this.getDirectionToRef(localAxis, mesh, result);
  78778. return result;
  78779. };
  78780. /**
  78781. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  78782. * @param localAxis The local direction that is used to compute the world direction
  78783. * @param mesh The mesh that this bone is attached to
  78784. * @param result The vector3 that the world direction will be copied to
  78785. */
  78786. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  78787. if (mesh === void 0) { mesh = null; }
  78788. var wm = null;
  78789. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78790. if (mesh) {
  78791. wm = mesh.getWorldMatrix();
  78792. }
  78793. this._skeleton.computeAbsoluteTransforms();
  78794. var mat = Bone._tmpMats[0];
  78795. mat.copyFrom(this.getAbsoluteTransform());
  78796. if (mesh && wm) {
  78797. mat.multiplyToRef(wm, mat);
  78798. }
  78799. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  78800. result.normalize();
  78801. };
  78802. /**
  78803. * Get the euler rotation of the bone in local or world space
  78804. * @param space The space that the rotation should be in
  78805. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78806. * @returns The euler rotation
  78807. */
  78808. Bone.prototype.getRotation = function (space, mesh) {
  78809. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78810. if (mesh === void 0) { mesh = null; }
  78811. var result = BABYLON.Vector3.Zero();
  78812. this.getRotationToRef(space, mesh, result);
  78813. return result;
  78814. };
  78815. /**
  78816. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  78817. * @param space The space that the rotation should be in
  78818. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78819. * @param result The vector3 that the rotation should be copied to
  78820. */
  78821. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  78822. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78823. if (mesh === void 0) { mesh = null; }
  78824. var quat = Bone._tmpQuat;
  78825. this.getRotationQuaternionToRef(space, mesh, quat);
  78826. quat.toEulerAnglesToRef(result);
  78827. };
  78828. /**
  78829. * Get the quaternion rotation of the bone in either local or world space
  78830. * @param space The space that the rotation should be in
  78831. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78832. * @returns The quaternion rotation
  78833. */
  78834. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  78835. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78836. if (mesh === void 0) { mesh = null; }
  78837. var result = BABYLON.Quaternion.Identity();
  78838. this.getRotationQuaternionToRef(space, mesh, result);
  78839. return result;
  78840. };
  78841. /**
  78842. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  78843. * @param space The space that the rotation should be in
  78844. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78845. * @param result The quaternion that the rotation should be copied to
  78846. */
  78847. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  78848. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78849. if (mesh === void 0) { mesh = null; }
  78850. if (space == BABYLON.Space.LOCAL) {
  78851. this._decompose();
  78852. result.copyFrom(this._localRotation);
  78853. }
  78854. else {
  78855. var mat = Bone._tmpMats[0];
  78856. var amat = this.getAbsoluteTransform();
  78857. if (mesh) {
  78858. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78859. }
  78860. else {
  78861. mat.copyFrom(amat);
  78862. }
  78863. mat.m[0] *= this._scalingDeterminant;
  78864. mat.m[1] *= this._scalingDeterminant;
  78865. mat.m[2] *= this._scalingDeterminant;
  78866. mat.decompose(undefined, result, undefined);
  78867. }
  78868. };
  78869. /**
  78870. * Get the rotation matrix of the bone in local or world space
  78871. * @param space The space that the rotation should be in
  78872. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78873. * @returns The rotation matrix
  78874. */
  78875. Bone.prototype.getRotationMatrix = function (space, mesh) {
  78876. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78877. var result = BABYLON.Matrix.Identity();
  78878. this.getRotationMatrixToRef(space, mesh, result);
  78879. return result;
  78880. };
  78881. /**
  78882. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  78883. * @param space The space that the rotation should be in
  78884. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78885. * @param result The quaternion that the rotation should be copied to
  78886. */
  78887. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  78888. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78889. if (space == BABYLON.Space.LOCAL) {
  78890. this.getLocalMatrix().getRotationMatrixToRef(result);
  78891. }
  78892. else {
  78893. var mat = Bone._tmpMats[0];
  78894. var amat = this.getAbsoluteTransform();
  78895. if (mesh) {
  78896. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78897. }
  78898. else {
  78899. mat.copyFrom(amat);
  78900. }
  78901. mat.m[0] *= this._scalingDeterminant;
  78902. mat.m[1] *= this._scalingDeterminant;
  78903. mat.m[2] *= this._scalingDeterminant;
  78904. mat.getRotationMatrixToRef(result);
  78905. }
  78906. };
  78907. /**
  78908. * Get the world position of a point that is in the local space of the bone
  78909. * @param position The local position
  78910. * @param mesh The mesh that this bone is attached to
  78911. * @returns The world position
  78912. */
  78913. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  78914. if (mesh === void 0) { mesh = null; }
  78915. var result = BABYLON.Vector3.Zero();
  78916. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  78917. return result;
  78918. };
  78919. /**
  78920. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  78921. * @param position The local position
  78922. * @param mesh The mesh that this bone is attached to
  78923. * @param result The vector3 that the world position should be copied to
  78924. */
  78925. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  78926. if (mesh === void 0) { mesh = null; }
  78927. var wm = null;
  78928. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78929. if (mesh) {
  78930. wm = mesh.getWorldMatrix();
  78931. }
  78932. this._skeleton.computeAbsoluteTransforms();
  78933. var tmat = Bone._tmpMats[0];
  78934. if (mesh && wm) {
  78935. tmat.copyFrom(this.getAbsoluteTransform());
  78936. tmat.multiplyToRef(wm, tmat);
  78937. }
  78938. else {
  78939. tmat = this.getAbsoluteTransform();
  78940. }
  78941. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78942. };
  78943. /**
  78944. * Get the local position of a point that is in world space
  78945. * @param position The world position
  78946. * @param mesh The mesh that this bone is attached to
  78947. * @returns The local position
  78948. */
  78949. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  78950. if (mesh === void 0) { mesh = null; }
  78951. var result = BABYLON.Vector3.Zero();
  78952. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  78953. return result;
  78954. };
  78955. /**
  78956. * Get the local position of a point that is in world space and copy it to the result param
  78957. * @param position The world position
  78958. * @param mesh The mesh that this bone is attached to
  78959. * @param result The vector3 that the local position should be copied to
  78960. */
  78961. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  78962. if (mesh === void 0) { mesh = null; }
  78963. var wm = null;
  78964. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78965. if (mesh) {
  78966. wm = mesh.getWorldMatrix();
  78967. }
  78968. this._skeleton.computeAbsoluteTransforms();
  78969. var tmat = Bone._tmpMats[0];
  78970. tmat.copyFrom(this.getAbsoluteTransform());
  78971. if (mesh && wm) {
  78972. tmat.multiplyToRef(wm, tmat);
  78973. }
  78974. tmat.invert();
  78975. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78976. };
  78977. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78978. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  78979. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78980. return Bone;
  78981. }(BABYLON.Node));
  78982. BABYLON.Bone = Bone;
  78983. })(BABYLON || (BABYLON = {}));
  78984. //# sourceMappingURL=babylon.bone.js.map
  78985. var BABYLON;
  78986. (function (BABYLON) {
  78987. /**
  78988. * Class used to apply inverse kinematics to bones
  78989. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  78990. */
  78991. var BoneIKController = /** @class */ (function () {
  78992. /**
  78993. * Creates a new BoneIKController
  78994. * @param mesh defines the mesh to control
  78995. * @param bone defines the bone to control
  78996. * @param options defines options to set up the controller
  78997. */
  78998. function BoneIKController(mesh, bone, options) {
  78999. /**
  79000. * Gets or sets the target position
  79001. */
  79002. this.targetPosition = BABYLON.Vector3.Zero();
  79003. /**
  79004. * Gets or sets the pole target position
  79005. */
  79006. this.poleTargetPosition = BABYLON.Vector3.Zero();
  79007. /**
  79008. * Gets or sets the pole target local offset
  79009. */
  79010. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  79011. /**
  79012. * Gets or sets the pole angle
  79013. */
  79014. this.poleAngle = 0;
  79015. /**
  79016. * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp)
  79017. */
  79018. this.slerpAmount = 1;
  79019. this._bone1Quat = BABYLON.Quaternion.Identity();
  79020. this._bone1Mat = BABYLON.Matrix.Identity();
  79021. this._bone2Ang = Math.PI;
  79022. this._maxAngle = Math.PI;
  79023. this._rightHandedSystem = false;
  79024. this._bendAxis = BABYLON.Vector3.Right();
  79025. this._slerping = false;
  79026. this._adjustRoll = 0;
  79027. this._bone2 = bone;
  79028. this._bone1 = bone.getParent();
  79029. if (!this._bone1) {
  79030. return;
  79031. }
  79032. this.mesh = mesh;
  79033. var bonePos = bone.getPosition();
  79034. if (bone.getAbsoluteTransform().determinant() > 0) {
  79035. this._rightHandedSystem = true;
  79036. this._bendAxis.x = 0;
  79037. this._bendAxis.y = 0;
  79038. this._bendAxis.z = -1;
  79039. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  79040. this._adjustRoll = Math.PI * .5;
  79041. this._bendAxis.z = 1;
  79042. }
  79043. }
  79044. if (this._bone1.length) {
  79045. var boneScale1 = this._bone1.getScale();
  79046. var boneScale2 = this._bone2.getScale();
  79047. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  79048. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  79049. }
  79050. else if (this._bone1.children[0]) {
  79051. mesh.computeWorldMatrix(true);
  79052. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  79053. var pos2 = this._bone2.getAbsolutePosition(mesh);
  79054. var pos3 = this._bone1.getAbsolutePosition(mesh);
  79055. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  79056. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  79057. }
  79058. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  79059. this.maxAngle = Math.PI;
  79060. if (options) {
  79061. if (options.targetMesh) {
  79062. this.targetMesh = options.targetMesh;
  79063. this.targetMesh.computeWorldMatrix(true);
  79064. }
  79065. if (options.poleTargetMesh) {
  79066. this.poleTargetMesh = options.poleTargetMesh;
  79067. this.poleTargetMesh.computeWorldMatrix(true);
  79068. }
  79069. else if (options.poleTargetBone) {
  79070. this.poleTargetBone = options.poleTargetBone;
  79071. }
  79072. else if (this._bone1.getParent()) {
  79073. this.poleTargetBone = this._bone1.getParent();
  79074. }
  79075. if (options.poleTargetLocalOffset) {
  79076. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  79077. }
  79078. if (options.poleAngle) {
  79079. this.poleAngle = options.poleAngle;
  79080. }
  79081. if (options.bendAxis) {
  79082. this._bendAxis.copyFrom(options.bendAxis);
  79083. }
  79084. if (options.maxAngle) {
  79085. this.maxAngle = options.maxAngle;
  79086. }
  79087. if (options.slerpAmount) {
  79088. this.slerpAmount = options.slerpAmount;
  79089. }
  79090. }
  79091. }
  79092. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  79093. /**
  79094. * Gets or sets maximum allowed angle
  79095. */
  79096. get: function () {
  79097. return this._maxAngle;
  79098. },
  79099. set: function (value) {
  79100. this._setMaxAngle(value);
  79101. },
  79102. enumerable: true,
  79103. configurable: true
  79104. });
  79105. BoneIKController.prototype._setMaxAngle = function (ang) {
  79106. if (ang < 0) {
  79107. ang = 0;
  79108. }
  79109. if (ang > Math.PI || ang == undefined) {
  79110. ang = Math.PI;
  79111. }
  79112. this._maxAngle = ang;
  79113. var a = this._bone1Length;
  79114. var b = this._bone2Length;
  79115. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  79116. };
  79117. /**
  79118. * Force the controller to update the bones
  79119. */
  79120. BoneIKController.prototype.update = function () {
  79121. var bone1 = this._bone1;
  79122. if (!bone1) {
  79123. return;
  79124. }
  79125. var target = this.targetPosition;
  79126. var poleTarget = this.poleTargetPosition;
  79127. var mat1 = BoneIKController._tmpMats[0];
  79128. var mat2 = BoneIKController._tmpMats[1];
  79129. if (this.targetMesh) {
  79130. target.copyFrom(this.targetMesh.getAbsolutePosition());
  79131. }
  79132. if (this.poleTargetBone) {
  79133. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  79134. }
  79135. else if (this.poleTargetMesh) {
  79136. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  79137. }
  79138. var bonePos = BoneIKController._tmpVecs[0];
  79139. var zaxis = BoneIKController._tmpVecs[1];
  79140. var xaxis = BoneIKController._tmpVecs[2];
  79141. var yaxis = BoneIKController._tmpVecs[3];
  79142. var upAxis = BoneIKController._tmpVecs[4];
  79143. var _tmpQuat = BoneIKController._tmpQuat;
  79144. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  79145. poleTarget.subtractToRef(bonePos, upAxis);
  79146. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  79147. upAxis.y = 1;
  79148. }
  79149. else {
  79150. upAxis.normalize();
  79151. }
  79152. target.subtractToRef(bonePos, yaxis);
  79153. yaxis.normalize();
  79154. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  79155. zaxis.normalize();
  79156. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  79157. xaxis.normalize();
  79158. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  79159. var a = this._bone1Length;
  79160. var b = this._bone2Length;
  79161. var c = BABYLON.Vector3.Distance(bonePos, target);
  79162. if (this._maxReach > 0) {
  79163. c = Math.min(this._maxReach, c);
  79164. }
  79165. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  79166. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  79167. if (acosa > 1) {
  79168. acosa = 1;
  79169. }
  79170. if (acosb > 1) {
  79171. acosb = 1;
  79172. }
  79173. if (acosa < -1) {
  79174. acosa = -1;
  79175. }
  79176. if (acosb < -1) {
  79177. acosb = -1;
  79178. }
  79179. var angA = Math.acos(acosa);
  79180. var angB = Math.acos(acosb);
  79181. var angC = -angA - angB;
  79182. if (this._rightHandedSystem) {
  79183. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  79184. mat2.multiplyToRef(mat1, mat1);
  79185. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  79186. mat2.multiplyToRef(mat1, mat1);
  79187. }
  79188. else {
  79189. var _tmpVec = BoneIKController._tmpVecs[5];
  79190. _tmpVec.copyFrom(this._bendAxis);
  79191. _tmpVec.x *= -1;
  79192. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  79193. mat2.multiplyToRef(mat1, mat1);
  79194. }
  79195. if (this.poleAngle) {
  79196. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  79197. mat1.multiplyToRef(mat2, mat1);
  79198. }
  79199. if (this._bone1) {
  79200. if (this.slerpAmount < 1) {
  79201. if (!this._slerping) {
  79202. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  79203. }
  79204. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  79205. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  79206. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  79207. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  79208. this._slerping = true;
  79209. }
  79210. else {
  79211. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  79212. this._bone1Mat.copyFrom(mat1);
  79213. this._slerping = false;
  79214. }
  79215. }
  79216. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  79217. this._bone2Ang = angC;
  79218. };
  79219. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79220. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  79221. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79222. return BoneIKController;
  79223. }());
  79224. BABYLON.BoneIKController = BoneIKController;
  79225. })(BABYLON || (BABYLON = {}));
  79226. //# sourceMappingURL=babylon.boneIKController.js.map
  79227. var BABYLON;
  79228. (function (BABYLON) {
  79229. /**
  79230. * Class used to make a bone look toward a point in space
  79231. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  79232. */
  79233. var BoneLookController = /** @class */ (function () {
  79234. /**
  79235. * Create a BoneLookController
  79236. * @param mesh the mesh that the bone belongs to
  79237. * @param bone the bone that will be looking to the target
  79238. * @param target the target Vector3 to look at
  79239. * @param settings optional settings:
  79240. * * maxYaw: the maximum angle the bone will yaw to
  79241. * * minYaw: the minimum angle the bone will yaw to
  79242. * * maxPitch: the maximum angle the bone will pitch to
  79243. * * minPitch: the minimum angle the bone will yaw to
  79244. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  79245. * * upAxis: the up axis of the coordinate system
  79246. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  79247. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  79248. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  79249. * * adjustYaw: used to make an adjustment to the yaw of the bone
  79250. * * adjustPitch: used to make an adjustment to the pitch of the bone
  79251. * * adjustRoll: used to make an adjustment to the roll of the bone
  79252. **/
  79253. function BoneLookController(mesh, bone, target, options) {
  79254. /**
  79255. * The up axis of the coordinate system that is used when the bone is rotated
  79256. */
  79257. this.upAxis = BABYLON.Vector3.Up();
  79258. /**
  79259. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  79260. */
  79261. this.upAxisSpace = BABYLON.Space.LOCAL;
  79262. /**
  79263. * Used to make an adjustment to the yaw of the bone
  79264. */
  79265. this.adjustYaw = 0;
  79266. /**
  79267. * Used to make an adjustment to the pitch of the bone
  79268. */
  79269. this.adjustPitch = 0;
  79270. /**
  79271. * Used to make an adjustment to the roll of the bone
  79272. */
  79273. this.adjustRoll = 0;
  79274. /**
  79275. * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp)
  79276. */
  79277. this.slerpAmount = 1;
  79278. this._boneQuat = BABYLON.Quaternion.Identity();
  79279. this._slerping = false;
  79280. this._firstFrameSkipped = false;
  79281. this._fowardAxis = BABYLON.Vector3.Forward();
  79282. this.mesh = mesh;
  79283. this.bone = bone;
  79284. this.target = target;
  79285. if (options) {
  79286. if (options.adjustYaw) {
  79287. this.adjustYaw = options.adjustYaw;
  79288. }
  79289. if (options.adjustPitch) {
  79290. this.adjustPitch = options.adjustPitch;
  79291. }
  79292. if (options.adjustRoll) {
  79293. this.adjustRoll = options.adjustRoll;
  79294. }
  79295. if (options.maxYaw != null) {
  79296. this.maxYaw = options.maxYaw;
  79297. }
  79298. else {
  79299. this.maxYaw = Math.PI;
  79300. }
  79301. if (options.minYaw != null) {
  79302. this.minYaw = options.minYaw;
  79303. }
  79304. else {
  79305. this.minYaw = -Math.PI;
  79306. }
  79307. if (options.maxPitch != null) {
  79308. this.maxPitch = options.maxPitch;
  79309. }
  79310. else {
  79311. this.maxPitch = Math.PI;
  79312. }
  79313. if (options.minPitch != null) {
  79314. this.minPitch = options.minPitch;
  79315. }
  79316. else {
  79317. this.minPitch = -Math.PI;
  79318. }
  79319. if (options.slerpAmount != null) {
  79320. this.slerpAmount = options.slerpAmount;
  79321. }
  79322. if (options.upAxis != null) {
  79323. this.upAxis = options.upAxis;
  79324. }
  79325. if (options.upAxisSpace != null) {
  79326. this.upAxisSpace = options.upAxisSpace;
  79327. }
  79328. if (options.yawAxis != null || options.pitchAxis != null) {
  79329. var newYawAxis = BABYLON.Axis.Y;
  79330. var newPitchAxis = BABYLON.Axis.X;
  79331. if (options.yawAxis != null) {
  79332. newYawAxis = options.yawAxis.clone();
  79333. newYawAxis.normalize();
  79334. }
  79335. if (options.pitchAxis != null) {
  79336. newPitchAxis = options.pitchAxis.clone();
  79337. newPitchAxis.normalize();
  79338. }
  79339. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  79340. this._transformYawPitch = BABYLON.Matrix.Identity();
  79341. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  79342. this._transformYawPitchInv = this._transformYawPitch.clone();
  79343. this._transformYawPitch.invert();
  79344. }
  79345. }
  79346. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  79347. this.upAxisSpace = BABYLON.Space.LOCAL;
  79348. }
  79349. }
  79350. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  79351. /**
  79352. * Gets or sets the minimum yaw angle that the bone can look to
  79353. */
  79354. get: function () {
  79355. return this._minYaw;
  79356. },
  79357. set: function (value) {
  79358. this._minYaw = value;
  79359. this._minYawSin = Math.sin(value);
  79360. this._minYawCos = Math.cos(value);
  79361. if (this._maxYaw != null) {
  79362. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79363. this._yawRange = this._maxYaw - this._minYaw;
  79364. }
  79365. },
  79366. enumerable: true,
  79367. configurable: true
  79368. });
  79369. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  79370. /**
  79371. * Gets or sets the maximum yaw angle that the bone can look to
  79372. */
  79373. get: function () {
  79374. return this._maxYaw;
  79375. },
  79376. set: function (value) {
  79377. this._maxYaw = value;
  79378. this._maxYawSin = Math.sin(value);
  79379. this._maxYawCos = Math.cos(value);
  79380. if (this._minYaw != null) {
  79381. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79382. this._yawRange = this._maxYaw - this._minYaw;
  79383. }
  79384. },
  79385. enumerable: true,
  79386. configurable: true
  79387. });
  79388. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  79389. /**
  79390. * Gets or sets the minimum pitch angle that the bone can look to
  79391. */
  79392. get: function () {
  79393. return this._minPitch;
  79394. },
  79395. set: function (value) {
  79396. this._minPitch = value;
  79397. this._minPitchTan = Math.tan(value);
  79398. },
  79399. enumerable: true,
  79400. configurable: true
  79401. });
  79402. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  79403. /**
  79404. * Gets or sets the maximum pitch angle that the bone can look to
  79405. */
  79406. get: function () {
  79407. return this._maxPitch;
  79408. },
  79409. set: function (value) {
  79410. this._maxPitch = value;
  79411. this._maxPitchTan = Math.tan(value);
  79412. },
  79413. enumerable: true,
  79414. configurable: true
  79415. });
  79416. /**
  79417. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  79418. */
  79419. BoneLookController.prototype.update = function () {
  79420. //skip the first frame when slerping so that the mesh rotation is correct
  79421. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  79422. this._firstFrameSkipped = true;
  79423. return;
  79424. }
  79425. var bone = this.bone;
  79426. var bonePos = BoneLookController._tmpVecs[0];
  79427. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  79428. var target = this.target;
  79429. var _tmpMat1 = BoneLookController._tmpMats[0];
  79430. var _tmpMat2 = BoneLookController._tmpMats[1];
  79431. var mesh = this.mesh;
  79432. var parentBone = bone.getParent();
  79433. var upAxis = BoneLookController._tmpVecs[1];
  79434. upAxis.copyFrom(this.upAxis);
  79435. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  79436. if (this._transformYawPitch) {
  79437. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  79438. }
  79439. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  79440. }
  79441. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  79442. mesh.getDirectionToRef(upAxis, upAxis);
  79443. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  79444. upAxis.normalize();
  79445. }
  79446. }
  79447. var checkYaw = false;
  79448. var checkPitch = false;
  79449. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  79450. checkYaw = true;
  79451. }
  79452. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  79453. checkPitch = true;
  79454. }
  79455. if (checkYaw || checkPitch) {
  79456. var spaceMat = BoneLookController._tmpMats[2];
  79457. var spaceMatInv = BoneLookController._tmpMats[3];
  79458. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  79459. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  79460. }
  79461. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  79462. spaceMat.copyFrom(mesh.getWorldMatrix());
  79463. }
  79464. else {
  79465. var forwardAxis = BoneLookController._tmpVecs[2];
  79466. forwardAxis.copyFrom(this._fowardAxis);
  79467. if (this._transformYawPitch) {
  79468. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  79469. }
  79470. if (parentBone) {
  79471. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  79472. }
  79473. else {
  79474. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  79475. }
  79476. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  79477. rightAxis.normalize();
  79478. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  79479. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  79480. }
  79481. spaceMat.invertToRef(spaceMatInv);
  79482. var xzlen = null;
  79483. if (checkPitch) {
  79484. var localTarget = BoneLookController._tmpVecs[3];
  79485. target.subtractToRef(bonePos, localTarget);
  79486. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79487. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79488. var pitch = Math.atan2(localTarget.y, xzlen);
  79489. var newPitch = pitch;
  79490. if (pitch > this._maxPitch) {
  79491. localTarget.y = this._maxPitchTan * xzlen;
  79492. newPitch = this._maxPitch;
  79493. }
  79494. else if (pitch < this._minPitch) {
  79495. localTarget.y = this._minPitchTan * xzlen;
  79496. newPitch = this._minPitch;
  79497. }
  79498. if (pitch != newPitch) {
  79499. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79500. localTarget.addInPlace(bonePos);
  79501. target = localTarget;
  79502. }
  79503. }
  79504. if (checkYaw) {
  79505. var localTarget = BoneLookController._tmpVecs[4];
  79506. target.subtractToRef(bonePos, localTarget);
  79507. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79508. var yaw = Math.atan2(localTarget.x, localTarget.z);
  79509. var newYaw = yaw;
  79510. if (yaw > this._maxYaw || yaw < this._minYaw) {
  79511. if (xzlen == null) {
  79512. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79513. }
  79514. if (this._yawRange > Math.PI) {
  79515. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  79516. localTarget.z = this._maxYawCos * xzlen;
  79517. localTarget.x = this._maxYawSin * xzlen;
  79518. newYaw = this._maxYaw;
  79519. }
  79520. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  79521. localTarget.z = this._minYawCos * xzlen;
  79522. localTarget.x = this._minYawSin * xzlen;
  79523. newYaw = this._minYaw;
  79524. }
  79525. }
  79526. else {
  79527. if (yaw > this._maxYaw) {
  79528. localTarget.z = this._maxYawCos * xzlen;
  79529. localTarget.x = this._maxYawSin * xzlen;
  79530. newYaw = this._maxYaw;
  79531. }
  79532. else if (yaw < this._minYaw) {
  79533. localTarget.z = this._minYawCos * xzlen;
  79534. localTarget.x = this._minYawSin * xzlen;
  79535. newYaw = this._minYaw;
  79536. }
  79537. }
  79538. }
  79539. if (this._slerping && this._yawRange > Math.PI) {
  79540. //are we going to be crossing into the min/max region?
  79541. var boneFwd = BoneLookController._tmpVecs[8];
  79542. boneFwd.copyFrom(BABYLON.Axis.Z);
  79543. if (this._transformYawPitch) {
  79544. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  79545. }
  79546. var boneRotMat = BoneLookController._tmpMats[4];
  79547. this._boneQuat.toRotationMatrix(boneRotMat);
  79548. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  79549. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  79550. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  79551. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  79552. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  79553. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  79554. if (angBtwTar > angBtwMidYaw) {
  79555. if (xzlen == null) {
  79556. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79557. }
  79558. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  79559. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  79560. if (angBtwMin < angBtwMax) {
  79561. newYaw = boneYaw + Math.PI * .75;
  79562. localTarget.z = Math.cos(newYaw) * xzlen;
  79563. localTarget.x = Math.sin(newYaw) * xzlen;
  79564. }
  79565. else {
  79566. newYaw = boneYaw - Math.PI * .75;
  79567. localTarget.z = Math.cos(newYaw) * xzlen;
  79568. localTarget.x = Math.sin(newYaw) * xzlen;
  79569. }
  79570. }
  79571. }
  79572. if (yaw != newYaw) {
  79573. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79574. localTarget.addInPlace(bonePos);
  79575. target = localTarget;
  79576. }
  79577. }
  79578. }
  79579. var zaxis = BoneLookController._tmpVecs[5];
  79580. var xaxis = BoneLookController._tmpVecs[6];
  79581. var yaxis = BoneLookController._tmpVecs[7];
  79582. var _tmpQuat = BoneLookController._tmpQuat;
  79583. target.subtractToRef(bonePos, zaxis);
  79584. zaxis.normalize();
  79585. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  79586. xaxis.normalize();
  79587. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  79588. yaxis.normalize();
  79589. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  79590. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  79591. return;
  79592. }
  79593. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  79594. return;
  79595. }
  79596. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  79597. return;
  79598. }
  79599. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  79600. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  79601. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  79602. }
  79603. if (this.slerpAmount < 1) {
  79604. if (!this._slerping) {
  79605. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  79606. }
  79607. if (this._transformYawPitch) {
  79608. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79609. }
  79610. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  79611. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  79612. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  79613. this._slerping = true;
  79614. }
  79615. else {
  79616. if (this._transformYawPitch) {
  79617. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79618. }
  79619. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  79620. this._slerping = false;
  79621. }
  79622. };
  79623. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  79624. var angDiff = ang2 - ang1;
  79625. angDiff %= Math.PI * 2;
  79626. if (angDiff > Math.PI) {
  79627. angDiff -= Math.PI * 2;
  79628. }
  79629. else if (angDiff < -Math.PI) {
  79630. angDiff += Math.PI * 2;
  79631. }
  79632. return angDiff;
  79633. };
  79634. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  79635. ang1 %= (2 * Math.PI);
  79636. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79637. ang2 %= (2 * Math.PI);
  79638. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79639. var ab = 0;
  79640. if (ang1 < ang2) {
  79641. ab = ang2 - ang1;
  79642. }
  79643. else {
  79644. ab = ang1 - ang2;
  79645. }
  79646. if (ab > Math.PI) {
  79647. ab = Math.PI * 2 - ab;
  79648. }
  79649. return ab;
  79650. };
  79651. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  79652. ang %= (2 * Math.PI);
  79653. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  79654. ang1 %= (2 * Math.PI);
  79655. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79656. ang2 %= (2 * Math.PI);
  79657. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79658. if (ang1 < ang2) {
  79659. if (ang > ang1 && ang < ang2) {
  79660. return true;
  79661. }
  79662. }
  79663. else {
  79664. if (ang > ang2 && ang < ang1) {
  79665. return true;
  79666. }
  79667. }
  79668. return false;
  79669. };
  79670. BoneLookController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79671. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  79672. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79673. return BoneLookController;
  79674. }());
  79675. BABYLON.BoneLookController = BoneLookController;
  79676. })(BABYLON || (BABYLON = {}));
  79677. //# sourceMappingURL=babylon.boneLookController.js.map
  79678. var BABYLON;
  79679. (function (BABYLON) {
  79680. /**
  79681. * Class used to handle skinning animations
  79682. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79683. */
  79684. var Skeleton = /** @class */ (function () {
  79685. /**
  79686. * Creates a new skeleton
  79687. * @param name defines the skeleton name
  79688. * @param id defines the skeleton Id
  79689. * @param scene defines the hosting scene
  79690. */
  79691. function Skeleton(
  79692. /** defines the skeleton name */
  79693. name,
  79694. /** defines the skeleton Id */
  79695. id, scene) {
  79696. this.name = name;
  79697. this.id = id;
  79698. /**
  79699. * Gets the list of child bones
  79700. */
  79701. this.bones = new Array();
  79702. /**
  79703. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  79704. */
  79705. this.needInitialSkinMatrix = false;
  79706. this._isDirty = true;
  79707. this._meshesWithPoseMatrix = new Array();
  79708. this._identity = BABYLON.Matrix.Identity();
  79709. this._ranges = {};
  79710. this._lastAbsoluteTransformsUpdateId = -1;
  79711. /**
  79712. * Specifies if the skeleton should be serialized
  79713. */
  79714. this.doNotSerialize = false;
  79715. this._animationPropertiesOverride = null;
  79716. // Events
  79717. /**
  79718. * An observable triggered before computing the skeleton's matrices
  79719. */
  79720. this.onBeforeComputeObservable = new BABYLON.Observable();
  79721. this.bones = [];
  79722. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79723. scene.skeletons.push(this);
  79724. //make sure it will recalculate the matrix next time prepare is called.
  79725. this._isDirty = true;
  79726. }
  79727. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  79728. /**
  79729. * Gets or sets the animation properties override
  79730. */
  79731. get: function () {
  79732. if (!this._animationPropertiesOverride) {
  79733. return this._scene.animationPropertiesOverride;
  79734. }
  79735. return this._animationPropertiesOverride;
  79736. },
  79737. set: function (value) {
  79738. this._animationPropertiesOverride = value;
  79739. },
  79740. enumerable: true,
  79741. configurable: true
  79742. });
  79743. // Members
  79744. /**
  79745. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  79746. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  79747. * @returns a Float32Array containing matrices data
  79748. */
  79749. Skeleton.prototype.getTransformMatrices = function (mesh) {
  79750. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  79751. return mesh._bonesTransformMatrices;
  79752. }
  79753. if (!this._transformMatrices) {
  79754. this.prepare();
  79755. }
  79756. return this._transformMatrices;
  79757. };
  79758. /**
  79759. * Gets the current hosting scene
  79760. * @returns a scene object
  79761. */
  79762. Skeleton.prototype.getScene = function () {
  79763. return this._scene;
  79764. };
  79765. // Methods
  79766. /**
  79767. * Gets a string representing the current skeleton data
  79768. * @param fullDetails defines a boolean indicating if we want a verbose version
  79769. * @returns a string representing the current skeleton data
  79770. */
  79771. Skeleton.prototype.toString = function (fullDetails) {
  79772. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  79773. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  79774. if (fullDetails) {
  79775. ret += ", Ranges: {";
  79776. var first = true;
  79777. for (var name_1 in this._ranges) {
  79778. if (first) {
  79779. ret += ", ";
  79780. first = false;
  79781. }
  79782. ret += name_1;
  79783. }
  79784. ret += "}";
  79785. }
  79786. return ret;
  79787. };
  79788. /**
  79789. * Get bone's index searching by name
  79790. * @param name defines bone's name to search for
  79791. * @return the indice of the bone. Returns -1 if not found
  79792. */
  79793. Skeleton.prototype.getBoneIndexByName = function (name) {
  79794. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  79795. if (this.bones[boneIndex].name === name) {
  79796. return boneIndex;
  79797. }
  79798. }
  79799. return -1;
  79800. };
  79801. /**
  79802. * Creater a new animation range
  79803. * @param name defines the name of the range
  79804. * @param from defines the start key
  79805. * @param to defines the end key
  79806. */
  79807. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  79808. // check name not already in use
  79809. if (!this._ranges[name]) {
  79810. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  79811. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79812. if (this.bones[i].animations[0]) {
  79813. this.bones[i].animations[0].createRange(name, from, to);
  79814. }
  79815. }
  79816. }
  79817. };
  79818. /**
  79819. * Delete a specific animation range
  79820. * @param name defines the name of the range
  79821. * @param deleteFrames defines if frames must be removed as well
  79822. */
  79823. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  79824. if (deleteFrames === void 0) { deleteFrames = true; }
  79825. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79826. if (this.bones[i].animations[0]) {
  79827. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  79828. }
  79829. }
  79830. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  79831. };
  79832. /**
  79833. * Gets a specific animation range
  79834. * @param name defines the name of the range to look for
  79835. * @returns the requested animation range or null if not found
  79836. */
  79837. Skeleton.prototype.getAnimationRange = function (name) {
  79838. return this._ranges[name];
  79839. };
  79840. /**
  79841. * Gets the list of all animation ranges defined on this skeleton
  79842. * @returns an array
  79843. */
  79844. Skeleton.prototype.getAnimationRanges = function () {
  79845. var animationRanges = [];
  79846. var name;
  79847. var i = 0;
  79848. for (name in this._ranges) {
  79849. animationRanges[i] = this._ranges[name];
  79850. i++;
  79851. }
  79852. return animationRanges;
  79853. };
  79854. /**
  79855. * Copy animation range from a source skeleton.
  79856. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  79857. * @param source defines the source skeleton
  79858. * @param name defines the name of the range to copy
  79859. * @param rescaleAsRequired defines if rescaling must be applied if required
  79860. * @returns true if operation was successful
  79861. */
  79862. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  79863. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79864. if (this._ranges[name] || !source.getAnimationRange(name)) {
  79865. return false;
  79866. }
  79867. var ret = true;
  79868. var frameOffset = this._getHighestAnimationFrame() + 1;
  79869. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  79870. var boneDict = {};
  79871. var sourceBones = source.bones;
  79872. var nBones;
  79873. var i;
  79874. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  79875. boneDict[sourceBones[i].name] = sourceBones[i];
  79876. }
  79877. if (this.bones.length !== sourceBones.length) {
  79878. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  79879. ret = false;
  79880. }
  79881. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  79882. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  79883. var boneName = this.bones[i].name;
  79884. var sourceBone = boneDict[boneName];
  79885. if (sourceBone) {
  79886. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  79887. }
  79888. else {
  79889. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  79890. ret = false;
  79891. }
  79892. }
  79893. // do not call createAnimationRange(), since it also is done to bones, which was already done
  79894. var range = source.getAnimationRange(name);
  79895. if (range) {
  79896. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  79897. }
  79898. return ret;
  79899. };
  79900. /**
  79901. * Forces the skeleton to go to rest pose
  79902. */
  79903. Skeleton.prototype.returnToRest = function () {
  79904. for (var index = 0; index < this.bones.length; index++) {
  79905. this.bones[index].returnToRest();
  79906. }
  79907. };
  79908. Skeleton.prototype._getHighestAnimationFrame = function () {
  79909. var ret = 0;
  79910. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79911. if (this.bones[i].animations[0]) {
  79912. var highest = this.bones[i].animations[0].getHighestFrame();
  79913. if (ret < highest) {
  79914. ret = highest;
  79915. }
  79916. }
  79917. }
  79918. return ret;
  79919. };
  79920. /**
  79921. * Begin a specific animation range
  79922. * @param name defines the name of the range to start
  79923. * @param loop defines if looping must be turned on (false by default)
  79924. * @param speedRatio defines the speed ratio to apply (1 by default)
  79925. * @param onAnimationEnd defines a callback which will be called when animation will end
  79926. * @returns a new animatable
  79927. */
  79928. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  79929. var range = this.getAnimationRange(name);
  79930. if (!range) {
  79931. return null;
  79932. }
  79933. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  79934. };
  79935. /** @hidden */
  79936. Skeleton.prototype._markAsDirty = function () {
  79937. this._isDirty = true;
  79938. };
  79939. /** @hidden */
  79940. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  79941. this._meshesWithPoseMatrix.push(mesh);
  79942. };
  79943. /** @hidden */
  79944. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  79945. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  79946. if (index > -1) {
  79947. this._meshesWithPoseMatrix.splice(index, 1);
  79948. }
  79949. };
  79950. /** @hidden */
  79951. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  79952. this.onBeforeComputeObservable.notifyObservers(this);
  79953. for (var index = 0; index < this.bones.length; index++) {
  79954. var bone = this.bones[index];
  79955. var parentBone = bone.getParent();
  79956. if (parentBone) {
  79957. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  79958. }
  79959. else {
  79960. if (initialSkinMatrix) {
  79961. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  79962. }
  79963. else {
  79964. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  79965. }
  79966. }
  79967. if (bone._index !== -1) {
  79968. var mappedIndex = bone._index === null ? index : bone._index;
  79969. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  79970. }
  79971. }
  79972. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  79973. };
  79974. /**
  79975. * Build all resources required to render a skeleton
  79976. */
  79977. Skeleton.prototype.prepare = function () {
  79978. if (!this._isDirty) {
  79979. return;
  79980. }
  79981. if (this.needInitialSkinMatrix) {
  79982. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  79983. var mesh = this._meshesWithPoseMatrix[index];
  79984. var poseMatrix = mesh.getPoseMatrix();
  79985. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  79986. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79987. }
  79988. if (this._synchronizedWithMesh !== mesh) {
  79989. this._synchronizedWithMesh = mesh;
  79990. // Prepare bones
  79991. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  79992. var bone = this.bones[boneIndex];
  79993. if (!bone.getParent()) {
  79994. var matrix = bone.getBaseMatrix();
  79995. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  79996. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  79997. }
  79998. }
  79999. }
  80000. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  80001. }
  80002. }
  80003. else {
  80004. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  80005. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80006. }
  80007. this._computeTransformMatrices(this._transformMatrices, null);
  80008. }
  80009. this._isDirty = false;
  80010. this._scene._activeBones.addCount(this.bones.length, false);
  80011. };
  80012. /**
  80013. * Gets the list of animatables currently running for this skeleton
  80014. * @returns an array of animatables
  80015. */
  80016. Skeleton.prototype.getAnimatables = function () {
  80017. if (!this._animatables || this._animatables.length !== this.bones.length) {
  80018. this._animatables = [];
  80019. for (var index = 0; index < this.bones.length; index++) {
  80020. this._animatables.push(this.bones[index]);
  80021. }
  80022. }
  80023. return this._animatables;
  80024. };
  80025. /**
  80026. * Clone the current skeleton
  80027. * @param name defines the name of the new skeleton
  80028. * @param id defines the id of the enw skeleton
  80029. * @returns the new skeleton
  80030. */
  80031. Skeleton.prototype.clone = function (name, id) {
  80032. var result = new Skeleton(name, id || name, this._scene);
  80033. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80034. for (var index = 0; index < this.bones.length; index++) {
  80035. var source = this.bones[index];
  80036. var parentBone = null;
  80037. var parent_1 = source.getParent();
  80038. if (parent_1) {
  80039. var parentIndex = this.bones.indexOf(parent_1);
  80040. parentBone = result.bones[parentIndex];
  80041. }
  80042. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  80043. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  80044. }
  80045. if (this._ranges) {
  80046. result._ranges = {};
  80047. for (var rangeName in this._ranges) {
  80048. var range = this._ranges[rangeName];
  80049. if (range) {
  80050. result._ranges[rangeName] = range.clone();
  80051. }
  80052. }
  80053. }
  80054. this._isDirty = true;
  80055. return result;
  80056. };
  80057. /**
  80058. * Enable animation blending for this skeleton
  80059. * @param blendingSpeed defines the blending speed to apply
  80060. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  80061. */
  80062. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  80063. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  80064. this.bones.forEach(function (bone) {
  80065. bone.animations.forEach(function (animation) {
  80066. animation.enableBlending = true;
  80067. animation.blendingSpeed = blendingSpeed;
  80068. });
  80069. });
  80070. };
  80071. /**
  80072. * Releases all resources associated with the current skeleton
  80073. */
  80074. Skeleton.prototype.dispose = function () {
  80075. this._meshesWithPoseMatrix = [];
  80076. // Animations
  80077. this.getScene().stopAnimation(this);
  80078. // Remove from scene
  80079. this.getScene().removeSkeleton(this);
  80080. };
  80081. /**
  80082. * Serialize the skeleton in a JSON object
  80083. * @returns a JSON object
  80084. */
  80085. Skeleton.prototype.serialize = function () {
  80086. var serializationObject = {};
  80087. serializationObject.name = this.name;
  80088. serializationObject.id = this.id;
  80089. if (this.dimensionsAtRest) {
  80090. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  80091. }
  80092. serializationObject.bones = [];
  80093. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80094. for (var index = 0; index < this.bones.length; index++) {
  80095. var bone = this.bones[index];
  80096. var parent_2 = bone.getParent();
  80097. var serializedBone = {
  80098. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  80099. name: bone.name,
  80100. matrix: bone.getBaseMatrix().toArray(),
  80101. rest: bone.getRestPose().toArray()
  80102. };
  80103. serializationObject.bones.push(serializedBone);
  80104. if (bone.length) {
  80105. serializedBone.length = bone.length;
  80106. }
  80107. if (bone.metadata) {
  80108. serializedBone.metadata = bone.metadata;
  80109. }
  80110. if (bone.animations && bone.animations.length > 0) {
  80111. serializedBone.animation = bone.animations[0].serialize();
  80112. }
  80113. serializationObject.ranges = [];
  80114. for (var name in this._ranges) {
  80115. var source = this._ranges[name];
  80116. if (!source) {
  80117. continue;
  80118. }
  80119. var range = {};
  80120. range.name = name;
  80121. range.from = source.from;
  80122. range.to = source.to;
  80123. serializationObject.ranges.push(range);
  80124. }
  80125. }
  80126. return serializationObject;
  80127. };
  80128. /**
  80129. * Creates a new skeleton from serialized data
  80130. * @param parsedSkeleton defines the serialized data
  80131. * @param scene defines the hosting scene
  80132. * @returns a new skeleton
  80133. */
  80134. Skeleton.Parse = function (parsedSkeleton, scene) {
  80135. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  80136. if (parsedSkeleton.dimensionsAtRest) {
  80137. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  80138. }
  80139. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  80140. var index;
  80141. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  80142. var parsedBone = parsedSkeleton.bones[index];
  80143. var parentBone = null;
  80144. if (parsedBone.parentBoneIndex > -1) {
  80145. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  80146. }
  80147. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  80148. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  80149. if (parsedBone.length) {
  80150. bone.length = parsedBone.length;
  80151. }
  80152. if (parsedBone.metadata) {
  80153. bone.metadata = parsedBone.metadata;
  80154. }
  80155. if (parsedBone.animation) {
  80156. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  80157. }
  80158. }
  80159. // placed after bones, so createAnimationRange can cascade down
  80160. if (parsedSkeleton.ranges) {
  80161. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  80162. var data = parsedSkeleton.ranges[index];
  80163. skeleton.createAnimationRange(data.name, data.from, data.to);
  80164. }
  80165. }
  80166. return skeleton;
  80167. };
  80168. /**
  80169. * Compute all node absolute transforms
  80170. * @param forceUpdate defines if computation must be done even if cache is up to date
  80171. */
  80172. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  80173. if (forceUpdate === void 0) { forceUpdate = false; }
  80174. var renderId = this._scene.getRenderId();
  80175. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  80176. this.bones[0].computeAbsoluteTransforms();
  80177. this._lastAbsoluteTransformsUpdateId = renderId;
  80178. }
  80179. };
  80180. /**
  80181. * Gets the root pose matrix
  80182. * @returns a matrix
  80183. */
  80184. Skeleton.prototype.getPoseMatrix = function () {
  80185. var poseMatrix = null;
  80186. if (this._meshesWithPoseMatrix.length > 0) {
  80187. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  80188. }
  80189. return poseMatrix;
  80190. };
  80191. /**
  80192. * Sorts bones per internal index
  80193. */
  80194. Skeleton.prototype.sortBones = function () {
  80195. var bones = new Array();
  80196. var visited = new Array(this.bones.length);
  80197. for (var index = 0; index < this.bones.length; index++) {
  80198. this._sortBones(index, bones, visited);
  80199. }
  80200. this.bones = bones;
  80201. };
  80202. Skeleton.prototype._sortBones = function (index, bones, visited) {
  80203. if (visited[index]) {
  80204. return;
  80205. }
  80206. visited[index] = true;
  80207. var bone = this.bones[index];
  80208. if (bone._index === undefined) {
  80209. bone._index = index;
  80210. }
  80211. var parentBone = bone.getParent();
  80212. if (parentBone) {
  80213. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  80214. }
  80215. bones.push(bone);
  80216. };
  80217. return Skeleton;
  80218. }());
  80219. BABYLON.Skeleton = Skeleton;
  80220. })(BABYLON || (BABYLON = {}));
  80221. //# sourceMappingURL=babylon.skeleton.js.map
  80222. var BABYLON;
  80223. (function (BABYLON) {
  80224. var SphericalPolynomial = /** @class */ (function () {
  80225. function SphericalPolynomial() {
  80226. this.x = BABYLON.Vector3.Zero();
  80227. this.y = BABYLON.Vector3.Zero();
  80228. this.z = BABYLON.Vector3.Zero();
  80229. this.xx = BABYLON.Vector3.Zero();
  80230. this.yy = BABYLON.Vector3.Zero();
  80231. this.zz = BABYLON.Vector3.Zero();
  80232. this.xy = BABYLON.Vector3.Zero();
  80233. this.yz = BABYLON.Vector3.Zero();
  80234. this.zx = BABYLON.Vector3.Zero();
  80235. }
  80236. SphericalPolynomial.prototype.addAmbient = function (color) {
  80237. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80238. this.xx = this.xx.add(colorVector);
  80239. this.yy = this.yy.add(colorVector);
  80240. this.zz = this.zz.add(colorVector);
  80241. };
  80242. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  80243. var result = new SphericalPolynomial();
  80244. result.x = harmonics.L11.scale(1.02333);
  80245. result.y = harmonics.L1_1.scale(1.02333);
  80246. result.z = harmonics.L10.scale(1.02333);
  80247. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  80248. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  80249. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  80250. result.yz = harmonics.L2_1.scale(0.858086);
  80251. result.zx = harmonics.L21.scale(0.858086);
  80252. result.xy = harmonics.L2_2.scale(0.858086);
  80253. result.scale(1.0 / Math.PI);
  80254. return result;
  80255. };
  80256. SphericalPolynomial.prototype.scale = function (scale) {
  80257. this.x = this.x.scale(scale);
  80258. this.y = this.y.scale(scale);
  80259. this.z = this.z.scale(scale);
  80260. this.xx = this.xx.scale(scale);
  80261. this.yy = this.yy.scale(scale);
  80262. this.zz = this.zz.scale(scale);
  80263. this.yz = this.yz.scale(scale);
  80264. this.zx = this.zx.scale(scale);
  80265. this.xy = this.xy.scale(scale);
  80266. };
  80267. return SphericalPolynomial;
  80268. }());
  80269. BABYLON.SphericalPolynomial = SphericalPolynomial;
  80270. var SphericalHarmonics = /** @class */ (function () {
  80271. function SphericalHarmonics() {
  80272. this.L00 = BABYLON.Vector3.Zero();
  80273. this.L1_1 = BABYLON.Vector3.Zero();
  80274. this.L10 = BABYLON.Vector3.Zero();
  80275. this.L11 = BABYLON.Vector3.Zero();
  80276. this.L2_2 = BABYLON.Vector3.Zero();
  80277. this.L2_1 = BABYLON.Vector3.Zero();
  80278. this.L20 = BABYLON.Vector3.Zero();
  80279. this.L21 = BABYLON.Vector3.Zero();
  80280. this.L22 = BABYLON.Vector3.Zero();
  80281. }
  80282. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  80283. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80284. var c = colorVector.scale(deltaSolidAngle);
  80285. this.L00 = this.L00.add(c.scale(0.282095));
  80286. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  80287. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  80288. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  80289. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  80290. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  80291. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  80292. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  80293. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  80294. };
  80295. SphericalHarmonics.prototype.scale = function (scale) {
  80296. this.L00 = this.L00.scale(scale);
  80297. this.L1_1 = this.L1_1.scale(scale);
  80298. this.L10 = this.L10.scale(scale);
  80299. this.L11 = this.L11.scale(scale);
  80300. this.L2_2 = this.L2_2.scale(scale);
  80301. this.L2_1 = this.L2_1.scale(scale);
  80302. this.L20 = this.L20.scale(scale);
  80303. this.L21 = this.L21.scale(scale);
  80304. this.L22 = this.L22.scale(scale);
  80305. };
  80306. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  80307. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  80308. //
  80309. // E_lm = A_l * L_lm
  80310. //
  80311. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  80312. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  80313. // the scaling factors are given in equation 9.
  80314. // Constant (Band 0)
  80315. this.L00 = this.L00.scale(3.141593);
  80316. // Linear (Band 1)
  80317. this.L1_1 = this.L1_1.scale(2.094395);
  80318. this.L10 = this.L10.scale(2.094395);
  80319. this.L11 = this.L11.scale(2.094395);
  80320. // Quadratic (Band 2)
  80321. this.L2_2 = this.L2_2.scale(0.785398);
  80322. this.L2_1 = this.L2_1.scale(0.785398);
  80323. this.L20 = this.L20.scale(0.785398);
  80324. this.L21 = this.L21.scale(0.785398);
  80325. this.L22 = this.L22.scale(0.785398);
  80326. };
  80327. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  80328. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  80329. // L = (1/pi) * E * rho
  80330. //
  80331. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  80332. this.scale(1.0 / Math.PI);
  80333. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  80334. // (The pixel shader must apply albedo after texture fetches, etc).
  80335. };
  80336. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  80337. var result = new SphericalHarmonics();
  80338. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  80339. result.L1_1 = polynomial.y.scale(0.977204);
  80340. result.L10 = polynomial.z.scale(0.977204);
  80341. result.L11 = polynomial.x.scale(0.977204);
  80342. result.L2_2 = polynomial.xy.scale(1.16538);
  80343. result.L2_1 = polynomial.yz.scale(1.16538);
  80344. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  80345. result.L21 = polynomial.zx.scale(1.16538);
  80346. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  80347. result.scale(Math.PI);
  80348. return result;
  80349. };
  80350. return SphericalHarmonics;
  80351. }());
  80352. BABYLON.SphericalHarmonics = SphericalHarmonics;
  80353. })(BABYLON || (BABYLON = {}));
  80354. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  80355. var BABYLON;
  80356. (function (BABYLON) {
  80357. var FileFaceOrientation = /** @class */ (function () {
  80358. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  80359. this.name = name;
  80360. this.worldAxisForNormal = worldAxisForNormal;
  80361. this.worldAxisForFileX = worldAxisForFileX;
  80362. this.worldAxisForFileY = worldAxisForFileY;
  80363. }
  80364. return FileFaceOrientation;
  80365. }());
  80366. ;
  80367. /**
  80368. * Helper class dealing with the extraction of spherical polynomial dataArray
  80369. * from a cube map.
  80370. */
  80371. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  80372. function CubeMapToSphericalPolynomialTools() {
  80373. }
  80374. /**
  80375. * Converts a texture to the according Spherical Polynomial data.
  80376. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80377. *
  80378. * @param texture The texture to extract the information from.
  80379. * @return The Spherical Polynomial data.
  80380. */
  80381. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  80382. if (!texture.isCube) {
  80383. // Only supports cube Textures currently.
  80384. return null;
  80385. }
  80386. var size = texture.getSize().width;
  80387. var right = texture.readPixels(0);
  80388. var left = texture.readPixels(1);
  80389. var up;
  80390. var down;
  80391. if (texture.isRenderTarget) {
  80392. up = texture.readPixels(3);
  80393. down = texture.readPixels(2);
  80394. }
  80395. else {
  80396. up = texture.readPixels(2);
  80397. down = texture.readPixels(3);
  80398. }
  80399. var front = texture.readPixels(4);
  80400. var back = texture.readPixels(5);
  80401. var gammaSpace = texture.gammaSpace;
  80402. // Always read as RGBA.
  80403. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  80404. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80405. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80406. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80407. }
  80408. var cubeInfo = {
  80409. size: size,
  80410. right: right,
  80411. left: left,
  80412. up: up,
  80413. down: down,
  80414. front: front,
  80415. back: back,
  80416. format: format,
  80417. type: type,
  80418. gammaSpace: gammaSpace,
  80419. };
  80420. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  80421. };
  80422. /**
  80423. * Converts a cubemap to the according Spherical Polynomial data.
  80424. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80425. *
  80426. * @param cubeInfo The Cube map to extract the information from.
  80427. * @return The Spherical Polynomial data.
  80428. */
  80429. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  80430. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  80431. var totalSolidAngle = 0.0;
  80432. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  80433. var du = 2.0 / cubeInfo.size;
  80434. var dv = du;
  80435. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  80436. var minUV = du * 0.5 - 1.0;
  80437. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  80438. var fileFace = this.FileFaces[faceIndex];
  80439. var dataArray = cubeInfo[fileFace.name];
  80440. var v = minUV;
  80441. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  80442. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  80443. // Because SP is still linear, so summation is fine in that basis.
  80444. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  80445. for (var y = 0; y < cubeInfo.size; y++) {
  80446. var u = minUV;
  80447. for (var x = 0; x < cubeInfo.size; x++) {
  80448. // World direction (not normalised)
  80449. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  80450. worldDirection.normalize();
  80451. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  80452. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  80453. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  80454. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  80455. // Handle Integer types.
  80456. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80457. r /= 255;
  80458. g /= 255;
  80459. b /= 255;
  80460. }
  80461. // Handle Gamma space textures.
  80462. if (cubeInfo.gammaSpace) {
  80463. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  80464. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  80465. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  80466. }
  80467. var color = new BABYLON.Color3(r, g, b);
  80468. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  80469. totalSolidAngle += deltaSolidAngle;
  80470. u += du;
  80471. }
  80472. v += dv;
  80473. }
  80474. }
  80475. // Solid angle for entire sphere is 4*pi
  80476. var sphereSolidAngle = 4.0 * Math.PI;
  80477. // Adjust the solid angle to allow for how many faces we processed.
  80478. var facesProcessed = 6.0;
  80479. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  80480. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  80481. // This is needed because the numerical integration over the cube uses a
  80482. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  80483. // and also to compensate for accumulative error due to float precision in the summation.
  80484. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  80485. sphericalHarmonics.scale(correctionFactor);
  80486. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  80487. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  80488. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  80489. };
  80490. CubeMapToSphericalPolynomialTools.FileFaces = [
  80491. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  80492. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  80493. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  80494. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  80495. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  80496. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  80497. ];
  80498. return CubeMapToSphericalPolynomialTools;
  80499. }());
  80500. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  80501. })(BABYLON || (BABYLON = {}));
  80502. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  80503. var BABYLON;
  80504. (function (BABYLON) {
  80505. /**
  80506. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  80507. */
  80508. var PanoramaToCubeMapTools = /** @class */ (function () {
  80509. function PanoramaToCubeMapTools() {
  80510. }
  80511. /**
  80512. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  80513. *
  80514. * @param float32Array The source data.
  80515. * @param inputWidth The width of the input panorama.
  80516. * @param inputhHeight The height of the input panorama.
  80517. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  80518. * @return The cubemap data
  80519. */
  80520. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  80521. if (!float32Array) {
  80522. throw "ConvertPanoramaToCubemap: input cannot be null";
  80523. }
  80524. if (float32Array.length != inputWidth * inputHeight * 3) {
  80525. throw "ConvertPanoramaToCubemap: input size is wrong";
  80526. }
  80527. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  80528. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  80529. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  80530. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  80531. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  80532. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  80533. return {
  80534. front: textureFront,
  80535. back: textureBack,
  80536. left: textureLeft,
  80537. right: textureRight,
  80538. up: textureUp,
  80539. down: textureDown,
  80540. size: size,
  80541. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  80542. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  80543. gammaSpace: false,
  80544. };
  80545. };
  80546. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  80547. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  80548. var textureArray = new Float32Array(buffer);
  80549. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  80550. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  80551. var dy = 1 / texSize;
  80552. var fy = 0;
  80553. for (var y = 0; y < texSize; y++) {
  80554. var xv1 = faceData[0];
  80555. var xv2 = faceData[2];
  80556. for (var x = 0; x < texSize; x++) {
  80557. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  80558. v.normalize();
  80559. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  80560. // 3 channels per pixels
  80561. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  80562. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  80563. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  80564. xv1 = xv1.add(rotDX1);
  80565. xv2 = xv2.add(rotDX2);
  80566. }
  80567. fy += dy;
  80568. }
  80569. return textureArray;
  80570. };
  80571. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  80572. var theta = Math.atan2(vDir.z, vDir.x);
  80573. var phi = Math.acos(vDir.y);
  80574. while (theta < -Math.PI)
  80575. theta += 2 * Math.PI;
  80576. while (theta > Math.PI)
  80577. theta -= 2 * Math.PI;
  80578. var dx = theta / Math.PI;
  80579. var dy = phi / Math.PI;
  80580. // recenter.
  80581. dx = dx * 0.5 + 0.5;
  80582. var px = Math.round(dx * inputWidth);
  80583. if (px < 0)
  80584. px = 0;
  80585. else if (px >= inputWidth)
  80586. px = inputWidth - 1;
  80587. var py = Math.round(dy * inputHeight);
  80588. if (py < 0)
  80589. py = 0;
  80590. else if (py >= inputHeight)
  80591. py = inputHeight - 1;
  80592. var inputY = (inputHeight - py - 1);
  80593. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  80594. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  80595. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  80596. return {
  80597. r: r,
  80598. g: g,
  80599. b: b
  80600. };
  80601. };
  80602. PanoramaToCubeMapTools.FACE_FRONT = [
  80603. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80604. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80605. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80606. new BABYLON.Vector3(1.0, 1.0, -1.0)
  80607. ];
  80608. PanoramaToCubeMapTools.FACE_BACK = [
  80609. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80610. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80611. new BABYLON.Vector3(1.0, 1.0, 1.0),
  80612. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  80613. ];
  80614. PanoramaToCubeMapTools.FACE_RIGHT = [
  80615. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80616. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80617. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80618. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80619. ];
  80620. PanoramaToCubeMapTools.FACE_LEFT = [
  80621. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80622. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80623. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80624. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  80625. ];
  80626. PanoramaToCubeMapTools.FACE_DOWN = [
  80627. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80628. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80629. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80630. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80631. ];
  80632. PanoramaToCubeMapTools.FACE_UP = [
  80633. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80634. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80635. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80636. new BABYLON.Vector3(1.0, -1.0, -1.0)
  80637. ];
  80638. return PanoramaToCubeMapTools;
  80639. }());
  80640. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  80641. })(BABYLON || (BABYLON = {}));
  80642. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  80643. var BABYLON;
  80644. (function (BABYLON) {
  80645. ;
  80646. /**
  80647. * This groups tools to convert HDR texture to native colors array.
  80648. */
  80649. var HDRTools = /** @class */ (function () {
  80650. function HDRTools() {
  80651. }
  80652. HDRTools.Ldexp = function (mantissa, exponent) {
  80653. if (exponent > 1023) {
  80654. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  80655. }
  80656. if (exponent < -1074) {
  80657. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  80658. }
  80659. return mantissa * Math.pow(2, exponent);
  80660. };
  80661. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  80662. if (exponent > 0) { /*nonzero pixel*/
  80663. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  80664. float32array[index + 0] = red * exponent;
  80665. float32array[index + 1] = green * exponent;
  80666. float32array[index + 2] = blue * exponent;
  80667. }
  80668. else {
  80669. float32array[index + 0] = 0;
  80670. float32array[index + 1] = 0;
  80671. float32array[index + 2] = 0;
  80672. }
  80673. };
  80674. HDRTools.readStringLine = function (uint8array, startIndex) {
  80675. var line = "";
  80676. var character = "";
  80677. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  80678. character = String.fromCharCode(uint8array[i]);
  80679. if (character == "\n") {
  80680. break;
  80681. }
  80682. line += character;
  80683. }
  80684. return line;
  80685. };
  80686. /**
  80687. * Reads header information from an RGBE texture stored in a native array.
  80688. * More information on this format are available here:
  80689. * https://en.wikipedia.org/wiki/RGBE_image_format
  80690. *
  80691. * @param uint8array The binary file stored in native array.
  80692. * @return The header information.
  80693. */
  80694. HDRTools.RGBE_ReadHeader = function (uint8array) {
  80695. var height = 0;
  80696. var width = 0;
  80697. var line = this.readStringLine(uint8array, 0);
  80698. if (line[0] != '#' || line[1] != '?') {
  80699. throw "Bad HDR Format.";
  80700. }
  80701. var endOfHeader = false;
  80702. var findFormat = false;
  80703. var lineIndex = 0;
  80704. do {
  80705. lineIndex += (line.length + 1);
  80706. line = this.readStringLine(uint8array, lineIndex);
  80707. if (line == "FORMAT=32-bit_rle_rgbe") {
  80708. findFormat = true;
  80709. }
  80710. else if (line.length == 0) {
  80711. endOfHeader = true;
  80712. }
  80713. } while (!endOfHeader);
  80714. if (!findFormat) {
  80715. throw "HDR Bad header format, unsupported FORMAT";
  80716. }
  80717. lineIndex += (line.length + 1);
  80718. line = this.readStringLine(uint8array, lineIndex);
  80719. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  80720. var match = sizeRegexp.exec(line);
  80721. // TODO. Support +Y and -X if needed.
  80722. if (!match || match.length < 3) {
  80723. throw "HDR Bad header format, no size";
  80724. }
  80725. width = parseInt(match[2]);
  80726. height = parseInt(match[1]);
  80727. if (width < 8 || width > 0x7fff) {
  80728. throw "HDR Bad header format, unsupported size";
  80729. }
  80730. lineIndex += (line.length + 1);
  80731. return {
  80732. height: height,
  80733. width: width,
  80734. dataPosition: lineIndex
  80735. };
  80736. };
  80737. /**
  80738. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  80739. * This RGBE texture needs to store the information as a panorama.
  80740. *
  80741. * More information on this format are available here:
  80742. * https://en.wikipedia.org/wiki/RGBE_image_format
  80743. *
  80744. * @param buffer The binary file stored in an array buffer.
  80745. * @param size The expected size of the extracted cubemap.
  80746. * @return The Cube Map information.
  80747. */
  80748. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  80749. var uint8array = new Uint8Array(buffer);
  80750. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  80751. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80752. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  80753. return cubeMapData;
  80754. };
  80755. /**
  80756. * Returns the pixels data extracted from an RGBE texture.
  80757. * This pixels will be stored left to right up to down in the R G B order in one array.
  80758. *
  80759. * More information on this format are available here:
  80760. * https://en.wikipedia.org/wiki/RGBE_image_format
  80761. *
  80762. * @param uint8array The binary file stored in an array buffer.
  80763. * @param hdrInfo The header information of the file.
  80764. * @return The pixels data in RGB right to left up to down order.
  80765. */
  80766. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  80767. // Keep for multi format supports.
  80768. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80769. };
  80770. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  80771. var num_scanlines = hdrInfo.height;
  80772. var scanline_width = hdrInfo.width;
  80773. var a, b, c, d, count;
  80774. var dataIndex = hdrInfo.dataPosition;
  80775. var index = 0, endIndex = 0, i = 0;
  80776. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  80777. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  80778. // 3 channels of 4 bytes per pixel in float.
  80779. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  80780. var resultArray = new Float32Array(resultBuffer);
  80781. // read in each successive scanline
  80782. while (num_scanlines > 0) {
  80783. a = uint8array[dataIndex++];
  80784. b = uint8array[dataIndex++];
  80785. c = uint8array[dataIndex++];
  80786. d = uint8array[dataIndex++];
  80787. if (a != 2 || b != 2 || (c & 0x80)) {
  80788. // this file is not run length encoded
  80789. throw "HDR Bad header format, not RLE";
  80790. }
  80791. if (((c << 8) | d) != scanline_width) {
  80792. throw "HDR Bad header format, wrong scan line width";
  80793. }
  80794. index = 0;
  80795. // read each of the four channels for the scanline into the buffer
  80796. for (i = 0; i < 4; i++) {
  80797. endIndex = (i + 1) * scanline_width;
  80798. while (index < endIndex) {
  80799. a = uint8array[dataIndex++];
  80800. b = uint8array[dataIndex++];
  80801. if (a > 128) {
  80802. // a run of the same value
  80803. count = a - 128;
  80804. if ((count == 0) || (count > endIndex - index)) {
  80805. throw "HDR Bad Format, bad scanline data (run)";
  80806. }
  80807. while (count-- > 0) {
  80808. scanLineArray[index++] = b;
  80809. }
  80810. }
  80811. else {
  80812. // a non-run
  80813. count = a;
  80814. if ((count == 0) || (count > endIndex - index)) {
  80815. throw "HDR Bad Format, bad scanline data (non-run)";
  80816. }
  80817. scanLineArray[index++] = b;
  80818. if (--count > 0) {
  80819. for (var j = 0; j < count; j++) {
  80820. scanLineArray[index++] = uint8array[dataIndex++];
  80821. }
  80822. }
  80823. }
  80824. }
  80825. }
  80826. // now convert data from buffer into floats
  80827. for (i = 0; i < scanline_width; i++) {
  80828. a = scanLineArray[i];
  80829. b = scanLineArray[i + scanline_width];
  80830. c = scanLineArray[i + 2 * scanline_width];
  80831. d = scanLineArray[i + 3 * scanline_width];
  80832. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  80833. }
  80834. num_scanlines--;
  80835. }
  80836. return resultArray;
  80837. };
  80838. return HDRTools;
  80839. }());
  80840. BABYLON.HDRTools = HDRTools;
  80841. })(BABYLON || (BABYLON = {}));
  80842. //# sourceMappingURL=babylon.hdr.js.map
  80843. var BABYLON;
  80844. (function (BABYLON) {
  80845. /**
  80846. * This represents a texture coming from an HDR input.
  80847. *
  80848. * The only supported format is currently panorama picture stored in RGBE format.
  80849. * Example of such files can be found on HDRLib: http://hdrlib.com/
  80850. */
  80851. var HDRCubeTexture = /** @class */ (function (_super) {
  80852. __extends(HDRCubeTexture, _super);
  80853. /**
  80854. * Instantiates an HDRTexture from the following parameters.
  80855. *
  80856. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  80857. * @param scene The scene the texture will be used in
  80858. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  80859. * @param noMipmap Forces to not generate the mipmap if true
  80860. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  80861. * @param gammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  80862. * @param reserved Reserved flag for internal use.
  80863. */
  80864. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  80865. if (noMipmap === void 0) { noMipmap = false; }
  80866. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80867. if (gammaSpace === void 0) { gammaSpace = false; }
  80868. if (reserved === void 0) { reserved = false; }
  80869. if (onLoad === void 0) { onLoad = null; }
  80870. if (onError === void 0) { onError = null; }
  80871. var _this = _super.call(this, scene) || this;
  80872. _this._generateHarmonics = true;
  80873. _this._onLoad = null;
  80874. _this._onError = null;
  80875. /**
  80876. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  80877. */
  80878. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  80879. _this._isBlocking = true;
  80880. _this._rotationY = 0;
  80881. /**
  80882. * Gets or sets the center of the bounding box associated with the cube texture
  80883. * It must define where the camera used to render the texture was set
  80884. */
  80885. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  80886. if (!url) {
  80887. return _this;
  80888. }
  80889. _this.name = url;
  80890. _this.url = url;
  80891. _this.hasAlpha = false;
  80892. _this.isCube = true;
  80893. _this._textureMatrix = BABYLON.Matrix.Identity();
  80894. _this._onLoad = onLoad;
  80895. _this._onError = onError;
  80896. _this.gammaSpace = gammaSpace;
  80897. _this._noMipmap = noMipmap;
  80898. _this._size = size;
  80899. _this._texture = _this._getFromCache(url, _this._noMipmap);
  80900. if (!_this._texture) {
  80901. if (!scene.useDelayedTextureLoading) {
  80902. _this.loadTexture();
  80903. }
  80904. else {
  80905. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80906. }
  80907. }
  80908. return _this;
  80909. }
  80910. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  80911. /**
  80912. * Gets wether or not the texture is blocking during loading.
  80913. */
  80914. get: function () {
  80915. return this._isBlocking;
  80916. },
  80917. /**
  80918. * Sets wether or not the texture is blocking during loading.
  80919. */
  80920. set: function (value) {
  80921. this._isBlocking = value;
  80922. },
  80923. enumerable: true,
  80924. configurable: true
  80925. });
  80926. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  80927. /**
  80928. * Gets texture matrix rotation angle around Y axis radians.
  80929. */
  80930. get: function () {
  80931. return this._rotationY;
  80932. },
  80933. /**
  80934. * Sets texture matrix rotation angle around Y axis in radians.
  80935. */
  80936. set: function (value) {
  80937. this._rotationY = value;
  80938. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  80939. },
  80940. enumerable: true,
  80941. configurable: true
  80942. });
  80943. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  80944. get: function () {
  80945. return this._boundingBoxSize;
  80946. },
  80947. /**
  80948. * Gets or sets the size of the bounding box associated with the cube texture
  80949. * When defined, the cubemap will switch to local mode
  80950. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  80951. * @example https://www.babylonjs-playground.com/#RNASML
  80952. */
  80953. set: function (value) {
  80954. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  80955. return;
  80956. }
  80957. this._boundingBoxSize = value;
  80958. var scene = this.getScene();
  80959. if (scene) {
  80960. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  80961. }
  80962. },
  80963. enumerable: true,
  80964. configurable: true
  80965. });
  80966. /**
  80967. * Occurs when the file is raw .hdr file.
  80968. */
  80969. HDRCubeTexture.prototype.loadTexture = function () {
  80970. var _this = this;
  80971. var callback = function (buffer) {
  80972. var scene = _this.getScene();
  80973. if (!scene) {
  80974. return null;
  80975. }
  80976. // Extract the raw linear data.
  80977. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  80978. // Generate harmonics if needed.
  80979. if (_this._generateHarmonics) {
  80980. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  80981. _this.sphericalPolynomial = sphericalPolynomial;
  80982. }
  80983. var results = [];
  80984. var byteArray = null;
  80985. // Push each faces.
  80986. for (var j = 0; j < 6; j++) {
  80987. // Create uintarray fallback.
  80988. if (!scene.getEngine().getCaps().textureFloat) {
  80989. // 3 channels of 1 bytes per pixel in bytes.
  80990. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  80991. byteArray = new Uint8Array(byteBuffer);
  80992. }
  80993. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  80994. // If special cases.
  80995. if (_this.gammaSpace || byteArray) {
  80996. for (var i = 0; i < _this._size * _this._size; i++) {
  80997. // Put in gamma space if requested.
  80998. if (_this.gammaSpace) {
  80999. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  81000. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  81001. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  81002. }
  81003. // Convert to int texture for fallback.
  81004. if (byteArray) {
  81005. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  81006. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  81007. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  81008. // May use luminance instead if the result is not accurate.
  81009. var max = Math.max(Math.max(r, g), b);
  81010. if (max > 255) {
  81011. var scale = 255 / max;
  81012. r *= scale;
  81013. g *= scale;
  81014. b *= scale;
  81015. }
  81016. byteArray[(i * 3) + 0] = r;
  81017. byteArray[(i * 3) + 1] = g;
  81018. byteArray[(i * 3) + 2] = b;
  81019. }
  81020. }
  81021. }
  81022. if (byteArray) {
  81023. results.push(byteArray);
  81024. }
  81025. else {
  81026. results.push(dataFace);
  81027. }
  81028. }
  81029. return results;
  81030. };
  81031. var scene = this.getScene();
  81032. if (scene) {
  81033. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, null, this._onLoad, this._onError);
  81034. }
  81035. };
  81036. HDRCubeTexture.prototype.clone = function () {
  81037. var scene = this.getScene();
  81038. if (!scene) {
  81039. return this;
  81040. }
  81041. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  81042. // Base texture
  81043. newTexture.level = this.level;
  81044. newTexture.wrapU = this.wrapU;
  81045. newTexture.wrapV = this.wrapV;
  81046. newTexture.coordinatesIndex = this.coordinatesIndex;
  81047. newTexture.coordinatesMode = this.coordinatesMode;
  81048. return newTexture;
  81049. };
  81050. // Methods
  81051. HDRCubeTexture.prototype.delayLoad = function () {
  81052. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  81053. return;
  81054. }
  81055. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  81056. this._texture = this._getFromCache(this.url, this._noMipmap);
  81057. if (!this._texture) {
  81058. this.loadTexture();
  81059. }
  81060. };
  81061. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  81062. return this._textureMatrix;
  81063. };
  81064. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  81065. this._textureMatrix = value;
  81066. };
  81067. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  81068. var texture = null;
  81069. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  81070. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  81071. texture.name = parsedTexture.name;
  81072. texture.hasAlpha = parsedTexture.hasAlpha;
  81073. texture.level = parsedTexture.level;
  81074. texture.coordinatesMode = parsedTexture.coordinatesMode;
  81075. texture.isBlocking = parsedTexture.isBlocking;
  81076. }
  81077. if (texture) {
  81078. if (parsedTexture.boundingBoxPosition) {
  81079. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  81080. }
  81081. if (parsedTexture.boundingBoxSize) {
  81082. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  81083. }
  81084. if (parsedTexture.rotationY) {
  81085. texture.rotationY = parsedTexture.rotationY;
  81086. }
  81087. }
  81088. return texture;
  81089. };
  81090. HDRCubeTexture.prototype.serialize = function () {
  81091. if (!this.name) {
  81092. return null;
  81093. }
  81094. var serializationObject = {};
  81095. serializationObject.name = this.name;
  81096. serializationObject.hasAlpha = this.hasAlpha;
  81097. serializationObject.isCube = true;
  81098. serializationObject.level = this.level;
  81099. serializationObject.size = this._size;
  81100. serializationObject.coordinatesMode = this.coordinatesMode;
  81101. serializationObject.useInGammaSpace = this.gammaSpace;
  81102. serializationObject.generateHarmonics = this._generateHarmonics;
  81103. serializationObject.customType = "BABYLON.HDRCubeTexture";
  81104. serializationObject.noMipmap = this._noMipmap;
  81105. serializationObject.isBlocking = this._isBlocking;
  81106. serializationObject.rotationY = this._rotationY;
  81107. return serializationObject;
  81108. };
  81109. HDRCubeTexture._facesMapping = [
  81110. "right",
  81111. "left",
  81112. "up",
  81113. "down",
  81114. "front",
  81115. "back"
  81116. ];
  81117. return HDRCubeTexture;
  81118. }(BABYLON.BaseTexture));
  81119. BABYLON.HDRCubeTexture = HDRCubeTexture;
  81120. })(BABYLON || (BABYLON = {}));
  81121. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  81122. var BABYLON;
  81123. (function (BABYLON) {
  81124. var IndexedVector2 = /** @class */ (function (_super) {
  81125. __extends(IndexedVector2, _super);
  81126. function IndexedVector2(original, index) {
  81127. var _this = _super.call(this, original.x, original.y) || this;
  81128. _this.index = index;
  81129. return _this;
  81130. }
  81131. return IndexedVector2;
  81132. }(BABYLON.Vector2));
  81133. var PolygonPoints = /** @class */ (function () {
  81134. function PolygonPoints() {
  81135. this.elements = new Array();
  81136. }
  81137. PolygonPoints.prototype.add = function (originalPoints) {
  81138. var _this = this;
  81139. var result = new Array();
  81140. originalPoints.forEach(function (point) {
  81141. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  81142. var newPoint = new IndexedVector2(point, _this.elements.length);
  81143. result.push(newPoint);
  81144. _this.elements.push(newPoint);
  81145. }
  81146. });
  81147. return result;
  81148. };
  81149. PolygonPoints.prototype.computeBounds = function () {
  81150. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  81151. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  81152. this.elements.forEach(function (point) {
  81153. // x
  81154. if (point.x < lmin.x) {
  81155. lmin.x = point.x;
  81156. }
  81157. else if (point.x > lmax.x) {
  81158. lmax.x = point.x;
  81159. }
  81160. // y
  81161. if (point.y < lmin.y) {
  81162. lmin.y = point.y;
  81163. }
  81164. else if (point.y > lmax.y) {
  81165. lmax.y = point.y;
  81166. }
  81167. });
  81168. return {
  81169. min: lmin,
  81170. max: lmax,
  81171. width: lmax.x - lmin.x,
  81172. height: lmax.y - lmin.y
  81173. };
  81174. };
  81175. return PolygonPoints;
  81176. }());
  81177. var Polygon = /** @class */ (function () {
  81178. function Polygon() {
  81179. }
  81180. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  81181. return [
  81182. new BABYLON.Vector2(xmin, ymin),
  81183. new BABYLON.Vector2(xmax, ymin),
  81184. new BABYLON.Vector2(xmax, ymax),
  81185. new BABYLON.Vector2(xmin, ymax)
  81186. ];
  81187. };
  81188. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  81189. if (cx === void 0) { cx = 0; }
  81190. if (cy === void 0) { cy = 0; }
  81191. if (numberOfSides === void 0) { numberOfSides = 32; }
  81192. var result = new Array();
  81193. var angle = 0;
  81194. var increment = (Math.PI * 2) / numberOfSides;
  81195. for (var i = 0; i < numberOfSides; i++) {
  81196. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  81197. angle -= increment;
  81198. }
  81199. return result;
  81200. };
  81201. Polygon.Parse = function (input) {
  81202. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  81203. var i, result = [];
  81204. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  81205. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  81206. }
  81207. return result;
  81208. };
  81209. Polygon.StartingAt = function (x, y) {
  81210. return BABYLON.Path2.StartingAt(x, y);
  81211. };
  81212. return Polygon;
  81213. }());
  81214. BABYLON.Polygon = Polygon;
  81215. var PolygonMeshBuilder = /** @class */ (function () {
  81216. function PolygonMeshBuilder(name, contours, scene) {
  81217. this._points = new PolygonPoints();
  81218. this._outlinepoints = new PolygonPoints();
  81219. this._holes = new Array();
  81220. this._epoints = new Array();
  81221. this._eholes = new Array();
  81222. this._name = name;
  81223. this._scene = scene;
  81224. var points;
  81225. if (contours instanceof BABYLON.Path2) {
  81226. points = contours.getPoints();
  81227. }
  81228. else {
  81229. points = contours;
  81230. }
  81231. this._addToepoint(points);
  81232. this._points.add(points);
  81233. this._outlinepoints.add(points);
  81234. if (typeof earcut === 'undefined') {
  81235. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  81236. }
  81237. }
  81238. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  81239. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  81240. var p = points_1[_i];
  81241. this._epoints.push(p.x, p.y);
  81242. }
  81243. };
  81244. PolygonMeshBuilder.prototype.addHole = function (hole) {
  81245. this._points.add(hole);
  81246. var holepoints = new PolygonPoints();
  81247. holepoints.add(hole);
  81248. this._holes.push(holepoints);
  81249. this._eholes.push(this._epoints.length / 2);
  81250. this._addToepoint(hole);
  81251. return this;
  81252. };
  81253. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  81254. var _this = this;
  81255. if (updatable === void 0) { updatable = false; }
  81256. if (depth === void 0) { depth = 0; }
  81257. var result = new BABYLON.Mesh(this._name, this._scene);
  81258. var normals = new Array();
  81259. var positions = new Array();
  81260. var uvs = new Array();
  81261. var bounds = this._points.computeBounds();
  81262. this._points.elements.forEach(function (p) {
  81263. normals.push(0, 1.0, 0);
  81264. positions.push(p.x, 0, p.y);
  81265. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  81266. });
  81267. var indices = new Array();
  81268. var res = earcut(this._epoints, this._eholes, 2);
  81269. for (var i = 0; i < res.length; i++) {
  81270. indices.push(res[i]);
  81271. }
  81272. if (depth > 0) {
  81273. var positionscount = (positions.length / 3); //get the current pointcount
  81274. this._points.elements.forEach(function (p) {
  81275. normals.push(0, -1.0, 0);
  81276. positions.push(p.x, -depth, p.y);
  81277. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  81278. });
  81279. var totalCount = indices.length;
  81280. for (var i = 0; i < totalCount; i += 3) {
  81281. var i0 = indices[i + 0];
  81282. var i1 = indices[i + 1];
  81283. var i2 = indices[i + 2];
  81284. indices.push(i2 + positionscount);
  81285. indices.push(i1 + positionscount);
  81286. indices.push(i0 + positionscount);
  81287. }
  81288. //Add the sides
  81289. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  81290. this._holes.forEach(function (hole) {
  81291. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  81292. });
  81293. }
  81294. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  81295. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  81296. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  81297. result.setIndices(indices);
  81298. return result;
  81299. };
  81300. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  81301. var StartIndex = positions.length / 3;
  81302. var ulength = 0;
  81303. for (var i = 0; i < points.elements.length; i++) {
  81304. var p = points.elements[i];
  81305. var p1;
  81306. if ((i + 1) > points.elements.length - 1) {
  81307. p1 = points.elements[0];
  81308. }
  81309. else {
  81310. p1 = points.elements[i + 1];
  81311. }
  81312. positions.push(p.x, 0, p.y);
  81313. positions.push(p.x, -depth, p.y);
  81314. positions.push(p1.x, 0, p1.y);
  81315. positions.push(p1.x, -depth, p1.y);
  81316. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  81317. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  81318. var v3 = v2.subtract(v1);
  81319. var v4 = new BABYLON.Vector3(0, 1, 0);
  81320. var vn = BABYLON.Vector3.Cross(v3, v4);
  81321. vn = vn.normalize();
  81322. uvs.push(ulength / bounds.width, 0);
  81323. uvs.push(ulength / bounds.width, 1);
  81324. ulength += v3.length();
  81325. uvs.push((ulength / bounds.width), 0);
  81326. uvs.push((ulength / bounds.width), 1);
  81327. if (!flip) {
  81328. normals.push(-vn.x, -vn.y, -vn.z);
  81329. normals.push(-vn.x, -vn.y, -vn.z);
  81330. normals.push(-vn.x, -vn.y, -vn.z);
  81331. normals.push(-vn.x, -vn.y, -vn.z);
  81332. indices.push(StartIndex);
  81333. indices.push(StartIndex + 1);
  81334. indices.push(StartIndex + 2);
  81335. indices.push(StartIndex + 1);
  81336. indices.push(StartIndex + 3);
  81337. indices.push(StartIndex + 2);
  81338. }
  81339. else {
  81340. normals.push(vn.x, vn.y, vn.z);
  81341. normals.push(vn.x, vn.y, vn.z);
  81342. normals.push(vn.x, vn.y, vn.z);
  81343. normals.push(vn.x, vn.y, vn.z);
  81344. indices.push(StartIndex);
  81345. indices.push(StartIndex + 2);
  81346. indices.push(StartIndex + 1);
  81347. indices.push(StartIndex + 1);
  81348. indices.push(StartIndex + 2);
  81349. indices.push(StartIndex + 3);
  81350. }
  81351. StartIndex += 4;
  81352. }
  81353. ;
  81354. };
  81355. return PolygonMeshBuilder;
  81356. }());
  81357. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  81358. })(BABYLON || (BABYLON = {}));
  81359. //# sourceMappingURL=babylon.polygonMesh.js.map
  81360. var BABYLON;
  81361. (function (BABYLON) {
  81362. // Unique ID when we import meshes from Babylon to CSG
  81363. var currentCSGMeshId = 0;
  81364. // # class Vertex
  81365. // Represents a vertex of a polygon. Use your own vertex class instead of this
  81366. // one to provide additional features like texture coordinates and vertex
  81367. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  81368. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  81369. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  81370. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  81371. // is not used anywhere else.
  81372. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  81373. var Vertex = /** @class */ (function () {
  81374. function Vertex(pos, normal, uv) {
  81375. this.pos = pos;
  81376. this.normal = normal;
  81377. this.uv = uv;
  81378. }
  81379. Vertex.prototype.clone = function () {
  81380. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  81381. };
  81382. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  81383. // orientation of a polygon is flipped.
  81384. Vertex.prototype.flip = function () {
  81385. this.normal = this.normal.scale(-1);
  81386. };
  81387. // Create a new vertex between this vertex and `other` by linearly
  81388. // interpolating all properties using a parameter of `t`. Subclasses should
  81389. // override this to interpolate additional properties.
  81390. Vertex.prototype.interpolate = function (other, t) {
  81391. 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));
  81392. };
  81393. return Vertex;
  81394. }());
  81395. // # class Plane
  81396. // Represents a plane in 3D space.
  81397. var Plane = /** @class */ (function () {
  81398. function Plane(normal, w) {
  81399. this.normal = normal;
  81400. this.w = w;
  81401. }
  81402. Plane.FromPoints = function (a, b, c) {
  81403. var v0 = c.subtract(a);
  81404. var v1 = b.subtract(a);
  81405. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  81406. return null;
  81407. }
  81408. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  81409. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  81410. };
  81411. Plane.prototype.clone = function () {
  81412. return new Plane(this.normal.clone(), this.w);
  81413. };
  81414. Plane.prototype.flip = function () {
  81415. this.normal.scaleInPlace(-1);
  81416. this.w = -this.w;
  81417. };
  81418. // Split `polygon` by this plane if needed, then put the polygon or polygon
  81419. // fragments in the appropriate lists. Coplanar polygons go into either
  81420. // `coplanarFront` or `coplanarBack` depending on their orientation with
  81421. // respect to this plane. Polygons in front or in back of this plane go into
  81422. // either `front` or `back`.
  81423. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  81424. var COPLANAR = 0;
  81425. var FRONT = 1;
  81426. var BACK = 2;
  81427. var SPANNING = 3;
  81428. // Classify each point as well as the entire polygon into one of the above
  81429. // four classes.
  81430. var polygonType = 0;
  81431. var types = [];
  81432. var i;
  81433. var t;
  81434. for (i = 0; i < polygon.vertices.length; i++) {
  81435. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  81436. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  81437. polygonType |= type;
  81438. types.push(type);
  81439. }
  81440. // Put the polygon in the correct list, splitting it when necessary.
  81441. switch (polygonType) {
  81442. case COPLANAR:
  81443. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  81444. break;
  81445. case FRONT:
  81446. front.push(polygon);
  81447. break;
  81448. case BACK:
  81449. back.push(polygon);
  81450. break;
  81451. case SPANNING:
  81452. var f = [], b = [];
  81453. for (i = 0; i < polygon.vertices.length; i++) {
  81454. var j = (i + 1) % polygon.vertices.length;
  81455. var ti = types[i], tj = types[j];
  81456. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  81457. if (ti !== BACK)
  81458. f.push(vi);
  81459. if (ti !== FRONT)
  81460. b.push(ti !== BACK ? vi.clone() : vi);
  81461. if ((ti | tj) === SPANNING) {
  81462. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  81463. var v = vi.interpolate(vj, t);
  81464. f.push(v);
  81465. b.push(v.clone());
  81466. }
  81467. }
  81468. var poly;
  81469. if (f.length >= 3) {
  81470. poly = new Polygon(f, polygon.shared);
  81471. if (poly.plane)
  81472. front.push(poly);
  81473. }
  81474. if (b.length >= 3) {
  81475. poly = new Polygon(b, polygon.shared);
  81476. if (poly.plane)
  81477. back.push(poly);
  81478. }
  81479. break;
  81480. }
  81481. };
  81482. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  81483. // point is on the plane.
  81484. Plane.EPSILON = 1e-5;
  81485. return Plane;
  81486. }());
  81487. // # class Polygon
  81488. // Represents a convex polygon. The vertices used to initialize a polygon must
  81489. // be coplanar and form a convex loop.
  81490. //
  81491. // Each convex polygon has a `shared` property, which is shared between all
  81492. // polygons that are clones of each other or were split from the same polygon.
  81493. // This can be used to define per-polygon properties (such as surface color).
  81494. var Polygon = /** @class */ (function () {
  81495. function Polygon(vertices, shared) {
  81496. this.vertices = vertices;
  81497. this.shared = shared;
  81498. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  81499. }
  81500. Polygon.prototype.clone = function () {
  81501. var vertices = this.vertices.map(function (v) { return v.clone(); });
  81502. return new Polygon(vertices, this.shared);
  81503. };
  81504. Polygon.prototype.flip = function () {
  81505. this.vertices.reverse().map(function (v) { v.flip(); });
  81506. this.plane.flip();
  81507. };
  81508. return Polygon;
  81509. }());
  81510. // # class Node
  81511. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  81512. // by picking a polygon to split along. That polygon (and all other coplanar
  81513. // polygons) are added directly to that node and the other polygons are added to
  81514. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  81515. // no distinction between internal and leaf nodes.
  81516. var Node = /** @class */ (function () {
  81517. function Node(polygons) {
  81518. this.plane = null;
  81519. this.front = null;
  81520. this.back = null;
  81521. this.polygons = new Array();
  81522. if (polygons) {
  81523. this.build(polygons);
  81524. }
  81525. }
  81526. Node.prototype.clone = function () {
  81527. var node = new Node();
  81528. node.plane = this.plane && this.plane.clone();
  81529. node.front = this.front && this.front.clone();
  81530. node.back = this.back && this.back.clone();
  81531. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  81532. return node;
  81533. };
  81534. // Convert solid space to empty space and empty space to solid space.
  81535. Node.prototype.invert = function () {
  81536. for (var i = 0; i < this.polygons.length; i++) {
  81537. this.polygons[i].flip();
  81538. }
  81539. if (this.plane) {
  81540. this.plane.flip();
  81541. }
  81542. if (this.front) {
  81543. this.front.invert();
  81544. }
  81545. if (this.back) {
  81546. this.back.invert();
  81547. }
  81548. var temp = this.front;
  81549. this.front = this.back;
  81550. this.back = temp;
  81551. };
  81552. // Recursively remove all polygons in `polygons` that are inside this BSP
  81553. // tree.
  81554. Node.prototype.clipPolygons = function (polygons) {
  81555. if (!this.plane)
  81556. return polygons.slice();
  81557. var front = new Array(), back = new Array();
  81558. for (var i = 0; i < polygons.length; i++) {
  81559. this.plane.splitPolygon(polygons[i], front, back, front, back);
  81560. }
  81561. if (this.front) {
  81562. front = this.front.clipPolygons(front);
  81563. }
  81564. if (this.back) {
  81565. back = this.back.clipPolygons(back);
  81566. }
  81567. else {
  81568. back = [];
  81569. }
  81570. return front.concat(back);
  81571. };
  81572. // Remove all polygons in this BSP tree that are inside the other BSP tree
  81573. // `bsp`.
  81574. Node.prototype.clipTo = function (bsp) {
  81575. this.polygons = bsp.clipPolygons(this.polygons);
  81576. if (this.front)
  81577. this.front.clipTo(bsp);
  81578. if (this.back)
  81579. this.back.clipTo(bsp);
  81580. };
  81581. // Return a list of all polygons in this BSP tree.
  81582. Node.prototype.allPolygons = function () {
  81583. var polygons = this.polygons.slice();
  81584. if (this.front)
  81585. polygons = polygons.concat(this.front.allPolygons());
  81586. if (this.back)
  81587. polygons = polygons.concat(this.back.allPolygons());
  81588. return polygons;
  81589. };
  81590. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  81591. // new polygons are filtered down to the bottom of the tree and become new
  81592. // nodes there. Each set of polygons is partitioned using the first polygon
  81593. // (no heuristic is used to pick a good split).
  81594. Node.prototype.build = function (polygons) {
  81595. if (!polygons.length)
  81596. return;
  81597. if (!this.plane)
  81598. this.plane = polygons[0].plane.clone();
  81599. var front = new Array(), back = new Array();
  81600. for (var i = 0; i < polygons.length; i++) {
  81601. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  81602. }
  81603. if (front.length) {
  81604. if (!this.front)
  81605. this.front = new Node();
  81606. this.front.build(front);
  81607. }
  81608. if (back.length) {
  81609. if (!this.back)
  81610. this.back = new Node();
  81611. this.back.build(back);
  81612. }
  81613. };
  81614. return Node;
  81615. }());
  81616. var CSG = /** @class */ (function () {
  81617. function CSG() {
  81618. this.polygons = new Array();
  81619. }
  81620. // Convert BABYLON.Mesh to BABYLON.CSG
  81621. CSG.FromMesh = function (mesh) {
  81622. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  81623. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  81624. if (mesh instanceof BABYLON.Mesh) {
  81625. mesh.computeWorldMatrix(true);
  81626. matrix = mesh.getWorldMatrix();
  81627. meshPosition = mesh.position.clone();
  81628. meshRotation = mesh.rotation.clone();
  81629. if (mesh.rotationQuaternion) {
  81630. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  81631. }
  81632. meshScaling = mesh.scaling.clone();
  81633. }
  81634. else {
  81635. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  81636. }
  81637. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  81638. var subMeshes = mesh.subMeshes;
  81639. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  81640. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  81641. vertices = [];
  81642. for (var j = 0; j < 3; j++) {
  81643. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  81644. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  81645. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  81646. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  81647. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  81648. vertex = new Vertex(position, normal, uv);
  81649. vertices.push(vertex);
  81650. }
  81651. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  81652. // To handle the case of degenerated triangle
  81653. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  81654. if (polygon.plane)
  81655. polygons.push(polygon);
  81656. }
  81657. }
  81658. var csg = CSG.FromPolygons(polygons);
  81659. csg.matrix = matrix;
  81660. csg.position = meshPosition;
  81661. csg.rotation = meshRotation;
  81662. csg.scaling = meshScaling;
  81663. csg.rotationQuaternion = meshRotationQuaternion;
  81664. currentCSGMeshId++;
  81665. return csg;
  81666. };
  81667. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  81668. CSG.FromPolygons = function (polygons) {
  81669. var csg = new CSG();
  81670. csg.polygons = polygons;
  81671. return csg;
  81672. };
  81673. CSG.prototype.clone = function () {
  81674. var csg = new CSG();
  81675. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  81676. csg.copyTransformAttributes(this);
  81677. return csg;
  81678. };
  81679. CSG.prototype.union = function (csg) {
  81680. var a = new Node(this.clone().polygons);
  81681. var b = new Node(csg.clone().polygons);
  81682. a.clipTo(b);
  81683. b.clipTo(a);
  81684. b.invert();
  81685. b.clipTo(a);
  81686. b.invert();
  81687. a.build(b.allPolygons());
  81688. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81689. };
  81690. CSG.prototype.unionInPlace = function (csg) {
  81691. var a = new Node(this.polygons);
  81692. var b = new Node(csg.polygons);
  81693. a.clipTo(b);
  81694. b.clipTo(a);
  81695. b.invert();
  81696. b.clipTo(a);
  81697. b.invert();
  81698. a.build(b.allPolygons());
  81699. this.polygons = a.allPolygons();
  81700. };
  81701. CSG.prototype.subtract = function (csg) {
  81702. var a = new Node(this.clone().polygons);
  81703. var b = new Node(csg.clone().polygons);
  81704. a.invert();
  81705. a.clipTo(b);
  81706. b.clipTo(a);
  81707. b.invert();
  81708. b.clipTo(a);
  81709. b.invert();
  81710. a.build(b.allPolygons());
  81711. a.invert();
  81712. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81713. };
  81714. CSG.prototype.subtractInPlace = function (csg) {
  81715. var a = new Node(this.polygons);
  81716. var b = new Node(csg.polygons);
  81717. a.invert();
  81718. a.clipTo(b);
  81719. b.clipTo(a);
  81720. b.invert();
  81721. b.clipTo(a);
  81722. b.invert();
  81723. a.build(b.allPolygons());
  81724. a.invert();
  81725. this.polygons = a.allPolygons();
  81726. };
  81727. CSG.prototype.intersect = function (csg) {
  81728. var a = new Node(this.clone().polygons);
  81729. var b = new Node(csg.clone().polygons);
  81730. a.invert();
  81731. b.clipTo(a);
  81732. b.invert();
  81733. a.clipTo(b);
  81734. b.clipTo(a);
  81735. a.build(b.allPolygons());
  81736. a.invert();
  81737. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81738. };
  81739. CSG.prototype.intersectInPlace = function (csg) {
  81740. var a = new Node(this.polygons);
  81741. var b = new Node(csg.polygons);
  81742. a.invert();
  81743. b.clipTo(a);
  81744. b.invert();
  81745. a.clipTo(b);
  81746. b.clipTo(a);
  81747. a.build(b.allPolygons());
  81748. a.invert();
  81749. this.polygons = a.allPolygons();
  81750. };
  81751. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  81752. // not modified.
  81753. CSG.prototype.inverse = function () {
  81754. var csg = this.clone();
  81755. csg.inverseInPlace();
  81756. return csg;
  81757. };
  81758. CSG.prototype.inverseInPlace = function () {
  81759. this.polygons.map(function (p) { p.flip(); });
  81760. };
  81761. // This is used to keep meshes transformations so they can be restored
  81762. // when we build back a Babylon Mesh
  81763. // NB : All CSG operations are performed in world coordinates
  81764. CSG.prototype.copyTransformAttributes = function (csg) {
  81765. this.matrix = csg.matrix;
  81766. this.position = csg.position;
  81767. this.rotation = csg.rotation;
  81768. this.scaling = csg.scaling;
  81769. this.rotationQuaternion = csg.rotationQuaternion;
  81770. return this;
  81771. };
  81772. // Build Raw mesh from CSG
  81773. // Coordinates here are in world space
  81774. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  81775. var matrix = this.matrix.clone();
  81776. matrix.invert();
  81777. 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;
  81778. if (keepSubMeshes) {
  81779. // Sort Polygons, since subMeshes are indices range
  81780. polygons.sort(function (a, b) {
  81781. if (a.shared.meshId === b.shared.meshId) {
  81782. return a.shared.subMeshId - b.shared.subMeshId;
  81783. }
  81784. else {
  81785. return a.shared.meshId - b.shared.meshId;
  81786. }
  81787. });
  81788. }
  81789. for (var i = 0, il = polygons.length; i < il; i++) {
  81790. polygon = polygons[i];
  81791. // Building SubMeshes
  81792. if (!subMesh_dict[polygon.shared.meshId]) {
  81793. subMesh_dict[polygon.shared.meshId] = {};
  81794. }
  81795. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  81796. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  81797. indexStart: +Infinity,
  81798. indexEnd: -Infinity,
  81799. materialIndex: polygon.shared.materialIndex
  81800. };
  81801. }
  81802. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  81803. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  81804. polygonIndices[0] = 0;
  81805. polygonIndices[1] = j - 1;
  81806. polygonIndices[2] = j;
  81807. for (var k = 0; k < 3; k++) {
  81808. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  81809. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  81810. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  81811. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  81812. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  81813. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  81814. // Check if 2 points can be merged
  81815. if (!(typeof vertex_idx !== 'undefined' &&
  81816. normals[vertex_idx * 3] === localNormal.x &&
  81817. normals[vertex_idx * 3 + 1] === localNormal.y &&
  81818. normals[vertex_idx * 3 + 2] === localNormal.z &&
  81819. uvs[vertex_idx * 2] === uv.x &&
  81820. uvs[vertex_idx * 2 + 1] === uv.y)) {
  81821. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  81822. uvs.push(uv.x, uv.y);
  81823. normals.push(normal.x, normal.y, normal.z);
  81824. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  81825. }
  81826. indices.push(vertex_idx);
  81827. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  81828. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  81829. currentIndex++;
  81830. }
  81831. }
  81832. }
  81833. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  81834. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  81835. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  81836. mesh.setIndices(indices, null);
  81837. if (keepSubMeshes) {
  81838. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  81839. var materialIndexOffset = 0, materialMaxIndex;
  81840. mesh.subMeshes = new Array();
  81841. for (var m in subMesh_dict) {
  81842. materialMaxIndex = -1;
  81843. for (var sm in subMesh_dict[m]) {
  81844. subMesh_obj = subMesh_dict[m][sm];
  81845. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  81846. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  81847. }
  81848. materialIndexOffset += ++materialMaxIndex;
  81849. }
  81850. }
  81851. return mesh;
  81852. };
  81853. // Build Mesh from CSG taking material and transforms into account
  81854. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  81855. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  81856. mesh.material = material;
  81857. mesh.position.copyFrom(this.position);
  81858. mesh.rotation.copyFrom(this.rotation);
  81859. if (this.rotationQuaternion) {
  81860. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  81861. }
  81862. mesh.scaling.copyFrom(this.scaling);
  81863. mesh.computeWorldMatrix(true);
  81864. return mesh;
  81865. };
  81866. return CSG;
  81867. }());
  81868. BABYLON.CSG = CSG;
  81869. })(BABYLON || (BABYLON = {}));
  81870. //# sourceMappingURL=babylon.csg.js.map
  81871. var BABYLON;
  81872. (function (BABYLON) {
  81873. var LensFlare = /** @class */ (function () {
  81874. function LensFlare(size, position, color, imgUrl, system) {
  81875. this.size = size;
  81876. this.position = position;
  81877. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81878. this.color = color || new BABYLON.Color3(1, 1, 1);
  81879. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  81880. this._system = system;
  81881. system.lensFlares.push(this);
  81882. }
  81883. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  81884. return new LensFlare(size, position, color, imgUrl, system);
  81885. };
  81886. LensFlare.prototype.dispose = function () {
  81887. if (this.texture) {
  81888. this.texture.dispose();
  81889. }
  81890. // Remove from scene
  81891. var index = this._system.lensFlares.indexOf(this);
  81892. this._system.lensFlares.splice(index, 1);
  81893. };
  81894. ;
  81895. return LensFlare;
  81896. }());
  81897. BABYLON.LensFlare = LensFlare;
  81898. })(BABYLON || (BABYLON = {}));
  81899. //# sourceMappingURL=babylon.lensFlare.js.map
  81900. var BABYLON;
  81901. (function (BABYLON) {
  81902. var LensFlareSystem = /** @class */ (function () {
  81903. function LensFlareSystem(name, emitter, scene) {
  81904. this.name = name;
  81905. this.lensFlares = new Array();
  81906. this.borderLimit = 300;
  81907. this.viewportBorder = 0;
  81908. this.layerMask = 0x0FFFFFFF;
  81909. this._vertexBuffers = {};
  81910. this._isEnabled = true;
  81911. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81912. this._emitter = emitter;
  81913. this.id = name;
  81914. scene.lensFlareSystems.push(this);
  81915. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  81916. var engine = scene.getEngine();
  81917. // VBO
  81918. var vertices = [];
  81919. vertices.push(1, 1);
  81920. vertices.push(-1, 1);
  81921. vertices.push(-1, -1);
  81922. vertices.push(1, -1);
  81923. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81924. // Indices
  81925. var indices = [];
  81926. indices.push(0);
  81927. indices.push(1);
  81928. indices.push(2);
  81929. indices.push(0);
  81930. indices.push(2);
  81931. indices.push(3);
  81932. this._indexBuffer = engine.createIndexBuffer(indices);
  81933. // Effects
  81934. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  81935. }
  81936. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  81937. get: function () {
  81938. return this._isEnabled;
  81939. },
  81940. set: function (value) {
  81941. this._isEnabled = value;
  81942. },
  81943. enumerable: true,
  81944. configurable: true
  81945. });
  81946. LensFlareSystem.prototype.getScene = function () {
  81947. return this._scene;
  81948. };
  81949. LensFlareSystem.prototype.getEmitter = function () {
  81950. return this._emitter;
  81951. };
  81952. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  81953. this._emitter = newEmitter;
  81954. };
  81955. LensFlareSystem.prototype.getEmitterPosition = function () {
  81956. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  81957. };
  81958. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  81959. var position = this.getEmitterPosition();
  81960. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  81961. this._positionX = position.x;
  81962. this._positionY = position.y;
  81963. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  81964. if (this.viewportBorder > 0) {
  81965. globalViewport.x -= this.viewportBorder;
  81966. globalViewport.y -= this.viewportBorder;
  81967. globalViewport.width += this.viewportBorder * 2;
  81968. globalViewport.height += this.viewportBorder * 2;
  81969. position.x += this.viewportBorder;
  81970. position.y += this.viewportBorder;
  81971. this._positionX += this.viewportBorder;
  81972. this._positionY += this.viewportBorder;
  81973. }
  81974. if (position.z > 0) {
  81975. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  81976. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  81977. return true;
  81978. }
  81979. return true;
  81980. }
  81981. return false;
  81982. };
  81983. LensFlareSystem.prototype._isVisible = function () {
  81984. if (!this._isEnabled || !this._scene.activeCamera) {
  81985. return false;
  81986. }
  81987. var emitterPosition = this.getEmitterPosition();
  81988. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  81989. var distance = direction.length();
  81990. direction.normalize();
  81991. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  81992. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  81993. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  81994. };
  81995. LensFlareSystem.prototype.render = function () {
  81996. if (!this._effect.isReady() || !this._scene.activeCamera)
  81997. return false;
  81998. var engine = this._scene.getEngine();
  81999. var viewport = this._scene.activeCamera.viewport;
  82000. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  82001. // Position
  82002. if (!this.computeEffectivePosition(globalViewport)) {
  82003. return false;
  82004. }
  82005. // Visibility
  82006. if (!this._isVisible()) {
  82007. return false;
  82008. }
  82009. // Intensity
  82010. var awayX;
  82011. var awayY;
  82012. if (this._positionX < this.borderLimit + globalViewport.x) {
  82013. awayX = this.borderLimit + globalViewport.x - this._positionX;
  82014. }
  82015. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  82016. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  82017. }
  82018. else {
  82019. awayX = 0;
  82020. }
  82021. if (this._positionY < this.borderLimit + globalViewport.y) {
  82022. awayY = this.borderLimit + globalViewport.y - this._positionY;
  82023. }
  82024. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  82025. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  82026. }
  82027. else {
  82028. awayY = 0;
  82029. }
  82030. var away = (awayX > awayY) ? awayX : awayY;
  82031. away -= this.viewportBorder;
  82032. if (away > this.borderLimit) {
  82033. away = this.borderLimit;
  82034. }
  82035. var intensity = 1.0 - (away / this.borderLimit);
  82036. if (intensity < 0) {
  82037. return false;
  82038. }
  82039. if (intensity > 1.0) {
  82040. intensity = 1.0;
  82041. }
  82042. if (this.viewportBorder > 0) {
  82043. globalViewport.x += this.viewportBorder;
  82044. globalViewport.y += this.viewportBorder;
  82045. globalViewport.width -= this.viewportBorder * 2;
  82046. globalViewport.height -= this.viewportBorder * 2;
  82047. this._positionX -= this.viewportBorder;
  82048. this._positionY -= this.viewportBorder;
  82049. }
  82050. // Position
  82051. var centerX = globalViewport.x + globalViewport.width / 2;
  82052. var centerY = globalViewport.y + globalViewport.height / 2;
  82053. var distX = centerX - this._positionX;
  82054. var distY = centerY - this._positionY;
  82055. // Effects
  82056. engine.enableEffect(this._effect);
  82057. engine.setState(false);
  82058. engine.setDepthBuffer(false);
  82059. // VBOs
  82060. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  82061. // Flares
  82062. for (var index = 0; index < this.lensFlares.length; index++) {
  82063. var flare = this.lensFlares[index];
  82064. engine.setAlphaMode(flare.alphaMode);
  82065. var x = centerX - (distX * flare.position);
  82066. var y = centerY - (distY * flare.position);
  82067. var cw = flare.size;
  82068. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  82069. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  82070. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  82071. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  82072. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  82073. // Texture
  82074. this._effect.setTexture("textureSampler", flare.texture);
  82075. // Color
  82076. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  82077. // Draw order
  82078. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82079. }
  82080. engine.setDepthBuffer(true);
  82081. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  82082. return true;
  82083. };
  82084. LensFlareSystem.prototype.dispose = function () {
  82085. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82086. if (vertexBuffer) {
  82087. vertexBuffer.dispose();
  82088. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82089. }
  82090. if (this._indexBuffer) {
  82091. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82092. this._indexBuffer = null;
  82093. }
  82094. while (this.lensFlares.length) {
  82095. this.lensFlares[0].dispose();
  82096. }
  82097. // Remove from scene
  82098. var index = this._scene.lensFlareSystems.indexOf(this);
  82099. this._scene.lensFlareSystems.splice(index, 1);
  82100. };
  82101. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  82102. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  82103. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  82104. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  82105. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  82106. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  82107. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  82108. var parsedFlare = parsedLensFlareSystem.flares[index];
  82109. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  82110. }
  82111. return lensFlareSystem;
  82112. };
  82113. LensFlareSystem.prototype.serialize = function () {
  82114. var serializationObject = {};
  82115. serializationObject.id = this.id;
  82116. serializationObject.name = this.name;
  82117. serializationObject.emitterId = this.getEmitter().id;
  82118. serializationObject.borderLimit = this.borderLimit;
  82119. serializationObject.flares = [];
  82120. for (var index = 0; index < this.lensFlares.length; index++) {
  82121. var flare = this.lensFlares[index];
  82122. serializationObject.flares.push({
  82123. size: flare.size,
  82124. position: flare.position,
  82125. color: flare.color.asArray(),
  82126. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  82127. });
  82128. }
  82129. return serializationObject;
  82130. };
  82131. return LensFlareSystem;
  82132. }());
  82133. BABYLON.LensFlareSystem = LensFlareSystem;
  82134. })(BABYLON || (BABYLON = {}));
  82135. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  82136. var BABYLON;
  82137. (function (BABYLON) {
  82138. /**
  82139. * This is a holder class for the physics joint created by the physics plugin.
  82140. * It holds a set of functions to control the underlying joint.
  82141. */
  82142. var PhysicsJoint = /** @class */ (function () {
  82143. function PhysicsJoint(type, jointData) {
  82144. this.type = type;
  82145. this.jointData = jointData;
  82146. jointData.nativeParams = jointData.nativeParams || {};
  82147. }
  82148. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  82149. get: function () {
  82150. return this._physicsJoint;
  82151. },
  82152. set: function (newJoint) {
  82153. if (this._physicsJoint) {
  82154. //remove from the wolrd
  82155. }
  82156. this._physicsJoint = newJoint;
  82157. },
  82158. enumerable: true,
  82159. configurable: true
  82160. });
  82161. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  82162. set: function (physicsPlugin) {
  82163. this._physicsPlugin = physicsPlugin;
  82164. },
  82165. enumerable: true,
  82166. configurable: true
  82167. });
  82168. /**
  82169. * Execute a function that is physics-plugin specific.
  82170. * @param {Function} func the function that will be executed.
  82171. * It accepts two parameters: the physics world and the physics joint.
  82172. */
  82173. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  82174. func(this._physicsPlugin.world, this._physicsJoint);
  82175. };
  82176. //TODO check if the native joints are the same
  82177. //Joint Types
  82178. PhysicsJoint.DistanceJoint = 0;
  82179. PhysicsJoint.HingeJoint = 1;
  82180. PhysicsJoint.BallAndSocketJoint = 2;
  82181. PhysicsJoint.WheelJoint = 3;
  82182. PhysicsJoint.SliderJoint = 4;
  82183. //OIMO
  82184. PhysicsJoint.PrismaticJoint = 5;
  82185. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  82186. PhysicsJoint.UniversalJoint = 6;
  82187. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  82188. //Cannon
  82189. //Similar to a Ball-Joint. Different in params
  82190. PhysicsJoint.PointToPointJoint = 8;
  82191. //Cannon only at the moment
  82192. PhysicsJoint.SpringJoint = 9;
  82193. PhysicsJoint.LockJoint = 10;
  82194. return PhysicsJoint;
  82195. }());
  82196. BABYLON.PhysicsJoint = PhysicsJoint;
  82197. /**
  82198. * A class representing a physics distance joint.
  82199. */
  82200. var DistanceJoint = /** @class */ (function (_super) {
  82201. __extends(DistanceJoint, _super);
  82202. function DistanceJoint(jointData) {
  82203. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  82204. }
  82205. /**
  82206. * Update the predefined distance.
  82207. */
  82208. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  82209. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  82210. };
  82211. return DistanceJoint;
  82212. }(PhysicsJoint));
  82213. BABYLON.DistanceJoint = DistanceJoint;
  82214. var MotorEnabledJoint = /** @class */ (function (_super) {
  82215. __extends(MotorEnabledJoint, _super);
  82216. function MotorEnabledJoint(type, jointData) {
  82217. return _super.call(this, type, jointData) || this;
  82218. }
  82219. /**
  82220. * Set the motor values.
  82221. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82222. * @param {number} force the force to apply
  82223. * @param {number} maxForce max force for this motor.
  82224. */
  82225. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  82226. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  82227. };
  82228. /**
  82229. * Set the motor's limits.
  82230. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82231. */
  82232. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  82233. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  82234. };
  82235. return MotorEnabledJoint;
  82236. }(PhysicsJoint));
  82237. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  82238. /**
  82239. * This class represents a single hinge physics joint
  82240. */
  82241. var HingeJoint = /** @class */ (function (_super) {
  82242. __extends(HingeJoint, _super);
  82243. function HingeJoint(jointData) {
  82244. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  82245. }
  82246. /**
  82247. * Set the motor values.
  82248. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82249. * @param {number} force the force to apply
  82250. * @param {number} maxForce max force for this motor.
  82251. */
  82252. HingeJoint.prototype.setMotor = function (force, maxForce) {
  82253. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  82254. };
  82255. /**
  82256. * Set the motor's limits.
  82257. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82258. */
  82259. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  82260. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  82261. };
  82262. return HingeJoint;
  82263. }(MotorEnabledJoint));
  82264. BABYLON.HingeJoint = HingeJoint;
  82265. /**
  82266. * This class represents a dual hinge physics joint (same as wheel joint)
  82267. */
  82268. var Hinge2Joint = /** @class */ (function (_super) {
  82269. __extends(Hinge2Joint, _super);
  82270. function Hinge2Joint(jointData) {
  82271. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  82272. }
  82273. /**
  82274. * Set the motor values.
  82275. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82276. * @param {number} force the force to apply
  82277. * @param {number} maxForce max force for this motor.
  82278. * @param {motorIndex} the motor's index, 0 or 1.
  82279. */
  82280. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  82281. if (motorIndex === void 0) { motorIndex = 0; }
  82282. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  82283. };
  82284. /**
  82285. * Set the motor limits.
  82286. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82287. * @param {number} upperLimit the upper limit
  82288. * @param {number} lowerLimit lower limit
  82289. * @param {motorIndex} the motor's index, 0 or 1.
  82290. */
  82291. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  82292. if (motorIndex === void 0) { motorIndex = 0; }
  82293. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  82294. };
  82295. return Hinge2Joint;
  82296. }(MotorEnabledJoint));
  82297. BABYLON.Hinge2Joint = Hinge2Joint;
  82298. })(BABYLON || (BABYLON = {}));
  82299. //# sourceMappingURL=babylon.physicsJoint.js.map
  82300. var BABYLON;
  82301. (function (BABYLON) {
  82302. var PhysicsImpostor = /** @class */ (function () {
  82303. function PhysicsImpostor(object, type, _options, _scene) {
  82304. if (_options === void 0) { _options = { mass: 0 }; }
  82305. var _this = this;
  82306. this.object = object;
  82307. this.type = type;
  82308. this._options = _options;
  82309. this._scene = _scene;
  82310. this._bodyUpdateRequired = false;
  82311. this._onBeforePhysicsStepCallbacks = new Array();
  82312. this._onAfterPhysicsStepCallbacks = new Array();
  82313. this._onPhysicsCollideCallbacks = [];
  82314. this._deltaPosition = BABYLON.Vector3.Zero();
  82315. this._isDisposed = false;
  82316. //temp variables for parent rotation calculations
  82317. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  82318. this._tmpQuat = new BABYLON.Quaternion();
  82319. this._tmpQuat2 = new BABYLON.Quaternion();
  82320. /**
  82321. * this function is executed by the physics engine.
  82322. */
  82323. this.beforeStep = function () {
  82324. if (!_this._physicsEngine) {
  82325. return;
  82326. }
  82327. _this.object.translate(_this._deltaPosition, -1);
  82328. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  82329. _this.object.computeWorldMatrix(false);
  82330. if (_this.object.parent && _this.object.rotationQuaternion) {
  82331. _this.getParentsRotation();
  82332. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  82333. }
  82334. else {
  82335. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  82336. }
  82337. if (!_this._options.disableBidirectionalTransformation) {
  82338. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  82339. }
  82340. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  82341. func(_this);
  82342. });
  82343. };
  82344. /**
  82345. * this function is executed by the physics engine.
  82346. */
  82347. this.afterStep = function () {
  82348. if (!_this._physicsEngine) {
  82349. return;
  82350. }
  82351. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  82352. func(_this);
  82353. });
  82354. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  82355. // object has now its world rotation. needs to be converted to local.
  82356. if (_this.object.parent && _this.object.rotationQuaternion) {
  82357. _this.getParentsRotation();
  82358. _this._tmpQuat.conjugateInPlace();
  82359. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  82360. }
  82361. // take the position set and make it the absolute position of this object.
  82362. _this.object.setAbsolutePosition(_this.object.position);
  82363. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  82364. _this.object.translate(_this._deltaPosition, 1);
  82365. };
  82366. /**
  82367. * Legacy collision detection event support
  82368. */
  82369. this.onCollideEvent = null;
  82370. //event and body object due to cannon's event-based architecture.
  82371. this.onCollide = function (e) {
  82372. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  82373. return;
  82374. }
  82375. if (!_this._physicsEngine) {
  82376. return;
  82377. }
  82378. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  82379. if (otherImpostor) {
  82380. // Legacy collision detection event support
  82381. if (_this.onCollideEvent) {
  82382. _this.onCollideEvent(_this, otherImpostor);
  82383. }
  82384. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  82385. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  82386. }).forEach(function (obj) {
  82387. obj.callback(_this, otherImpostor);
  82388. });
  82389. }
  82390. };
  82391. //sanity check!
  82392. if (!this.object) {
  82393. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  82394. return;
  82395. }
  82396. //legacy support for old syntax.
  82397. if (!this._scene && object.getScene) {
  82398. this._scene = object.getScene();
  82399. }
  82400. if (!this._scene) {
  82401. return;
  82402. }
  82403. this._physicsEngine = this._scene.getPhysicsEngine();
  82404. if (!this._physicsEngine) {
  82405. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  82406. }
  82407. else {
  82408. //set the object's quaternion, if not set
  82409. if (!this.object.rotationQuaternion) {
  82410. if (this.object.rotation) {
  82411. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  82412. }
  82413. else {
  82414. this.object.rotationQuaternion = new BABYLON.Quaternion();
  82415. }
  82416. }
  82417. //default options params
  82418. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  82419. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  82420. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  82421. this._joints = [];
  82422. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  82423. if (!this.object.parent || this._options.ignoreParent) {
  82424. this._init();
  82425. }
  82426. else if (this.object.parent.physicsImpostor) {
  82427. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  82428. }
  82429. }
  82430. }
  82431. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  82432. get: function () {
  82433. return this._isDisposed;
  82434. },
  82435. enumerable: true,
  82436. configurable: true
  82437. });
  82438. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  82439. get: function () {
  82440. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  82441. },
  82442. set: function (value) {
  82443. this.setMass(value);
  82444. },
  82445. enumerable: true,
  82446. configurable: true
  82447. });
  82448. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  82449. get: function () {
  82450. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  82451. },
  82452. set: function (value) {
  82453. if (!this._physicsEngine) {
  82454. return;
  82455. }
  82456. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  82457. },
  82458. enumerable: true,
  82459. configurable: true
  82460. });
  82461. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  82462. get: function () {
  82463. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  82464. },
  82465. set: function (value) {
  82466. if (!this._physicsEngine) {
  82467. return;
  82468. }
  82469. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  82470. },
  82471. enumerable: true,
  82472. configurable: true
  82473. });
  82474. /**
  82475. * This function will completly initialize this impostor.
  82476. * It will create a new body - but only if this mesh has no parent.
  82477. * If it has, this impostor will not be used other than to define the impostor
  82478. * of the child mesh.
  82479. */
  82480. PhysicsImpostor.prototype._init = function () {
  82481. if (!this._physicsEngine) {
  82482. return;
  82483. }
  82484. this._physicsEngine.removeImpostor(this);
  82485. this.physicsBody = null;
  82486. this._parent = this._parent || this._getPhysicsParent();
  82487. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  82488. this._physicsEngine.addImpostor(this);
  82489. }
  82490. };
  82491. PhysicsImpostor.prototype._getPhysicsParent = function () {
  82492. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  82493. var parentMesh = this.object.parent;
  82494. return parentMesh.physicsImpostor;
  82495. }
  82496. return null;
  82497. };
  82498. /**
  82499. * Should a new body be generated.
  82500. */
  82501. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  82502. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  82503. };
  82504. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  82505. this.forceUpdate();
  82506. };
  82507. /**
  82508. * Force a regeneration of this or the parent's impostor's body.
  82509. * Use under cautious - This will remove all joints already implemented.
  82510. */
  82511. PhysicsImpostor.prototype.forceUpdate = function () {
  82512. this._init();
  82513. if (this.parent && !this._options.ignoreParent) {
  82514. this.parent.forceUpdate();
  82515. }
  82516. };
  82517. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  82518. /*public get mesh(): AbstractMesh {
  82519. return this._mesh;
  82520. }*/
  82521. /**
  82522. * Gets the body that holds this impostor. Either its own, or its parent.
  82523. */
  82524. get: function () {
  82525. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  82526. },
  82527. /**
  82528. * Set the physics body. Used mainly by the physics engine/plugin
  82529. */
  82530. set: function (physicsBody) {
  82531. if (this._physicsBody && this._physicsEngine) {
  82532. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  82533. }
  82534. this._physicsBody = physicsBody;
  82535. this.resetUpdateFlags();
  82536. },
  82537. enumerable: true,
  82538. configurable: true
  82539. });
  82540. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  82541. get: function () {
  82542. return !this._options.ignoreParent && this._parent ? this._parent : null;
  82543. },
  82544. set: function (value) {
  82545. this._parent = value;
  82546. },
  82547. enumerable: true,
  82548. configurable: true
  82549. });
  82550. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  82551. this._bodyUpdateRequired = false;
  82552. };
  82553. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  82554. if (this.object.getBoundingInfo) {
  82555. var q = this.object.rotationQuaternion;
  82556. //reset rotation
  82557. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  82558. //calculate the world matrix with no rotation
  82559. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82560. var boundingInfo = this.object.getBoundingInfo();
  82561. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  82562. //bring back the rotation
  82563. this.object.rotationQuaternion = q;
  82564. //calculate the world matrix with the new rotation
  82565. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82566. return size;
  82567. }
  82568. else {
  82569. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  82570. }
  82571. };
  82572. PhysicsImpostor.prototype.getObjectCenter = function () {
  82573. if (this.object.getBoundingInfo) {
  82574. var boundingInfo = this.object.getBoundingInfo();
  82575. return boundingInfo.boundingBox.centerWorld;
  82576. }
  82577. else {
  82578. return this.object.position;
  82579. }
  82580. };
  82581. /**
  82582. * Get a specific parametes from the options parameter.
  82583. */
  82584. PhysicsImpostor.prototype.getParam = function (paramName) {
  82585. return this._options[paramName];
  82586. };
  82587. /**
  82588. * Sets a specific parameter in the options given to the physics plugin
  82589. */
  82590. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  82591. this._options[paramName] = value;
  82592. this._bodyUpdateRequired = true;
  82593. };
  82594. /**
  82595. * Specifically change the body's mass option. Won't recreate the physics body object
  82596. */
  82597. PhysicsImpostor.prototype.setMass = function (mass) {
  82598. if (this.getParam("mass") !== mass) {
  82599. this.setParam("mass", mass);
  82600. }
  82601. if (this._physicsEngine) {
  82602. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  82603. }
  82604. };
  82605. PhysicsImpostor.prototype.getLinearVelocity = function () {
  82606. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  82607. };
  82608. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  82609. if (this._physicsEngine) {
  82610. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  82611. }
  82612. };
  82613. PhysicsImpostor.prototype.getAngularVelocity = function () {
  82614. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  82615. };
  82616. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  82617. if (this._physicsEngine) {
  82618. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  82619. }
  82620. };
  82621. /**
  82622. * Execute a function with the physics plugin native code.
  82623. * Provide a function the will have two variables - the world object and the physics body object.
  82624. */
  82625. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  82626. if (this._physicsEngine) {
  82627. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  82628. }
  82629. };
  82630. /**
  82631. * Register a function that will be executed before the physics world is stepping forward.
  82632. */
  82633. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  82634. this._onBeforePhysicsStepCallbacks.push(func);
  82635. };
  82636. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  82637. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  82638. if (index > -1) {
  82639. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  82640. }
  82641. else {
  82642. BABYLON.Tools.Warn("Function to remove was not found");
  82643. }
  82644. };
  82645. /**
  82646. * Register a function that will be executed after the physics step
  82647. */
  82648. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  82649. this._onAfterPhysicsStepCallbacks.push(func);
  82650. };
  82651. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  82652. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  82653. if (index > -1) {
  82654. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  82655. }
  82656. else {
  82657. BABYLON.Tools.Warn("Function to remove was not found");
  82658. }
  82659. };
  82660. /**
  82661. * register a function that will be executed when this impostor collides against a different body.
  82662. */
  82663. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  82664. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82665. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  82666. };
  82667. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  82668. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82669. var index = -1;
  82670. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  82671. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  82672. // chcek the arrays match
  82673. var sameList = cbDef.otherImpostors.every(function (impostor) {
  82674. return collidedAgainstList.indexOf(impostor) > -1;
  82675. });
  82676. if (sameList) {
  82677. index = idx;
  82678. }
  82679. return sameList;
  82680. }
  82681. return false;
  82682. });
  82683. if (found) {
  82684. this._onPhysicsCollideCallbacks.splice(index, 1);
  82685. }
  82686. else {
  82687. BABYLON.Tools.Warn("Function to remove was not found");
  82688. }
  82689. };
  82690. PhysicsImpostor.prototype.getParentsRotation = function () {
  82691. var parent = this.object.parent;
  82692. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  82693. while (parent) {
  82694. if (parent.rotationQuaternion) {
  82695. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  82696. }
  82697. else {
  82698. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  82699. }
  82700. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  82701. parent = parent.parent;
  82702. }
  82703. return this._tmpQuat;
  82704. };
  82705. /**
  82706. * Apply a force
  82707. */
  82708. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  82709. if (this._physicsEngine) {
  82710. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  82711. }
  82712. return this;
  82713. };
  82714. /**
  82715. * Apply an impulse
  82716. */
  82717. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  82718. if (this._physicsEngine) {
  82719. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  82720. }
  82721. return this;
  82722. };
  82723. /**
  82724. * A help function to create a joint.
  82725. */
  82726. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  82727. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  82728. this.addJoint(otherImpostor, joint);
  82729. return this;
  82730. };
  82731. /**
  82732. * Add a joint to this impostor with a different impostor.
  82733. */
  82734. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  82735. this._joints.push({
  82736. otherImpostor: otherImpostor,
  82737. joint: joint
  82738. });
  82739. if (this._physicsEngine) {
  82740. this._physicsEngine.addJoint(this, otherImpostor, joint);
  82741. }
  82742. return this;
  82743. };
  82744. /**
  82745. * Will keep this body still, in a sleep mode.
  82746. */
  82747. PhysicsImpostor.prototype.sleep = function () {
  82748. if (this._physicsEngine) {
  82749. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  82750. }
  82751. return this;
  82752. };
  82753. /**
  82754. * Wake the body up.
  82755. */
  82756. PhysicsImpostor.prototype.wakeUp = function () {
  82757. if (this._physicsEngine) {
  82758. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  82759. }
  82760. return this;
  82761. };
  82762. PhysicsImpostor.prototype.clone = function (newObject) {
  82763. if (!newObject)
  82764. return null;
  82765. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  82766. };
  82767. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  82768. var _this = this;
  82769. //no dispose if no physics engine is available.
  82770. if (!this._physicsEngine) {
  82771. return;
  82772. }
  82773. this._joints.forEach(function (j) {
  82774. if (_this._physicsEngine) {
  82775. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  82776. }
  82777. });
  82778. //dispose the physics body
  82779. this._physicsEngine.removeImpostor(this);
  82780. if (this.parent) {
  82781. this.parent.forceUpdate();
  82782. }
  82783. else {
  82784. /*this._object.getChildMeshes().forEach(function(mesh) {
  82785. if (mesh.physicsImpostor) {
  82786. if (disposeChildren) {
  82787. mesh.physicsImpostor.dispose();
  82788. mesh.physicsImpostor = null;
  82789. }
  82790. }
  82791. })*/
  82792. }
  82793. this._isDisposed = true;
  82794. };
  82795. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  82796. this._deltaPosition.copyFrom(position);
  82797. };
  82798. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  82799. if (!this._deltaRotation) {
  82800. this._deltaRotation = new BABYLON.Quaternion();
  82801. }
  82802. this._deltaRotation.copyFrom(rotation);
  82803. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  82804. };
  82805. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  82806. if (this._physicsEngine) {
  82807. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  82808. }
  82809. return this;
  82810. };
  82811. PhysicsImpostor.prototype.getRadius = function () {
  82812. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  82813. };
  82814. /**
  82815. * Sync a bone with this impostor
  82816. * @param bone The bone to sync to the impostor.
  82817. * @param boneMesh The mesh that the bone is influencing.
  82818. * @param jointPivot The pivot of the joint / bone in local space.
  82819. * @param distToJoint Optional distance from the impostor to the joint.
  82820. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82821. */
  82822. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  82823. var tempVec = PhysicsImpostor._tmpVecs[0];
  82824. var mesh = this.object;
  82825. if (mesh.rotationQuaternion) {
  82826. if (adjustRotation) {
  82827. var tempQuat = PhysicsImpostor._tmpQuat;
  82828. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  82829. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  82830. }
  82831. else {
  82832. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  82833. }
  82834. }
  82835. tempVec.x = 0;
  82836. tempVec.y = 0;
  82837. tempVec.z = 0;
  82838. if (jointPivot) {
  82839. tempVec.x = jointPivot.x;
  82840. tempVec.y = jointPivot.y;
  82841. tempVec.z = jointPivot.z;
  82842. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  82843. if (distToJoint === undefined || distToJoint === null) {
  82844. distToJoint = jointPivot.length();
  82845. }
  82846. tempVec.x *= distToJoint;
  82847. tempVec.y *= distToJoint;
  82848. tempVec.z *= distToJoint;
  82849. }
  82850. if (bone.getParent()) {
  82851. tempVec.addInPlace(mesh.getAbsolutePosition());
  82852. bone.setAbsolutePosition(tempVec, boneMesh);
  82853. }
  82854. else {
  82855. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  82856. boneMesh.position.x -= tempVec.x;
  82857. boneMesh.position.y -= tempVec.y;
  82858. boneMesh.position.z -= tempVec.z;
  82859. }
  82860. };
  82861. /**
  82862. * Sync impostor to a bone
  82863. * @param bone The bone that the impostor will be synced to.
  82864. * @param boneMesh The mesh that the bone is influencing.
  82865. * @param jointPivot The pivot of the joint / bone in local space.
  82866. * @param distToJoint Optional distance from the impostor to the joint.
  82867. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82868. * @param boneAxis Optional vector3 axis the bone is aligned with
  82869. */
  82870. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  82871. var mesh = this.object;
  82872. if (mesh.rotationQuaternion) {
  82873. if (adjustRotation) {
  82874. var tempQuat = PhysicsImpostor._tmpQuat;
  82875. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  82876. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  82877. }
  82878. else {
  82879. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  82880. }
  82881. }
  82882. var pos = PhysicsImpostor._tmpVecs[0];
  82883. var boneDir = PhysicsImpostor._tmpVecs[1];
  82884. if (!boneAxis) {
  82885. boneAxis = PhysicsImpostor._tmpVecs[2];
  82886. boneAxis.x = 0;
  82887. boneAxis.y = 1;
  82888. boneAxis.z = 0;
  82889. }
  82890. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  82891. bone.getAbsolutePositionToRef(boneMesh, pos);
  82892. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  82893. distToJoint = jointPivot.length();
  82894. }
  82895. if (distToJoint !== undefined && distToJoint !== null) {
  82896. pos.x += boneDir.x * distToJoint;
  82897. pos.y += boneDir.y * distToJoint;
  82898. pos.z += boneDir.z * distToJoint;
  82899. }
  82900. mesh.setAbsolutePosition(pos);
  82901. };
  82902. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  82903. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  82904. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82905. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  82906. //Impostor types
  82907. PhysicsImpostor.NoImpostor = 0;
  82908. PhysicsImpostor.SphereImpostor = 1;
  82909. PhysicsImpostor.BoxImpostor = 2;
  82910. PhysicsImpostor.PlaneImpostor = 3;
  82911. PhysicsImpostor.MeshImpostor = 4;
  82912. PhysicsImpostor.CylinderImpostor = 7;
  82913. PhysicsImpostor.ParticleImpostor = 8;
  82914. PhysicsImpostor.HeightmapImpostor = 9;
  82915. return PhysicsImpostor;
  82916. }());
  82917. BABYLON.PhysicsImpostor = PhysicsImpostor;
  82918. })(BABYLON || (BABYLON = {}));
  82919. //# sourceMappingURL=babylon.physicsImpostor.js.map
  82920. var BABYLON;
  82921. (function (BABYLON) {
  82922. var PhysicsEngine = /** @class */ (function () {
  82923. function PhysicsEngine(gravity, _physicsPlugin) {
  82924. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  82925. this._physicsPlugin = _physicsPlugin;
  82926. //new methods and parameters
  82927. this._impostors = [];
  82928. this._joints = [];
  82929. if (!this._physicsPlugin.isSupported()) {
  82930. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  82931. + "Please make sure it is included.");
  82932. }
  82933. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  82934. this.setGravity(gravity);
  82935. this.setTimeStep();
  82936. }
  82937. PhysicsEngine.prototype.setGravity = function (gravity) {
  82938. this.gravity = gravity;
  82939. this._physicsPlugin.setGravity(this.gravity);
  82940. };
  82941. /**
  82942. * Set the time step of the physics engine.
  82943. * default is 1/60.
  82944. * To slow it down, enter 1/600 for example.
  82945. * To speed it up, 1/30
  82946. * @param {number} newTimeStep the new timestep to apply to this world.
  82947. */
  82948. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  82949. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  82950. this._physicsPlugin.setTimeStep(newTimeStep);
  82951. };
  82952. /**
  82953. * Get the time step of the physics engine.
  82954. */
  82955. PhysicsEngine.prototype.getTimeStep = function () {
  82956. return this._physicsPlugin.getTimeStep();
  82957. };
  82958. PhysicsEngine.prototype.dispose = function () {
  82959. this._impostors.forEach(function (impostor) {
  82960. impostor.dispose();
  82961. });
  82962. this._physicsPlugin.dispose();
  82963. };
  82964. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  82965. return this._physicsPlugin.name;
  82966. };
  82967. /**
  82968. * Adding a new impostor for the impostor tracking.
  82969. * This will be done by the impostor itself.
  82970. * @param {PhysicsImpostor} impostor the impostor to add
  82971. */
  82972. PhysicsEngine.prototype.addImpostor = function (impostor) {
  82973. impostor.uniqueId = this._impostors.push(impostor);
  82974. //if no parent, generate the body
  82975. if (!impostor.parent) {
  82976. this._physicsPlugin.generatePhysicsBody(impostor);
  82977. }
  82978. };
  82979. /**
  82980. * Remove an impostor from the engine.
  82981. * This impostor and its mesh will not longer be updated by the physics engine.
  82982. * @param {PhysicsImpostor} impostor the impostor to remove
  82983. */
  82984. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  82985. var index = this._impostors.indexOf(impostor);
  82986. if (index > -1) {
  82987. var removed = this._impostors.splice(index, 1);
  82988. //Is it needed?
  82989. if (removed.length) {
  82990. //this will also remove it from the world.
  82991. removed[0].physicsBody = null;
  82992. }
  82993. }
  82994. };
  82995. /**
  82996. * Add a joint to the physics engine
  82997. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  82998. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  82999. * @param {PhysicsJoint} the joint that will connect both impostors.
  83000. */
  83001. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  83002. var impostorJoint = {
  83003. mainImpostor: mainImpostor,
  83004. connectedImpostor: connectedImpostor,
  83005. joint: joint
  83006. };
  83007. joint.physicsPlugin = this._physicsPlugin;
  83008. this._joints.push(impostorJoint);
  83009. this._physicsPlugin.generateJoint(impostorJoint);
  83010. };
  83011. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  83012. var matchingJoints = this._joints.filter(function (impostorJoint) {
  83013. return (impostorJoint.connectedImpostor === connectedImpostor
  83014. && impostorJoint.joint === joint
  83015. && impostorJoint.mainImpostor === mainImpostor);
  83016. });
  83017. if (matchingJoints.length) {
  83018. this._physicsPlugin.removeJoint(matchingJoints[0]);
  83019. //TODO remove it from the list as well
  83020. }
  83021. };
  83022. /**
  83023. * Called by the scene. no need to call it.
  83024. */
  83025. PhysicsEngine.prototype._step = function (delta) {
  83026. var _this = this;
  83027. //check if any mesh has no body / requires an update
  83028. this._impostors.forEach(function (impostor) {
  83029. if (impostor.isBodyInitRequired()) {
  83030. _this._physicsPlugin.generatePhysicsBody(impostor);
  83031. }
  83032. });
  83033. if (delta > 0.1) {
  83034. delta = 0.1;
  83035. }
  83036. else if (delta <= 0) {
  83037. delta = 1.0 / 60.0;
  83038. }
  83039. this._physicsPlugin.executeStep(delta, this._impostors);
  83040. };
  83041. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  83042. return this._physicsPlugin;
  83043. };
  83044. PhysicsEngine.prototype.getImpostors = function () {
  83045. return this._impostors;
  83046. };
  83047. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  83048. for (var i = 0; i < this._impostors.length; ++i) {
  83049. if (this._impostors[i].object === object) {
  83050. return this._impostors[i];
  83051. }
  83052. }
  83053. return null;
  83054. };
  83055. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  83056. for (var i = 0; i < this._impostors.length; ++i) {
  83057. if (this._impostors[i].physicsBody === body) {
  83058. return this._impostors[i];
  83059. }
  83060. }
  83061. return null;
  83062. };
  83063. // Statics
  83064. PhysicsEngine.Epsilon = 0.001;
  83065. return PhysicsEngine;
  83066. }());
  83067. BABYLON.PhysicsEngine = PhysicsEngine;
  83068. })(BABYLON || (BABYLON = {}));
  83069. //# sourceMappingURL=babylon.physicsEngine.js.map
  83070. var BABYLON;
  83071. (function (BABYLON) {
  83072. var PhysicsHelper = /** @class */ (function () {
  83073. function PhysicsHelper(scene) {
  83074. this._scene = scene;
  83075. this._physicsEngine = this._scene.getPhysicsEngine();
  83076. if (!this._physicsEngine) {
  83077. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  83078. }
  83079. }
  83080. /**
  83081. * @param {Vector3} origin the origin of the explosion
  83082. * @param {number} radius the explosion radius
  83083. * @param {number} strength the explosion strength
  83084. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83085. */
  83086. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  83087. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83088. if (!this._physicsEngine) {
  83089. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  83090. return null;
  83091. }
  83092. var impostors = this._physicsEngine.getImpostors();
  83093. if (impostors.length === 0) {
  83094. return null;
  83095. }
  83096. var event = new PhysicsRadialExplosionEvent(this._scene);
  83097. impostors.forEach(function (impostor) {
  83098. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  83099. if (!impostorForceAndContactPoint) {
  83100. return;
  83101. }
  83102. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83103. });
  83104. event.dispose(false);
  83105. return event;
  83106. };
  83107. /**
  83108. * @param {Vector3} origin the origin of the explosion
  83109. * @param {number} radius the explosion radius
  83110. * @param {number} strength the explosion strength
  83111. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83112. */
  83113. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  83114. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83115. if (!this._physicsEngine) {
  83116. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83117. return null;
  83118. }
  83119. var impostors = this._physicsEngine.getImpostors();
  83120. if (impostors.length === 0) {
  83121. return null;
  83122. }
  83123. var event = new PhysicsRadialExplosionEvent(this._scene);
  83124. impostors.forEach(function (impostor) {
  83125. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  83126. if (!impostorForceAndContactPoint) {
  83127. return;
  83128. }
  83129. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83130. });
  83131. event.dispose(false);
  83132. return event;
  83133. };
  83134. /**
  83135. * @param {Vector3} origin the origin of the explosion
  83136. * @param {number} radius the explosion radius
  83137. * @param {number} strength the explosion strength
  83138. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83139. */
  83140. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  83141. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83142. if (!this._physicsEngine) {
  83143. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83144. return null;
  83145. }
  83146. var impostors = this._physicsEngine.getImpostors();
  83147. if (impostors.length === 0) {
  83148. return null;
  83149. }
  83150. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  83151. event.dispose(false);
  83152. return event;
  83153. };
  83154. /**
  83155. * @param {Vector3} origin the origin of the updraft
  83156. * @param {number} radius the radius of the updraft
  83157. * @param {number} strength the strength of the updraft
  83158. * @param {number} height the height of the updraft
  83159. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  83160. */
  83161. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  83162. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  83163. if (!this._physicsEngine) {
  83164. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83165. return null;
  83166. }
  83167. if (this._physicsEngine.getImpostors().length === 0) {
  83168. return null;
  83169. }
  83170. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  83171. event.dispose(false);
  83172. return event;
  83173. };
  83174. /**
  83175. * @param {Vector3} origin the of the vortex
  83176. * @param {number} radius the radius of the vortex
  83177. * @param {number} strength the strength of the vortex
  83178. * @param {number} height the height of the vortex
  83179. */
  83180. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  83181. if (!this._physicsEngine) {
  83182. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83183. return null;
  83184. }
  83185. if (this._physicsEngine.getImpostors().length === 0) {
  83186. return null;
  83187. }
  83188. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  83189. event.dispose(false);
  83190. return event;
  83191. };
  83192. return PhysicsHelper;
  83193. }());
  83194. BABYLON.PhysicsHelper = PhysicsHelper;
  83195. /***** Radial explosion *****/
  83196. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  83197. function PhysicsRadialExplosionEvent(scene) {
  83198. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  83199. this._rays = [];
  83200. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  83201. this._scene = scene;
  83202. }
  83203. /**
  83204. * Returns the data related to the radial explosion event (sphere & rays).
  83205. * @returns {PhysicsRadialExplosionEventData}
  83206. */
  83207. PhysicsRadialExplosionEvent.prototype.getData = function () {
  83208. this._dataFetched = true;
  83209. return {
  83210. sphere: this._sphere,
  83211. rays: this._rays,
  83212. };
  83213. };
  83214. /**
  83215. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  83216. * @param impostor
  83217. * @param {Vector3} origin the origin of the explosion
  83218. * @param {number} radius the explosion radius
  83219. * @param {number} strength the explosion strength
  83220. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  83221. * @returns {Nullable<PhysicsForceAndContactPoint>}
  83222. */
  83223. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  83224. if (impostor.mass === 0) {
  83225. return null;
  83226. }
  83227. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  83228. return null;
  83229. }
  83230. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  83231. return null;
  83232. }
  83233. var impostorObjectCenter = impostor.getObjectCenter();
  83234. var direction = impostorObjectCenter.subtract(origin);
  83235. var ray = new BABYLON.Ray(origin, direction, radius);
  83236. this._rays.push(ray);
  83237. var hit = ray.intersectsMesh(impostor.object);
  83238. var contactPoint = hit.pickedPoint;
  83239. if (!contactPoint) {
  83240. return null;
  83241. }
  83242. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  83243. if (distanceFromOrigin > radius) {
  83244. return null;
  83245. }
  83246. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  83247. ? strength
  83248. : strength * (1 - (distanceFromOrigin / radius));
  83249. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  83250. return { force: force, contactPoint: contactPoint };
  83251. };
  83252. /**
  83253. * Disposes the sphere.
  83254. * @param {bolean} force
  83255. */
  83256. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  83257. var _this = this;
  83258. if (force === void 0) { force = true; }
  83259. if (force) {
  83260. this._sphere.dispose();
  83261. }
  83262. else {
  83263. setTimeout(function () {
  83264. if (!_this._dataFetched) {
  83265. _this._sphere.dispose();
  83266. }
  83267. }, 0);
  83268. }
  83269. };
  83270. /*** Helpers ***/
  83271. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  83272. if (!this._sphere) {
  83273. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  83274. this._sphere.isVisible = false;
  83275. }
  83276. };
  83277. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  83278. var impostorObject = impostor.object;
  83279. this._prepareSphere();
  83280. this._sphere.position = origin;
  83281. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  83282. this._sphere._updateBoundingInfo();
  83283. this._sphere.computeWorldMatrix(true);
  83284. return this._sphere.intersectsMesh(impostorObject, true);
  83285. };
  83286. return PhysicsRadialExplosionEvent;
  83287. }());
  83288. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  83289. /***** Gravitational Field *****/
  83290. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  83291. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  83292. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83293. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83294. this._physicsHelper = physicsHelper;
  83295. this._scene = scene;
  83296. this._origin = origin;
  83297. this._radius = radius;
  83298. this._strength = strength;
  83299. this._falloff = falloff;
  83300. this._tickCallback = this._tick.bind(this);
  83301. }
  83302. /**
  83303. * Returns the data related to the gravitational field event (sphere).
  83304. * @returns {PhysicsGravitationalFieldEventData}
  83305. */
  83306. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  83307. this._dataFetched = true;
  83308. return {
  83309. sphere: this._sphere,
  83310. };
  83311. };
  83312. /**
  83313. * Enables the gravitational field.
  83314. */
  83315. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  83316. this._tickCallback.call(this);
  83317. this._scene.registerBeforeRender(this._tickCallback);
  83318. };
  83319. /**
  83320. * Disables the gravitational field.
  83321. */
  83322. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  83323. this._scene.unregisterBeforeRender(this._tickCallback);
  83324. };
  83325. /**
  83326. * Disposes the sphere.
  83327. * @param {bolean} force
  83328. */
  83329. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  83330. var _this = this;
  83331. if (force === void 0) { force = true; }
  83332. if (force) {
  83333. this._sphere.dispose();
  83334. }
  83335. else {
  83336. setTimeout(function () {
  83337. if (!_this._dataFetched) {
  83338. _this._sphere.dispose();
  83339. }
  83340. }, 0);
  83341. }
  83342. };
  83343. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  83344. // Since the params won't change, we fetch the event only once
  83345. if (this._sphere) {
  83346. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  83347. }
  83348. else {
  83349. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  83350. if (radialExplosionEvent) {
  83351. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  83352. }
  83353. }
  83354. };
  83355. return PhysicsGravitationalFieldEvent;
  83356. }());
  83357. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  83358. /***** Updraft *****/
  83359. var PhysicsUpdraftEvent = /** @class */ (function () {
  83360. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  83361. this._scene = _scene;
  83362. this._origin = _origin;
  83363. this._radius = _radius;
  83364. this._strength = _strength;
  83365. this._height = _height;
  83366. this._updraftMode = _updraftMode;
  83367. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  83368. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  83369. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  83370. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83371. this._physicsEngine = this._scene.getPhysicsEngine();
  83372. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  83373. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  83374. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  83375. this._originDirection = this._origin.subtract(this._originTop).normalize();
  83376. }
  83377. this._tickCallback = this._tick.bind(this);
  83378. }
  83379. /**
  83380. * Returns the data related to the updraft event (cylinder).
  83381. * @returns {PhysicsUpdraftEventData}
  83382. */
  83383. PhysicsUpdraftEvent.prototype.getData = function () {
  83384. this._dataFetched = true;
  83385. return {
  83386. cylinder: this._cylinder,
  83387. };
  83388. };
  83389. /**
  83390. * Enables the updraft.
  83391. */
  83392. PhysicsUpdraftEvent.prototype.enable = function () {
  83393. this._tickCallback.call(this);
  83394. this._scene.registerBeforeRender(this._tickCallback);
  83395. };
  83396. /**
  83397. * Disables the cortex.
  83398. */
  83399. PhysicsUpdraftEvent.prototype.disable = function () {
  83400. this._scene.unregisterBeforeRender(this._tickCallback);
  83401. };
  83402. /**
  83403. * Disposes the sphere.
  83404. * @param {bolean} force
  83405. */
  83406. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  83407. var _this = this;
  83408. if (force === void 0) { force = true; }
  83409. if (force) {
  83410. this._cylinder.dispose();
  83411. }
  83412. else {
  83413. setTimeout(function () {
  83414. if (!_this._dataFetched) {
  83415. _this._cylinder.dispose();
  83416. }
  83417. }, 0);
  83418. }
  83419. };
  83420. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  83421. if (impostor.mass === 0) {
  83422. return null;
  83423. }
  83424. if (!this._intersectsWithCylinder(impostor)) {
  83425. return null;
  83426. }
  83427. var impostorObjectCenter = impostor.getObjectCenter();
  83428. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  83429. var direction = this._originDirection;
  83430. }
  83431. else {
  83432. var direction = impostorObjectCenter.subtract(this._originTop);
  83433. }
  83434. var multiplier = this._strength * -1;
  83435. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  83436. return { force: force, contactPoint: impostorObjectCenter };
  83437. };
  83438. PhysicsUpdraftEvent.prototype._tick = function () {
  83439. var _this = this;
  83440. this._physicsEngine.getImpostors().forEach(function (impostor) {
  83441. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  83442. if (!impostorForceAndContactPoint) {
  83443. return;
  83444. }
  83445. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83446. });
  83447. };
  83448. /*** Helpers ***/
  83449. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  83450. if (!this._cylinder) {
  83451. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  83452. height: this._height,
  83453. diameter: this._radius * 2,
  83454. }, this._scene);
  83455. this._cylinder.isVisible = false;
  83456. }
  83457. };
  83458. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  83459. var impostorObject = impostor.object;
  83460. this._prepareCylinder();
  83461. this._cylinder.position = this._cylinderPosition;
  83462. return this._cylinder.intersectsMesh(impostorObject, true);
  83463. };
  83464. return PhysicsUpdraftEvent;
  83465. }());
  83466. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  83467. /***** Vortex *****/
  83468. var PhysicsVortexEvent = /** @class */ (function () {
  83469. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  83470. this._scene = _scene;
  83471. this._origin = _origin;
  83472. this._radius = _radius;
  83473. this._strength = _strength;
  83474. this._height = _height;
  83475. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  83476. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  83477. this._updraftMultiplier = 0.02;
  83478. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  83479. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83480. this._physicsEngine = this._scene.getPhysicsEngine();
  83481. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  83482. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  83483. this._tickCallback = this._tick.bind(this);
  83484. }
  83485. /**
  83486. * Returns the data related to the vortex event (cylinder).
  83487. * @returns {PhysicsVortexEventData}
  83488. */
  83489. PhysicsVortexEvent.prototype.getData = function () {
  83490. this._dataFetched = true;
  83491. return {
  83492. cylinder: this._cylinder,
  83493. };
  83494. };
  83495. /**
  83496. * Enables the vortex.
  83497. */
  83498. PhysicsVortexEvent.prototype.enable = function () {
  83499. this._tickCallback.call(this);
  83500. this._scene.registerBeforeRender(this._tickCallback);
  83501. };
  83502. /**
  83503. * Disables the cortex.
  83504. */
  83505. PhysicsVortexEvent.prototype.disable = function () {
  83506. this._scene.unregisterBeforeRender(this._tickCallback);
  83507. };
  83508. /**
  83509. * Disposes the sphere.
  83510. * @param {bolean} force
  83511. */
  83512. PhysicsVortexEvent.prototype.dispose = function (force) {
  83513. var _this = this;
  83514. if (force === void 0) { force = true; }
  83515. if (force) {
  83516. this._cylinder.dispose();
  83517. }
  83518. else {
  83519. setTimeout(function () {
  83520. if (!_this._dataFetched) {
  83521. _this._cylinder.dispose();
  83522. }
  83523. }, 0);
  83524. }
  83525. };
  83526. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  83527. if (impostor.mass === 0) {
  83528. return null;
  83529. }
  83530. if (!this._intersectsWithCylinder(impostor)) {
  83531. return null;
  83532. }
  83533. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  83534. return null;
  83535. }
  83536. var impostorObjectCenter = impostor.getObjectCenter();
  83537. var originOnPlane = new BABYLON.Vector3(this._origin.x, impostorObjectCenter.y, this._origin.z); // the distance to the origin as if both objects were on a plane (Y-axis)
  83538. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  83539. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  83540. var hit = ray.intersectsMesh(impostor.object);
  83541. var contactPoint = hit.pickedPoint;
  83542. if (!contactPoint) {
  83543. return null;
  83544. }
  83545. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  83546. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  83547. var directionToOrigin = contactPoint.normalize();
  83548. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83549. directionToOrigin = directionToOrigin.negate();
  83550. }
  83551. // TODO: find a more physically based solution
  83552. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83553. var forceX = directionToOrigin.x * this._strength / 8;
  83554. var forceY = directionToOrigin.y * this._updraftMultiplier;
  83555. var forceZ = directionToOrigin.z * this._strength / 8;
  83556. }
  83557. else {
  83558. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  83559. var forceY = this._originTop.y * this._updraftMultiplier;
  83560. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  83561. }
  83562. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  83563. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  83564. return { force: force, contactPoint: impostorObjectCenter };
  83565. };
  83566. PhysicsVortexEvent.prototype._tick = function () {
  83567. var _this = this;
  83568. this._physicsEngine.getImpostors().forEach(function (impostor) {
  83569. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  83570. if (!impostorForceAndContactPoint) {
  83571. return;
  83572. }
  83573. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83574. });
  83575. };
  83576. /*** Helpers ***/
  83577. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  83578. if (!this._cylinder) {
  83579. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  83580. height: this._height,
  83581. diameter: this._radius * 2,
  83582. }, this._scene);
  83583. this._cylinder.isVisible = false;
  83584. }
  83585. };
  83586. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  83587. var impostorObject = impostor.object;
  83588. this._prepareCylinder();
  83589. this._cylinder.position = this._cylinderPosition;
  83590. return this._cylinder.intersectsMesh(impostorObject, true);
  83591. };
  83592. return PhysicsVortexEvent;
  83593. }());
  83594. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  83595. /***** Enums *****/
  83596. /**
  83597. * The strenght of the force in correspondence to the distance of the affected object
  83598. */
  83599. var PhysicsRadialImpulseFalloff;
  83600. (function (PhysicsRadialImpulseFalloff) {
  83601. /** Defines that impulse is constant in strength across it's whole radius */
  83602. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  83603. /** DEfines that impulse gets weaker if it's further from the origin */
  83604. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  83605. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  83606. /**
  83607. * The strenght of the force in correspondence to the distance of the affected object
  83608. */
  83609. var PhysicsUpdraftMode;
  83610. (function (PhysicsUpdraftMode) {
  83611. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  83612. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  83613. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  83614. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  83615. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  83616. })(BABYLON || (BABYLON = {}));
  83617. //# sourceMappingURL=babylon.physicsHelper.js.map
  83618. var BABYLON;
  83619. (function (BABYLON) {
  83620. var CannonJSPlugin = /** @class */ (function () {
  83621. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  83622. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  83623. if (iterations === void 0) { iterations = 10; }
  83624. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  83625. this.name = "CannonJSPlugin";
  83626. this._physicsMaterials = new Array();
  83627. this._fixedTimeStep = 1 / 60;
  83628. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  83629. this.BJSCANNON = CANNON;
  83630. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  83631. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  83632. this._tmpPosition = BABYLON.Vector3.Zero();
  83633. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  83634. this._tmpUnityRotation = new BABYLON.Quaternion();
  83635. if (!this.isSupported()) {
  83636. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  83637. return;
  83638. }
  83639. this._extendNamespace();
  83640. this.world = new this.BJSCANNON.World();
  83641. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  83642. this.world.solver.iterations = iterations;
  83643. }
  83644. CannonJSPlugin.prototype.setGravity = function (gravity) {
  83645. this.world.gravity.copy(gravity);
  83646. };
  83647. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  83648. this._fixedTimeStep = timeStep;
  83649. };
  83650. CannonJSPlugin.prototype.getTimeStep = function () {
  83651. return this._fixedTimeStep;
  83652. };
  83653. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  83654. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  83655. };
  83656. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83657. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83658. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83659. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  83660. };
  83661. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83662. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83663. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83664. impostor.physicsBody.applyForce(impulse, worldPoint);
  83665. };
  83666. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83667. //parent-child relationship. Does this impostor has a parent impostor?
  83668. if (impostor.parent) {
  83669. if (impostor.physicsBody) {
  83670. this.removePhysicsBody(impostor);
  83671. //TODO is that needed?
  83672. impostor.forceUpdate();
  83673. }
  83674. return;
  83675. }
  83676. //should a new body be created for this impostor?
  83677. if (impostor.isBodyInitRequired()) {
  83678. var shape = this._createShape(impostor);
  83679. //unregister events, if body is being changed
  83680. var oldBody = impostor.physicsBody;
  83681. if (oldBody) {
  83682. this.removePhysicsBody(impostor);
  83683. }
  83684. //create the body and material
  83685. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  83686. var bodyCreationObject = {
  83687. mass: impostor.getParam("mass"),
  83688. material: material
  83689. };
  83690. // A simple extend, in case native options were used.
  83691. var nativeOptions = impostor.getParam("nativeOptions");
  83692. for (var key in nativeOptions) {
  83693. if (nativeOptions.hasOwnProperty(key)) {
  83694. bodyCreationObject[key] = nativeOptions[key];
  83695. }
  83696. }
  83697. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  83698. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  83699. this.world.addEventListener("preStep", impostor.beforeStep);
  83700. this.world.addEventListener("postStep", impostor.afterStep);
  83701. impostor.physicsBody.addShape(shape);
  83702. this.world.add(impostor.physicsBody);
  83703. //try to keep the body moving in the right direction by taking old properties.
  83704. //Should be tested!
  83705. if (oldBody) {
  83706. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  83707. impostor.physicsBody[param].copy(oldBody[param]);
  83708. });
  83709. }
  83710. this._processChildMeshes(impostor);
  83711. }
  83712. //now update the body's transformation
  83713. this._updatePhysicsBodyTransformation(impostor);
  83714. };
  83715. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  83716. var _this = this;
  83717. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  83718. var currentRotation = mainImpostor.object.rotationQuaternion;
  83719. if (meshChildren.length) {
  83720. var processMesh = function (localPosition, mesh) {
  83721. if (!currentRotation || !mesh.rotationQuaternion) {
  83722. return;
  83723. }
  83724. var childImpostor = mesh.getPhysicsImpostor();
  83725. if (childImpostor) {
  83726. var parent = childImpostor.parent;
  83727. if (parent !== mainImpostor) {
  83728. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  83729. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  83730. if (childImpostor.physicsBody) {
  83731. _this.removePhysicsBody(childImpostor);
  83732. childImpostor.physicsBody = null;
  83733. }
  83734. childImpostor.parent = mainImpostor;
  83735. childImpostor.resetUpdateFlags();
  83736. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new _this.BJSCANNON.Vec3(pPosition.x, pPosition.y, pPosition.z), new _this.BJSCANNON.Quaternion(localRotation.x, localRotation.y, localRotation.z, localRotation.w));
  83737. //Add the mass of the children.
  83738. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  83739. }
  83740. }
  83741. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  83742. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  83743. };
  83744. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  83745. }
  83746. };
  83747. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83748. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  83749. this.world.removeEventListener("preStep", impostor.beforeStep);
  83750. this.world.removeEventListener("postStep", impostor.afterStep);
  83751. this.world.remove(impostor.physicsBody);
  83752. };
  83753. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83754. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83755. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83756. if (!mainBody || !connectedBody) {
  83757. return;
  83758. }
  83759. var constraint;
  83760. var jointData = impostorJoint.joint.jointData;
  83761. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  83762. var constraintData = {
  83763. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  83764. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  83765. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  83766. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  83767. maxForce: jointData.nativeParams.maxForce,
  83768. collideConnected: !!jointData.collision
  83769. };
  83770. switch (impostorJoint.joint.type) {
  83771. case BABYLON.PhysicsJoint.HingeJoint:
  83772. case BABYLON.PhysicsJoint.Hinge2Joint:
  83773. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  83774. break;
  83775. case BABYLON.PhysicsJoint.DistanceJoint:
  83776. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  83777. break;
  83778. case BABYLON.PhysicsJoint.SpringJoint:
  83779. var springData = jointData;
  83780. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  83781. restLength: springData.length,
  83782. stiffness: springData.stiffness,
  83783. damping: springData.damping,
  83784. localAnchorA: constraintData.pivotA,
  83785. localAnchorB: constraintData.pivotB
  83786. });
  83787. break;
  83788. case BABYLON.PhysicsJoint.LockJoint:
  83789. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  83790. break;
  83791. case BABYLON.PhysicsJoint.PointToPointJoint:
  83792. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83793. default:
  83794. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  83795. break;
  83796. }
  83797. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  83798. constraint.collideConnected = !!jointData.collision;
  83799. impostorJoint.joint.physicsJoint = constraint;
  83800. //don't add spring as constraint, as it is not one.
  83801. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  83802. this.world.addConstraint(constraint);
  83803. }
  83804. else {
  83805. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  83806. constraint.applyForce();
  83807. });
  83808. }
  83809. };
  83810. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83811. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  83812. };
  83813. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  83814. var index;
  83815. var mat;
  83816. for (index = 0; index < this._physicsMaterials.length; index++) {
  83817. mat = this._physicsMaterials[index];
  83818. if (mat.friction === friction && mat.restitution === restitution) {
  83819. return mat;
  83820. }
  83821. }
  83822. var currentMat = new this.BJSCANNON.Material(name);
  83823. currentMat.friction = friction;
  83824. currentMat.restitution = restitution;
  83825. this._physicsMaterials.push(currentMat);
  83826. return currentMat;
  83827. };
  83828. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  83829. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  83830. };
  83831. CannonJSPlugin.prototype._createShape = function (impostor) {
  83832. var object = impostor.object;
  83833. var returnValue;
  83834. var extendSize = impostor.getObjectExtendSize();
  83835. switch (impostor.type) {
  83836. case BABYLON.PhysicsImpostor.SphereImpostor:
  83837. var radiusX = extendSize.x;
  83838. var radiusY = extendSize.y;
  83839. var radiusZ = extendSize.z;
  83840. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  83841. break;
  83842. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  83843. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83844. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  83845. break;
  83846. case BABYLON.PhysicsImpostor.BoxImpostor:
  83847. var box = extendSize.scale(0.5);
  83848. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  83849. break;
  83850. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83851. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  83852. returnValue = new this.BJSCANNON.Plane();
  83853. break;
  83854. case BABYLON.PhysicsImpostor.MeshImpostor:
  83855. // should transform the vertex data to world coordinates!!
  83856. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  83857. var rawFaces = object.getIndices ? object.getIndices() : [];
  83858. if (!rawVerts)
  83859. return;
  83860. // get only scale! so the object could transform correctly.
  83861. var oldPosition = object.position.clone();
  83862. var oldRotation = object.rotation && object.rotation.clone();
  83863. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  83864. object.position.copyFromFloats(0, 0, 0);
  83865. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83866. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83867. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83868. var transform = object.computeWorldMatrix(true);
  83869. // convert rawVerts to object space
  83870. var temp = new Array();
  83871. var index;
  83872. for (index = 0; index < rawVerts.length; index += 3) {
  83873. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  83874. }
  83875. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  83876. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  83877. //now set back the transformation!
  83878. object.position.copyFrom(oldPosition);
  83879. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  83880. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  83881. break;
  83882. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  83883. var oldPosition2 = object.position.clone();
  83884. var oldRotation2 = object.rotation && object.rotation.clone();
  83885. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  83886. object.position.copyFromFloats(0, 0, 0);
  83887. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83888. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83889. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83890. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  83891. returnValue = this._createHeightmap(object);
  83892. object.position.copyFrom(oldPosition2);
  83893. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  83894. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  83895. object.computeWorldMatrix(true);
  83896. break;
  83897. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83898. returnValue = new this.BJSCANNON.Particle();
  83899. break;
  83900. }
  83901. return returnValue;
  83902. };
  83903. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  83904. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83905. var transform = object.computeWorldMatrix(true);
  83906. // convert rawVerts to object space
  83907. var temp = new Array();
  83908. var index;
  83909. for (index = 0; index < pos.length; index += 3) {
  83910. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  83911. }
  83912. pos = temp;
  83913. var matrix = new Array();
  83914. //For now pointDepth will not be used and will be automatically calculated.
  83915. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  83916. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  83917. var boundingInfo = object.getBoundingInfo();
  83918. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  83919. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  83920. var elementSize = dim * 2 / arraySize;
  83921. for (var i = 0; i < pos.length; i = i + 3) {
  83922. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  83923. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  83924. var y = -pos[i + 2] + minY;
  83925. if (!matrix[x]) {
  83926. matrix[x] = [];
  83927. }
  83928. if (!matrix[x][z]) {
  83929. matrix[x][z] = y;
  83930. }
  83931. matrix[x][z] = Math.max(y, matrix[x][z]);
  83932. }
  83933. for (var x = 0; x <= arraySize; ++x) {
  83934. if (!matrix[x]) {
  83935. var loc = 1;
  83936. while (!matrix[(x + loc) % arraySize]) {
  83937. loc++;
  83938. }
  83939. matrix[x] = matrix[(x + loc) % arraySize].slice();
  83940. //console.log("missing x", x);
  83941. }
  83942. for (var z = 0; z <= arraySize; ++z) {
  83943. if (!matrix[x][z]) {
  83944. var loc = 1;
  83945. var newValue;
  83946. while (newValue === undefined) {
  83947. newValue = matrix[x][(z + loc++) % arraySize];
  83948. }
  83949. matrix[x][z] = newValue;
  83950. }
  83951. }
  83952. }
  83953. var shape = new this.BJSCANNON.Heightfield(matrix, {
  83954. elementSize: elementSize
  83955. });
  83956. //For future reference, needed for body transformation
  83957. shape.minY = minY;
  83958. return shape;
  83959. };
  83960. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  83961. var object = impostor.object;
  83962. //make sure it is updated...
  83963. object.computeWorldMatrix && object.computeWorldMatrix(true);
  83964. // The delta between the mesh position and the mesh bounding box center
  83965. var bInfo = object.getBoundingInfo();
  83966. if (!bInfo)
  83967. return;
  83968. var center = impostor.getObjectCenter();
  83969. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  83970. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  83971. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  83972. this._tmpPosition.copyFrom(center);
  83973. var quaternion = object.rotationQuaternion;
  83974. if (!quaternion) {
  83975. return;
  83976. }
  83977. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  83978. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  83979. //-90 DEG in X, precalculated
  83980. quaternion = quaternion.multiply(this._minus90X);
  83981. //Invert! (Precalculated, 90 deg in X)
  83982. //No need to clone. this will never change.
  83983. impostor.setDeltaRotation(this._plus90X);
  83984. }
  83985. //If it is a heightfield, if should be centered.
  83986. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  83987. var mesh = object;
  83988. var boundingInfo = mesh.getBoundingInfo();
  83989. //calculate the correct body position:
  83990. var rotationQuaternion = mesh.rotationQuaternion;
  83991. mesh.rotationQuaternion = this._tmpUnityRotation;
  83992. mesh.computeWorldMatrix(true);
  83993. //get original center with no rotation
  83994. var c = center.clone();
  83995. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  83996. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  83997. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  83998. mesh.setPreTransformMatrix(p);
  83999. mesh.computeWorldMatrix(true);
  84000. //calculate the translation
  84001. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  84002. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  84003. //add it inverted to the delta
  84004. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  84005. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  84006. //rotation is back
  84007. mesh.rotationQuaternion = rotationQuaternion;
  84008. mesh.setPreTransformMatrix(oldPivot);
  84009. mesh.computeWorldMatrix(true);
  84010. }
  84011. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  84012. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  84013. //this._tmpPosition.copyFrom(object.position);
  84014. }
  84015. impostor.setDeltaPosition(this._tmpDeltaPosition);
  84016. //Now update the impostor object
  84017. impostor.physicsBody.position.copy(this._tmpPosition);
  84018. impostor.physicsBody.quaternion.copy(quaternion);
  84019. };
  84020. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  84021. impostor.object.position.copyFrom(impostor.physicsBody.position);
  84022. if (impostor.object.rotationQuaternion) {
  84023. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  84024. }
  84025. };
  84026. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  84027. impostor.physicsBody.position.copy(newPosition);
  84028. impostor.physicsBody.quaternion.copy(newRotation);
  84029. };
  84030. CannonJSPlugin.prototype.isSupported = function () {
  84031. return this.BJSCANNON !== undefined;
  84032. };
  84033. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  84034. impostor.physicsBody.velocity.copy(velocity);
  84035. };
  84036. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  84037. impostor.physicsBody.angularVelocity.copy(velocity);
  84038. };
  84039. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  84040. var v = impostor.physicsBody.velocity;
  84041. if (!v) {
  84042. return null;
  84043. }
  84044. return new BABYLON.Vector3(v.x, v.y, v.z);
  84045. };
  84046. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  84047. var v = impostor.physicsBody.angularVelocity;
  84048. if (!v) {
  84049. return null;
  84050. }
  84051. return new BABYLON.Vector3(v.x, v.y, v.z);
  84052. };
  84053. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  84054. impostor.physicsBody.mass = mass;
  84055. impostor.physicsBody.updateMassProperties();
  84056. };
  84057. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  84058. return impostor.physicsBody.mass;
  84059. };
  84060. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  84061. return impostor.physicsBody.material.friction;
  84062. };
  84063. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  84064. impostor.physicsBody.material.friction = friction;
  84065. };
  84066. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  84067. return impostor.physicsBody.material.restitution;
  84068. };
  84069. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84070. impostor.physicsBody.material.restitution = restitution;
  84071. };
  84072. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  84073. impostor.physicsBody.sleep();
  84074. };
  84075. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  84076. impostor.physicsBody.wakeUp();
  84077. };
  84078. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84079. joint.physicsJoint.distance = maxDistance;
  84080. };
  84081. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84082. // if (!motorIndex) {
  84083. // joint.physicsJoint.enableMotor();
  84084. // }
  84085. // }
  84086. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84087. // if (!motorIndex) {
  84088. // joint.physicsJoint.disableMotor();
  84089. // }
  84090. // }
  84091. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84092. if (!motorIndex) {
  84093. joint.physicsJoint.enableMotor();
  84094. joint.physicsJoint.setMotorSpeed(speed);
  84095. if (maxForce) {
  84096. this.setLimit(joint, maxForce);
  84097. }
  84098. }
  84099. };
  84100. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  84101. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  84102. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  84103. };
  84104. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84105. var body = impostor.physicsBody;
  84106. mesh.position.x = body.position.x;
  84107. mesh.position.y = body.position.y;
  84108. mesh.position.z = body.position.z;
  84109. if (mesh.rotationQuaternion) {
  84110. mesh.rotationQuaternion.x = body.quaternion.x;
  84111. mesh.rotationQuaternion.y = body.quaternion.y;
  84112. mesh.rotationQuaternion.z = body.quaternion.z;
  84113. mesh.rotationQuaternion.w = body.quaternion.w;
  84114. }
  84115. };
  84116. CannonJSPlugin.prototype.getRadius = function (impostor) {
  84117. var shape = impostor.physicsBody.shapes[0];
  84118. return shape.boundingSphereRadius;
  84119. };
  84120. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84121. var shape = impostor.physicsBody.shapes[0];
  84122. result.x = shape.halfExtents.x * 2;
  84123. result.y = shape.halfExtents.y * 2;
  84124. result.z = shape.halfExtents.z * 2;
  84125. };
  84126. CannonJSPlugin.prototype.dispose = function () {
  84127. };
  84128. CannonJSPlugin.prototype._extendNamespace = function () {
  84129. //this will force cannon to execute at least one step when using interpolation
  84130. var step_tmp1 = new this.BJSCANNON.Vec3();
  84131. var Engine = this.BJSCANNON;
  84132. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  84133. maxSubSteps = maxSubSteps || 10;
  84134. timeSinceLastCalled = timeSinceLastCalled || 0;
  84135. if (timeSinceLastCalled === 0) {
  84136. this.internalStep(dt);
  84137. this.time += dt;
  84138. }
  84139. else {
  84140. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  84141. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  84142. var t0 = performance.now();
  84143. for (var i = 0; i !== internalSteps; i++) {
  84144. this.internalStep(dt);
  84145. if (performance.now() - t0 > dt * 1000) {
  84146. break;
  84147. }
  84148. }
  84149. this.time += timeSinceLastCalled;
  84150. var h = this.time % dt;
  84151. var h_div_dt = h / dt;
  84152. var interpvelo = step_tmp1;
  84153. var bodies = this.bodies;
  84154. for (var j = 0; j !== bodies.length; j++) {
  84155. var b = bodies[j];
  84156. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  84157. b.position.vsub(b.previousPosition, interpvelo);
  84158. interpvelo.scale(h_div_dt, interpvelo);
  84159. b.position.vadd(interpvelo, b.interpolatedPosition);
  84160. }
  84161. else {
  84162. b.interpolatedPosition.copy(b.position);
  84163. b.interpolatedQuaternion.copy(b.quaternion);
  84164. }
  84165. }
  84166. }
  84167. };
  84168. };
  84169. return CannonJSPlugin;
  84170. }());
  84171. BABYLON.CannonJSPlugin = CannonJSPlugin;
  84172. })(BABYLON || (BABYLON = {}));
  84173. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  84174. var BABYLON;
  84175. (function (BABYLON) {
  84176. var OimoJSPlugin = /** @class */ (function () {
  84177. function OimoJSPlugin(iterations) {
  84178. this.name = "OimoJSPlugin";
  84179. this._tmpImpostorsArray = [];
  84180. this._tmpPositionVector = BABYLON.Vector3.Zero();
  84181. this.BJSOIMO = OIMO;
  84182. this.world = new this.BJSOIMO.World({
  84183. iterations: iterations
  84184. });
  84185. this.world.clear();
  84186. }
  84187. OimoJSPlugin.prototype.setGravity = function (gravity) {
  84188. this.world.gravity.copy(gravity);
  84189. };
  84190. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  84191. this.world.timeStep = timeStep;
  84192. };
  84193. OimoJSPlugin.prototype.getTimeStep = function () {
  84194. return this.world.timeStep;
  84195. };
  84196. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  84197. var _this = this;
  84198. impostors.forEach(function (impostor) {
  84199. impostor.beforeStep();
  84200. });
  84201. this.world.step();
  84202. impostors.forEach(function (impostor) {
  84203. impostor.afterStep();
  84204. //update the ordered impostors array
  84205. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  84206. });
  84207. //check for collisions
  84208. var contact = this.world.contacts;
  84209. while (contact !== null) {
  84210. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  84211. contact = contact.next;
  84212. continue;
  84213. }
  84214. //is this body colliding with any other? get the impostor
  84215. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  84216. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  84217. if (!mainImpostor || !collidingImpostor) {
  84218. contact = contact.next;
  84219. continue;
  84220. }
  84221. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  84222. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  84223. contact = contact.next;
  84224. }
  84225. };
  84226. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  84227. var mass = impostor.physicsBody.mass;
  84228. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  84229. };
  84230. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  84231. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  84232. this.applyImpulse(impostor, force, contactPoint);
  84233. };
  84234. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  84235. var _this = this;
  84236. //parent-child relationship. Does this impostor has a parent impostor?
  84237. if (impostor.parent) {
  84238. if (impostor.physicsBody) {
  84239. this.removePhysicsBody(impostor);
  84240. //TODO is that needed?
  84241. impostor.forceUpdate();
  84242. }
  84243. return;
  84244. }
  84245. if (impostor.isBodyInitRequired()) {
  84246. var bodyConfig = {
  84247. name: impostor.uniqueId,
  84248. //Oimo must have mass, also for static objects.
  84249. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  84250. size: [],
  84251. type: [],
  84252. pos: [],
  84253. posShape: [],
  84254. rot: [],
  84255. rotShape: [],
  84256. move: impostor.getParam("mass") !== 0,
  84257. density: impostor.getParam("mass"),
  84258. friction: impostor.getParam("friction"),
  84259. restitution: impostor.getParam("restitution"),
  84260. //Supporting older versions of Oimo
  84261. world: this.world
  84262. };
  84263. var impostors = [impostor];
  84264. var addToArray = function (parent) {
  84265. if (!parent.getChildMeshes)
  84266. return;
  84267. parent.getChildMeshes().forEach(function (m) {
  84268. if (m.physicsImpostor) {
  84269. impostors.push(m.physicsImpostor);
  84270. //m.physicsImpostor._init();
  84271. }
  84272. });
  84273. };
  84274. addToArray(impostor.object);
  84275. var checkWithEpsilon_1 = function (value) {
  84276. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  84277. };
  84278. impostors.forEach(function (i) {
  84279. if (!i.object.rotationQuaternion) {
  84280. return;
  84281. }
  84282. //get the correct bounding box
  84283. var oldQuaternion = i.object.rotationQuaternion;
  84284. var rot = oldQuaternion.toEulerAngles();
  84285. var extendSize = i.getObjectExtendSize();
  84286. var radToDeg = 57.295779513082320876;
  84287. if (i === impostor) {
  84288. var center = impostor.getObjectCenter();
  84289. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  84290. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  84291. //Can also use Array.prototype.push.apply
  84292. bodyConfig.pos.push(center.x);
  84293. bodyConfig.pos.push(center.y);
  84294. bodyConfig.pos.push(center.z);
  84295. bodyConfig.posShape.push(0, 0, 0);
  84296. //tmp solution
  84297. bodyConfig.rot.push(rot.x * radToDeg);
  84298. bodyConfig.rot.push(rot.y * radToDeg);
  84299. bodyConfig.rot.push(rot.z * radToDeg);
  84300. bodyConfig.rotShape.push(0, 0, 0);
  84301. }
  84302. else {
  84303. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  84304. bodyConfig.posShape.push(localPosition.x);
  84305. bodyConfig.posShape.push(localPosition.y);
  84306. bodyConfig.posShape.push(localPosition.z);
  84307. bodyConfig.pos.push(0, 0, 0);
  84308. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  84309. bodyConfig.rot.push(0);
  84310. bodyConfig.rot.push(0);
  84311. bodyConfig.rot.push(0);
  84312. bodyConfig.rotShape.push(rot.x * radToDeg);
  84313. bodyConfig.rotShape.push(rot.y * radToDeg);
  84314. bodyConfig.rotShape.push(rot.z * radToDeg);
  84315. }
  84316. // register mesh
  84317. switch (i.type) {
  84318. case BABYLON.PhysicsImpostor.ParticleImpostor:
  84319. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  84320. case BABYLON.PhysicsImpostor.SphereImpostor:
  84321. var radiusX = extendSize.x;
  84322. var radiusY = extendSize.y;
  84323. var radiusZ = extendSize.z;
  84324. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  84325. bodyConfig.type.push('sphere');
  84326. //due to the way oimo works with compounds, add 3 times
  84327. bodyConfig.size.push(size);
  84328. bodyConfig.size.push(size);
  84329. bodyConfig.size.push(size);
  84330. break;
  84331. case BABYLON.PhysicsImpostor.CylinderImpostor:
  84332. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  84333. var sizeY = checkWithEpsilon_1(extendSize.y);
  84334. bodyConfig.type.push('cylinder');
  84335. bodyConfig.size.push(sizeX);
  84336. bodyConfig.size.push(sizeY);
  84337. //due to the way oimo works with compounds, add one more value.
  84338. bodyConfig.size.push(sizeY);
  84339. break;
  84340. case BABYLON.PhysicsImpostor.PlaneImpostor:
  84341. case BABYLON.PhysicsImpostor.BoxImpostor:
  84342. default:
  84343. var sizeX = checkWithEpsilon_1(extendSize.x);
  84344. var sizeY = checkWithEpsilon_1(extendSize.y);
  84345. var sizeZ = checkWithEpsilon_1(extendSize.z);
  84346. bodyConfig.type.push('box');
  84347. //if (i === impostor) {
  84348. bodyConfig.size.push(sizeX);
  84349. bodyConfig.size.push(sizeY);
  84350. bodyConfig.size.push(sizeZ);
  84351. //} else {
  84352. // bodyConfig.size.push(0,0,0);
  84353. //}
  84354. break;
  84355. }
  84356. //actually not needed, but hey...
  84357. i.object.rotationQuaternion = oldQuaternion;
  84358. });
  84359. impostor.physicsBody = this.world.add(bodyConfig);
  84360. }
  84361. else {
  84362. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  84363. }
  84364. impostor.setDeltaPosition(this._tmpPositionVector);
  84365. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  84366. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  84367. };
  84368. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  84369. //impostor.physicsBody.dispose();
  84370. //Same as : (older oimo versions)
  84371. this.world.removeRigidBody(impostor.physicsBody);
  84372. };
  84373. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  84374. var mainBody = impostorJoint.mainImpostor.physicsBody;
  84375. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  84376. if (!mainBody || !connectedBody) {
  84377. return;
  84378. }
  84379. var jointData = impostorJoint.joint.jointData;
  84380. var options = jointData.nativeParams || {};
  84381. var type;
  84382. var nativeJointData = {
  84383. body1: mainBody,
  84384. body2: connectedBody,
  84385. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  84386. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  84387. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  84388. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  84389. min: options.min,
  84390. max: options.max,
  84391. collision: options.collision || jointData.collision,
  84392. spring: options.spring,
  84393. //supporting older version of Oimo
  84394. world: this.world
  84395. };
  84396. switch (impostorJoint.joint.type) {
  84397. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  84398. type = "jointBall";
  84399. break;
  84400. case BABYLON.PhysicsJoint.SpringJoint:
  84401. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  84402. var springData = jointData;
  84403. nativeJointData.min = springData.length || nativeJointData.min;
  84404. //Max should also be set, just make sure it is at least min
  84405. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  84406. case BABYLON.PhysicsJoint.DistanceJoint:
  84407. type = "jointDistance";
  84408. nativeJointData.max = jointData.maxDistance;
  84409. break;
  84410. case BABYLON.PhysicsJoint.PrismaticJoint:
  84411. type = "jointPrisme";
  84412. break;
  84413. case BABYLON.PhysicsJoint.SliderJoint:
  84414. type = "jointSlide";
  84415. break;
  84416. case BABYLON.PhysicsJoint.WheelJoint:
  84417. type = "jointWheel";
  84418. break;
  84419. case BABYLON.PhysicsJoint.HingeJoint:
  84420. default:
  84421. type = "jointHinge";
  84422. break;
  84423. }
  84424. nativeJointData.type = type;
  84425. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  84426. };
  84427. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  84428. //Bug in Oimo prevents us from disposing a joint in the playground
  84429. //joint.joint.physicsJoint.dispose();
  84430. //So we will bruteforce it!
  84431. try {
  84432. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  84433. }
  84434. catch (e) {
  84435. BABYLON.Tools.Warn(e);
  84436. }
  84437. };
  84438. OimoJSPlugin.prototype.isSupported = function () {
  84439. return this.BJSOIMO !== undefined;
  84440. };
  84441. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  84442. if (!impostor.physicsBody.sleeping) {
  84443. //TODO check that
  84444. /*if (impostor.physicsBody.shapes.next) {
  84445. var parentShape = this._getLastShape(impostor.physicsBody);
  84446. impostor.object.position.copyFrom(parentShape.position);
  84447. console.log(parentShape.position);
  84448. } else {*/
  84449. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  84450. //}
  84451. if (impostor.object.rotationQuaternion) {
  84452. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  84453. }
  84454. }
  84455. };
  84456. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  84457. var body = impostor.physicsBody;
  84458. body.position.copy(newPosition);
  84459. body.orientation.copy(newRotation);
  84460. body.syncShapes();
  84461. body.awake();
  84462. };
  84463. /*private _getLastShape(body: any): any {
  84464. var lastShape = body.shapes;
  84465. while (lastShape.next) {
  84466. lastShape = lastShape.next;
  84467. }
  84468. return lastShape;
  84469. }*/
  84470. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  84471. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  84472. };
  84473. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  84474. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  84475. };
  84476. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  84477. var v = impostor.physicsBody.linearVelocity;
  84478. if (!v) {
  84479. return null;
  84480. }
  84481. return new BABYLON.Vector3(v.x, v.y, v.z);
  84482. };
  84483. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  84484. var v = impostor.physicsBody.angularVelocity;
  84485. if (!v) {
  84486. return null;
  84487. }
  84488. return new BABYLON.Vector3(v.x, v.y, v.z);
  84489. };
  84490. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  84491. var staticBody = mass === 0;
  84492. //this will actually set the body's density and not its mass.
  84493. //But this is how oimo treats the mass variable.
  84494. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  84495. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  84496. };
  84497. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  84498. return impostor.physicsBody.shapes.density;
  84499. };
  84500. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  84501. return impostor.physicsBody.shapes.friction;
  84502. };
  84503. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  84504. impostor.physicsBody.shapes.friction = friction;
  84505. };
  84506. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  84507. return impostor.physicsBody.shapes.restitution;
  84508. };
  84509. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84510. impostor.physicsBody.shapes.restitution = restitution;
  84511. };
  84512. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  84513. impostor.physicsBody.sleep();
  84514. };
  84515. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  84516. impostor.physicsBody.awake();
  84517. };
  84518. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84519. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  84520. if (minDistance !== void 0) {
  84521. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  84522. }
  84523. };
  84524. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84525. //TODO separate rotational and transational motors.
  84526. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84527. if (motor) {
  84528. motor.setMotor(speed, maxForce);
  84529. }
  84530. };
  84531. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  84532. //TODO separate rotational and transational motors.
  84533. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84534. if (motor) {
  84535. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  84536. }
  84537. };
  84538. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84539. var body = impostor.physicsBody;
  84540. mesh.position.x = body.position.x;
  84541. mesh.position.y = body.position.y;
  84542. mesh.position.z = body.position.z;
  84543. if (mesh.rotationQuaternion) {
  84544. mesh.rotationQuaternion.x = body.orientation.x;
  84545. mesh.rotationQuaternion.y = body.orientation.y;
  84546. mesh.rotationQuaternion.z = body.orientation.z;
  84547. mesh.rotationQuaternion.w = body.orientation.s;
  84548. }
  84549. };
  84550. OimoJSPlugin.prototype.getRadius = function (impostor) {
  84551. return impostor.physicsBody.shapes.radius;
  84552. };
  84553. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84554. var shape = impostor.physicsBody.shapes;
  84555. result.x = shape.halfWidth * 2;
  84556. result.y = shape.halfHeight * 2;
  84557. result.z = shape.halfDepth * 2;
  84558. };
  84559. OimoJSPlugin.prototype.dispose = function () {
  84560. this.world.clear();
  84561. };
  84562. return OimoJSPlugin;
  84563. }());
  84564. BABYLON.OimoJSPlugin = OimoJSPlugin;
  84565. })(BABYLON || (BABYLON = {}));
  84566. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  84567. var BABYLON;
  84568. (function (BABYLON) {
  84569. /*
  84570. * Based on jsTGALoader - Javascript loader for TGA file
  84571. * By Vincent Thibault
  84572. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  84573. */
  84574. var TGATools = /** @class */ (function () {
  84575. function TGATools() {
  84576. }
  84577. TGATools.GetTGAHeader = function (data) {
  84578. var offset = 0;
  84579. var header = {
  84580. id_length: data[offset++],
  84581. colormap_type: data[offset++],
  84582. image_type: data[offset++],
  84583. colormap_index: data[offset++] | data[offset++] << 8,
  84584. colormap_length: data[offset++] | data[offset++] << 8,
  84585. colormap_size: data[offset++],
  84586. origin: [
  84587. data[offset++] | data[offset++] << 8,
  84588. data[offset++] | data[offset++] << 8
  84589. ],
  84590. width: data[offset++] | data[offset++] << 8,
  84591. height: data[offset++] | data[offset++] << 8,
  84592. pixel_size: data[offset++],
  84593. flags: data[offset++]
  84594. };
  84595. return header;
  84596. };
  84597. TGATools.UploadContent = function (gl, data) {
  84598. // Not enough data to contain header ?
  84599. if (data.length < 19) {
  84600. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  84601. return;
  84602. }
  84603. // Read Header
  84604. var offset = 18;
  84605. var header = TGATools.GetTGAHeader(data);
  84606. // Assume it's a valid Targa file.
  84607. if (header.id_length + offset > data.length) {
  84608. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  84609. return;
  84610. }
  84611. // Skip not needed data
  84612. offset += header.id_length;
  84613. var use_rle = false;
  84614. var use_pal = false;
  84615. var use_grey = false;
  84616. // Get some informations.
  84617. switch (header.image_type) {
  84618. case TGATools._TYPE_RLE_INDEXED:
  84619. use_rle = true;
  84620. case TGATools._TYPE_INDEXED:
  84621. use_pal = true;
  84622. break;
  84623. case TGATools._TYPE_RLE_RGB:
  84624. use_rle = true;
  84625. case TGATools._TYPE_RGB:
  84626. // use_rgb = true;
  84627. break;
  84628. case TGATools._TYPE_RLE_GREY:
  84629. use_rle = true;
  84630. case TGATools._TYPE_GREY:
  84631. use_grey = true;
  84632. break;
  84633. }
  84634. var pixel_data;
  84635. // var numAlphaBits = header.flags & 0xf;
  84636. var pixel_size = header.pixel_size >> 3;
  84637. var pixel_total = header.width * header.height * pixel_size;
  84638. // Read palettes
  84639. var palettes;
  84640. if (use_pal) {
  84641. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  84642. }
  84643. // Read LRE
  84644. if (use_rle) {
  84645. pixel_data = new Uint8Array(pixel_total);
  84646. var c, count, i;
  84647. var localOffset = 0;
  84648. var pixels = new Uint8Array(pixel_size);
  84649. while (offset < pixel_total && localOffset < pixel_total) {
  84650. c = data[offset++];
  84651. count = (c & 0x7f) + 1;
  84652. // RLE pixels
  84653. if (c & 0x80) {
  84654. // Bind pixel tmp array
  84655. for (i = 0; i < pixel_size; ++i) {
  84656. pixels[i] = data[offset++];
  84657. }
  84658. // Copy pixel array
  84659. for (i = 0; i < count; ++i) {
  84660. pixel_data.set(pixels, localOffset + i * pixel_size);
  84661. }
  84662. localOffset += pixel_size * count;
  84663. }
  84664. // Raw pixels
  84665. else {
  84666. count *= pixel_size;
  84667. for (i = 0; i < count; ++i) {
  84668. pixel_data[localOffset + i] = data[offset++];
  84669. }
  84670. localOffset += count;
  84671. }
  84672. }
  84673. }
  84674. // RAW Pixels
  84675. else {
  84676. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  84677. }
  84678. // Load to texture
  84679. var x_start, y_start, x_step, y_step, y_end, x_end;
  84680. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  84681. default:
  84682. case TGATools._ORIGIN_UL:
  84683. x_start = 0;
  84684. x_step = 1;
  84685. x_end = header.width;
  84686. y_start = 0;
  84687. y_step = 1;
  84688. y_end = header.height;
  84689. break;
  84690. case TGATools._ORIGIN_BL:
  84691. x_start = 0;
  84692. x_step = 1;
  84693. x_end = header.width;
  84694. y_start = header.height - 1;
  84695. y_step = -1;
  84696. y_end = -1;
  84697. break;
  84698. case TGATools._ORIGIN_UR:
  84699. x_start = header.width - 1;
  84700. x_step = -1;
  84701. x_end = -1;
  84702. y_start = 0;
  84703. y_step = 1;
  84704. y_end = header.height;
  84705. break;
  84706. case TGATools._ORIGIN_BR:
  84707. x_start = header.width - 1;
  84708. x_step = -1;
  84709. x_end = -1;
  84710. y_start = header.height - 1;
  84711. y_step = -1;
  84712. y_end = -1;
  84713. break;
  84714. }
  84715. // Load the specify method
  84716. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  84717. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  84718. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  84719. };
  84720. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84721. var image = pixel_data, colormap = palettes;
  84722. var width = header.width, height = header.height;
  84723. var color, i = 0, x, y;
  84724. var imageData = new Uint8Array(width * height * 4);
  84725. for (y = y_start; y !== y_end; y += y_step) {
  84726. for (x = x_start; x !== x_end; x += x_step, i++) {
  84727. color = image[i];
  84728. imageData[(x + width * y) * 4 + 3] = 255;
  84729. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  84730. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  84731. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  84732. }
  84733. }
  84734. return imageData;
  84735. };
  84736. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84737. var image = pixel_data;
  84738. var width = header.width, height = header.height;
  84739. var color, i = 0, x, y;
  84740. var imageData = new Uint8Array(width * height * 4);
  84741. for (y = y_start; y !== y_end; y += y_step) {
  84742. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84743. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  84744. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  84745. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  84746. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  84747. imageData[(x + width * y) * 4 + 0] = r;
  84748. imageData[(x + width * y) * 4 + 1] = g;
  84749. imageData[(x + width * y) * 4 + 2] = b;
  84750. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  84751. }
  84752. }
  84753. return imageData;
  84754. };
  84755. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84756. var image = pixel_data;
  84757. var width = header.width, height = header.height;
  84758. var i = 0, x, y;
  84759. var imageData = new Uint8Array(width * height * 4);
  84760. for (y = y_start; y !== y_end; y += y_step) {
  84761. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  84762. imageData[(x + width * y) * 4 + 3] = 255;
  84763. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84764. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84765. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84766. }
  84767. }
  84768. return imageData;
  84769. };
  84770. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84771. var image = pixel_data;
  84772. var width = header.width, height = header.height;
  84773. var i = 0, x, y;
  84774. var imageData = new Uint8Array(width * height * 4);
  84775. for (y = y_start; y !== y_end; y += y_step) {
  84776. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  84777. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84778. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84779. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84780. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  84781. }
  84782. }
  84783. return imageData;
  84784. };
  84785. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84786. var image = pixel_data;
  84787. var width = header.width, height = header.height;
  84788. var color, i = 0, x, y;
  84789. var imageData = new Uint8Array(width * height * 4);
  84790. for (y = y_start; y !== y_end; y += y_step) {
  84791. for (x = x_start; x !== x_end; x += x_step, i++) {
  84792. color = image[i];
  84793. imageData[(x + width * y) * 4 + 0] = color;
  84794. imageData[(x + width * y) * 4 + 1] = color;
  84795. imageData[(x + width * y) * 4 + 2] = color;
  84796. imageData[(x + width * y) * 4 + 3] = 255;
  84797. }
  84798. }
  84799. return imageData;
  84800. };
  84801. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84802. var image = pixel_data;
  84803. var width = header.width, height = header.height;
  84804. var i = 0, x, y;
  84805. var imageData = new Uint8Array(width * height * 4);
  84806. for (y = y_start; y !== y_end; y += y_step) {
  84807. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84808. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  84809. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  84810. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84811. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  84812. }
  84813. }
  84814. return imageData;
  84815. };
  84816. //private static _TYPE_NO_DATA = 0;
  84817. TGATools._TYPE_INDEXED = 1;
  84818. TGATools._TYPE_RGB = 2;
  84819. TGATools._TYPE_GREY = 3;
  84820. TGATools._TYPE_RLE_INDEXED = 9;
  84821. TGATools._TYPE_RLE_RGB = 10;
  84822. TGATools._TYPE_RLE_GREY = 11;
  84823. TGATools._ORIGIN_MASK = 0x30;
  84824. TGATools._ORIGIN_SHIFT = 0x04;
  84825. TGATools._ORIGIN_BL = 0x00;
  84826. TGATools._ORIGIN_BR = 0x01;
  84827. TGATools._ORIGIN_UL = 0x02;
  84828. TGATools._ORIGIN_UR = 0x03;
  84829. return TGATools;
  84830. }());
  84831. BABYLON.TGATools = TGATools;
  84832. })(BABYLON || (BABYLON = {}));
  84833. //# sourceMappingURL=babylon.tga.js.map
  84834. var BABYLON;
  84835. (function (BABYLON) {
  84836. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  84837. // All values and structures referenced from:
  84838. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  84839. var DDS_MAGIC = 0x20534444;
  84840. var
  84841. //DDSD_CAPS = 0x1,
  84842. //DDSD_HEIGHT = 0x2,
  84843. //DDSD_WIDTH = 0x4,
  84844. //DDSD_PITCH = 0x8,
  84845. //DDSD_PIXELFORMAT = 0x1000,
  84846. DDSD_MIPMAPCOUNT = 0x20000;
  84847. //DDSD_LINEARSIZE = 0x80000,
  84848. //DDSD_DEPTH = 0x800000;
  84849. // var DDSCAPS_COMPLEX = 0x8,
  84850. // DDSCAPS_MIPMAP = 0x400000,
  84851. // DDSCAPS_TEXTURE = 0x1000;
  84852. var DDSCAPS2_CUBEMAP = 0x200;
  84853. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  84854. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  84855. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  84856. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  84857. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  84858. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  84859. // DDSCAPS2_VOLUME = 0x200000;
  84860. var
  84861. //DDPF_ALPHAPIXELS = 0x1,
  84862. //DDPF_ALPHA = 0x2,
  84863. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  84864. //DDPF_YUV = 0x200,
  84865. DDPF_LUMINANCE = 0x20000;
  84866. function FourCCToInt32(value) {
  84867. return value.charCodeAt(0) +
  84868. (value.charCodeAt(1) << 8) +
  84869. (value.charCodeAt(2) << 16) +
  84870. (value.charCodeAt(3) << 24);
  84871. }
  84872. function Int32ToFourCC(value) {
  84873. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  84874. }
  84875. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  84876. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  84877. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  84878. var FOURCC_DX10 = FourCCToInt32("DX10");
  84879. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  84880. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  84881. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  84882. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  84883. var headerLengthInt = 31; // The header length in 32 bit ints
  84884. // Offsets into the header array
  84885. var off_magic = 0;
  84886. var off_size = 1;
  84887. var off_flags = 2;
  84888. var off_height = 3;
  84889. var off_width = 4;
  84890. var off_mipmapCount = 7;
  84891. var off_pfFlags = 20;
  84892. var off_pfFourCC = 21;
  84893. var off_RGBbpp = 22;
  84894. var off_RMask = 23;
  84895. var off_GMask = 24;
  84896. var off_BMask = 25;
  84897. var off_AMask = 26;
  84898. // var off_caps1 = 27;
  84899. var off_caps2 = 28;
  84900. // var off_caps3 = 29;
  84901. // var off_caps4 = 30;
  84902. var off_dxgiFormat = 32;
  84903. ;
  84904. var DDSTools = /** @class */ (function () {
  84905. function DDSTools() {
  84906. }
  84907. DDSTools.GetDDSInfo = function (arrayBuffer) {
  84908. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84909. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  84910. var mipmapCount = 1;
  84911. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  84912. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84913. }
  84914. var fourCC = header[off_pfFourCC];
  84915. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  84916. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84917. switch (fourCC) {
  84918. case FOURCC_D3DFMT_R16G16B16A16F:
  84919. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84920. break;
  84921. case FOURCC_D3DFMT_R32G32B32A32F:
  84922. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84923. break;
  84924. case FOURCC_DX10:
  84925. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  84926. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84927. break;
  84928. }
  84929. }
  84930. return {
  84931. width: header[off_width],
  84932. height: header[off_height],
  84933. mipmapCount: mipmapCount,
  84934. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  84935. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  84936. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  84937. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  84938. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  84939. dxgiFormat: dxgiFormat,
  84940. textureType: textureType
  84941. };
  84942. };
  84943. DDSTools._ToHalfFloat = function (value) {
  84944. if (!DDSTools._FloatView) {
  84945. DDSTools._FloatView = new Float32Array(1);
  84946. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  84947. }
  84948. DDSTools._FloatView[0] = value;
  84949. var x = DDSTools._Int32View[0];
  84950. var bits = (x >> 16) & 0x8000; /* Get the sign */
  84951. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  84952. var e = (x >> 23) & 0xff; /* Using int is faster here */
  84953. /* If zero, or denormal, or exponent underflows too much for a denormal
  84954. * half, return signed zero. */
  84955. if (e < 103) {
  84956. return bits;
  84957. }
  84958. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  84959. if (e > 142) {
  84960. bits |= 0x7c00;
  84961. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  84962. * not Inf, so make sure we set one mantissa bit too. */
  84963. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  84964. return bits;
  84965. }
  84966. /* If exponent underflows but not too much, return a denormal */
  84967. if (e < 113) {
  84968. m |= 0x0800;
  84969. /* Extra rounding may overflow and set mantissa to 0 and exponent
  84970. * to 1, which is OK. */
  84971. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  84972. return bits;
  84973. }
  84974. bits |= ((e - 112) << 10) | (m >> 1);
  84975. bits += m & 1;
  84976. return bits;
  84977. };
  84978. DDSTools._FromHalfFloat = function (value) {
  84979. var s = (value & 0x8000) >> 15;
  84980. var e = (value & 0x7C00) >> 10;
  84981. var f = value & 0x03FF;
  84982. if (e === 0) {
  84983. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  84984. }
  84985. else if (e == 0x1F) {
  84986. return f ? NaN : ((s ? -1 : 1) * Infinity);
  84987. }
  84988. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  84989. };
  84990. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84991. var destArray = new Float32Array(dataLength);
  84992. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84993. var index = 0;
  84994. for (var y = 0; y < height; y++) {
  84995. for (var x = 0; x < width; x++) {
  84996. var srcPos = (x + y * width) * 4;
  84997. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  84998. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  84999. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  85000. if (DDSTools.StoreLODInAlphaChannel) {
  85001. destArray[index + 3] = lod;
  85002. }
  85003. else {
  85004. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  85005. }
  85006. index += 4;
  85007. }
  85008. }
  85009. return destArray;
  85010. };
  85011. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85012. if (DDSTools.StoreLODInAlphaChannel) {
  85013. var destArray = new Uint16Array(dataLength);
  85014. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85015. var index = 0;
  85016. for (var y = 0; y < height; y++) {
  85017. for (var x = 0; x < width; x++) {
  85018. var srcPos = (x + y * width) * 4;
  85019. destArray[index] = srcData[srcPos];
  85020. destArray[index + 1] = srcData[srcPos + 1];
  85021. destArray[index + 2] = srcData[srcPos + 2];
  85022. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  85023. index += 4;
  85024. }
  85025. }
  85026. return destArray;
  85027. }
  85028. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  85029. };
  85030. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85031. if (DDSTools.StoreLODInAlphaChannel) {
  85032. var destArray = new Float32Array(dataLength);
  85033. var srcData = new Float32Array(arrayBuffer, dataOffset);
  85034. var index = 0;
  85035. for (var y = 0; y < height; y++) {
  85036. for (var x = 0; x < width; x++) {
  85037. var srcPos = (x + y * width) * 4;
  85038. destArray[index] = srcData[srcPos];
  85039. destArray[index + 1] = srcData[srcPos + 1];
  85040. destArray[index + 2] = srcData[srcPos + 2];
  85041. destArray[index + 3] = lod;
  85042. index += 4;
  85043. }
  85044. }
  85045. return destArray;
  85046. }
  85047. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  85048. };
  85049. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85050. var destArray = new Uint8Array(dataLength);
  85051. var srcData = new Float32Array(arrayBuffer, dataOffset);
  85052. var index = 0;
  85053. for (var y = 0; y < height; y++) {
  85054. for (var x = 0; x < width; x++) {
  85055. var srcPos = (x + y * width) * 4;
  85056. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  85057. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  85058. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  85059. if (DDSTools.StoreLODInAlphaChannel) {
  85060. destArray[index + 3] = lod;
  85061. }
  85062. else {
  85063. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  85064. }
  85065. index += 4;
  85066. }
  85067. }
  85068. return destArray;
  85069. };
  85070. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85071. var destArray = new Uint8Array(dataLength);
  85072. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85073. var index = 0;
  85074. for (var y = 0; y < height; y++) {
  85075. for (var x = 0; x < width; x++) {
  85076. var srcPos = (x + y * width) * 4;
  85077. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  85078. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  85079. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  85080. if (DDSTools.StoreLODInAlphaChannel) {
  85081. destArray[index + 3] = lod;
  85082. }
  85083. else {
  85084. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  85085. }
  85086. index += 4;
  85087. }
  85088. }
  85089. return destArray;
  85090. };
  85091. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  85092. var byteArray = new Uint8Array(dataLength);
  85093. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85094. var index = 0;
  85095. for (var y = 0; y < height; y++) {
  85096. for (var x = 0; x < width; x++) {
  85097. var srcPos = (x + y * width) * 4;
  85098. byteArray[index] = srcData[srcPos + rOffset];
  85099. byteArray[index + 1] = srcData[srcPos + gOffset];
  85100. byteArray[index + 2] = srcData[srcPos + bOffset];
  85101. byteArray[index + 3] = srcData[srcPos + aOffset];
  85102. index += 4;
  85103. }
  85104. }
  85105. return byteArray;
  85106. };
  85107. DDSTools._ExtractLongWordOrder = function (value) {
  85108. if (value === 0 || value === 255 || value === -16777216) {
  85109. return 0;
  85110. }
  85111. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  85112. };
  85113. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  85114. var byteArray = new Uint8Array(dataLength);
  85115. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85116. var index = 0;
  85117. for (var y = 0; y < height; y++) {
  85118. for (var x = 0; x < width; x++) {
  85119. var srcPos = (x + y * width) * 3;
  85120. byteArray[index] = srcData[srcPos + rOffset];
  85121. byteArray[index + 1] = srcData[srcPos + gOffset];
  85122. byteArray[index + 2] = srcData[srcPos + bOffset];
  85123. index += 3;
  85124. }
  85125. }
  85126. return byteArray;
  85127. };
  85128. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  85129. var byteArray = new Uint8Array(dataLength);
  85130. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85131. var index = 0;
  85132. for (var y = 0; y < height; y++) {
  85133. for (var x = 0; x < width; x++) {
  85134. var srcPos = (x + y * width);
  85135. byteArray[index] = srcData[srcPos];
  85136. index++;
  85137. }
  85138. }
  85139. return byteArray;
  85140. };
  85141. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  85142. if (lodIndex === void 0) { lodIndex = -1; }
  85143. var sphericalPolynomialFaces = null;
  85144. if (info.sphericalPolynomial) {
  85145. sphericalPolynomialFaces = new Array();
  85146. }
  85147. var ext = engine.getCaps().s3tc;
  85148. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  85149. var fourCC, width, height, dataLength = 0, dataOffset;
  85150. var byteArray, mipmapCount, mip;
  85151. var internalFormat = 0;
  85152. var format = 0;
  85153. var blockBytes = 1;
  85154. if (header[off_magic] !== DDS_MAGIC) {
  85155. BABYLON.Tools.Error("Invalid magic number in DDS header");
  85156. return;
  85157. }
  85158. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  85159. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  85160. return;
  85161. }
  85162. if (info.isCompressed && !ext) {
  85163. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  85164. return;
  85165. }
  85166. var bpp = header[off_RGBbpp];
  85167. dataOffset = header[off_size] + 4;
  85168. var computeFormats = false;
  85169. if (info.isFourCC) {
  85170. fourCC = header[off_pfFourCC];
  85171. switch (fourCC) {
  85172. case FOURCC_DXT1:
  85173. blockBytes = 8;
  85174. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  85175. break;
  85176. case FOURCC_DXT3:
  85177. blockBytes = 16;
  85178. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  85179. break;
  85180. case FOURCC_DXT5:
  85181. blockBytes = 16;
  85182. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  85183. break;
  85184. case FOURCC_D3DFMT_R16G16B16A16F:
  85185. computeFormats = true;
  85186. break;
  85187. case FOURCC_D3DFMT_R32G32B32A32F:
  85188. computeFormats = true;
  85189. break;
  85190. case FOURCC_DX10:
  85191. // There is an additionnal header so dataOffset need to be changed
  85192. dataOffset += 5 * 4; // 5 uints
  85193. var supported = false;
  85194. switch (info.dxgiFormat) {
  85195. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  85196. computeFormats = true;
  85197. supported = true;
  85198. break;
  85199. case DXGI_FORMAT_B8G8R8X8_UNORM:
  85200. info.isRGB = true;
  85201. info.isFourCC = false;
  85202. bpp = 32;
  85203. supported = true;
  85204. break;
  85205. }
  85206. if (supported) {
  85207. break;
  85208. }
  85209. default:
  85210. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  85211. return;
  85212. }
  85213. }
  85214. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  85215. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  85216. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  85217. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  85218. if (computeFormats) {
  85219. format = engine._getWebGLTextureType(info.textureType);
  85220. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85221. }
  85222. mipmapCount = 1;
  85223. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  85224. mipmapCount = Math.max(1, header[off_mipmapCount]);
  85225. }
  85226. for (var face = 0; face < faces; face++) {
  85227. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  85228. width = header[off_width];
  85229. height = header[off_height];
  85230. for (mip = 0; mip < mipmapCount; ++mip) {
  85231. if (lodIndex === -1 || lodIndex === mip) {
  85232. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  85233. var i = (lodIndex === -1) ? mip : 0;
  85234. if (!info.isCompressed && info.isFourCC) {
  85235. dataLength = width * height * 4;
  85236. var floatArray = null;
  85237. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  85238. if (bpp === 128) {
  85239. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85240. if (sphericalPolynomialFaces && i == 0) {
  85241. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85242. }
  85243. }
  85244. else if (bpp === 64) {
  85245. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85246. if (sphericalPolynomialFaces && i == 0) {
  85247. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85248. }
  85249. }
  85250. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  85251. format = engine._getWebGLTextureType(info.textureType);
  85252. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85253. }
  85254. else {
  85255. if (bpp === 128) {
  85256. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85257. if (sphericalPolynomialFaces && i == 0) {
  85258. sphericalPolynomialFaces.push(floatArray);
  85259. }
  85260. }
  85261. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  85262. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85263. if (sphericalPolynomialFaces && i == 0) {
  85264. sphericalPolynomialFaces.push(floatArray);
  85265. }
  85266. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  85267. format = engine._getWebGLTextureType(info.textureType);
  85268. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85269. }
  85270. else { // 64
  85271. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85272. if (sphericalPolynomialFaces && i == 0) {
  85273. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85274. }
  85275. }
  85276. }
  85277. if (floatArray) {
  85278. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  85279. }
  85280. }
  85281. else if (info.isRGB) {
  85282. if (bpp === 24) {
  85283. dataLength = width * height * 3;
  85284. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  85285. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  85286. }
  85287. else { // 32
  85288. dataLength = width * height * 4;
  85289. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  85290. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  85291. }
  85292. }
  85293. else if (info.isLuminance) {
  85294. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  85295. var unpaddedRowSize = width;
  85296. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  85297. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  85298. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  85299. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  85300. }
  85301. else {
  85302. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  85303. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  85304. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  85305. }
  85306. }
  85307. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  85308. width *= 0.5;
  85309. height *= 0.5;
  85310. width = Math.max(1.0, width);
  85311. height = Math.max(1.0, height);
  85312. }
  85313. if (currentFace !== undefined) {
  85314. // Loading a single face
  85315. break;
  85316. }
  85317. }
  85318. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  85319. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  85320. size: header[off_width],
  85321. right: sphericalPolynomialFaces[0],
  85322. left: sphericalPolynomialFaces[1],
  85323. up: sphericalPolynomialFaces[2],
  85324. down: sphericalPolynomialFaces[3],
  85325. front: sphericalPolynomialFaces[4],
  85326. back: sphericalPolynomialFaces[5],
  85327. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  85328. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  85329. gammaSpace: false,
  85330. });
  85331. }
  85332. else {
  85333. info.sphericalPolynomial = undefined;
  85334. }
  85335. };
  85336. DDSTools.StoreLODInAlphaChannel = false;
  85337. return DDSTools;
  85338. }());
  85339. BABYLON.DDSTools = DDSTools;
  85340. })(BABYLON || (BABYLON = {}));
  85341. //# sourceMappingURL=babylon.dds.js.map
  85342. var BABYLON;
  85343. (function (BABYLON) {
  85344. /**
  85345. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  85346. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  85347. */
  85348. var KhronosTextureContainer = /** @class */ (function () {
  85349. /**
  85350. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  85351. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  85352. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  85353. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  85354. */
  85355. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  85356. this.arrayBuffer = arrayBuffer;
  85357. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  85358. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  85359. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  85360. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  85361. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  85362. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  85363. BABYLON.Tools.Error("texture missing KTX identifier");
  85364. return;
  85365. }
  85366. // load the reset of the header in native 32 bit int
  85367. var header = new Int32Array(this.arrayBuffer, 12, 13);
  85368. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  85369. var oppositeEndianess = header[0] === 0x01020304;
  85370. // read all the header elements in order they exist in the file, without modification (sans endainness)
  85371. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  85372. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  85373. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  85374. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  85375. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  85376. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  85377. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  85378. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  85379. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  85380. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  85381. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  85382. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  85383. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  85384. if (this.glType !== 0) {
  85385. BABYLON.Tools.Error("only compressed formats currently supported");
  85386. return;
  85387. }
  85388. else {
  85389. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  85390. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  85391. }
  85392. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  85393. BABYLON.Tools.Error("only 2D textures currently supported");
  85394. return;
  85395. }
  85396. if (this.numberOfArrayElements !== 0) {
  85397. BABYLON.Tools.Error("texture arrays not currently supported");
  85398. return;
  85399. }
  85400. if (this.numberOfFaces !== facesExpected) {
  85401. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  85402. return;
  85403. }
  85404. // we now have a completely validated file, so could use existence of loadType as success
  85405. // would need to make this more elaborate & adjust checks above to support more than one load type
  85406. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  85407. }
  85408. // not as fast hardware based, but will probably never need to use
  85409. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  85410. return ((val & 0xFF) << 24)
  85411. | ((val & 0xFF00) << 8)
  85412. | ((val >> 8) & 0xFF00)
  85413. | ((val >> 24) & 0xFF);
  85414. };
  85415. /**
  85416. * It is assumed that the texture has already been created & is currently bound
  85417. */
  85418. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  85419. switch (this.loadType) {
  85420. case KhronosTextureContainer.COMPRESSED_2D:
  85421. this._upload2DCompressedLevels(gl, loadMipmaps);
  85422. break;
  85423. case KhronosTextureContainer.TEX_2D:
  85424. case KhronosTextureContainer.COMPRESSED_3D:
  85425. case KhronosTextureContainer.TEX_3D:
  85426. }
  85427. };
  85428. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  85429. // initialize width & height for level 1
  85430. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  85431. var width = this.pixelWidth;
  85432. var height = this.pixelHeight;
  85433. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  85434. for (var level = 0; level < mipmapCount; level++) {
  85435. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  85436. for (var face = 0; face < this.numberOfFaces; face++) {
  85437. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  85438. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  85439. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  85440. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  85441. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  85442. }
  85443. width = Math.max(1.0, width * 0.5);
  85444. height = Math.max(1.0, height * 0.5);
  85445. }
  85446. };
  85447. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  85448. // load types
  85449. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  85450. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  85451. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  85452. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  85453. return KhronosTextureContainer;
  85454. }());
  85455. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  85456. })(BABYLON || (BABYLON = {}));
  85457. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  85458. var BABYLON;
  85459. (function (BABYLON) {
  85460. var Debug;
  85461. (function (Debug) {
  85462. /**
  85463. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  85464. */
  85465. var SkeletonViewer = /** @class */ (function () {
  85466. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  85467. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  85468. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  85469. this.skeleton = skeleton;
  85470. this.mesh = mesh;
  85471. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  85472. this.renderingGroupId = renderingGroupId;
  85473. this.color = BABYLON.Color3.White();
  85474. this._debugLines = new Array();
  85475. this._isEnabled = false;
  85476. this._scene = scene;
  85477. this.update();
  85478. this._renderFunction = this.update.bind(this);
  85479. }
  85480. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  85481. get: function () {
  85482. return this._isEnabled;
  85483. },
  85484. set: function (value) {
  85485. if (this._isEnabled === value) {
  85486. return;
  85487. }
  85488. this._isEnabled = value;
  85489. if (value) {
  85490. this._scene.registerBeforeRender(this._renderFunction);
  85491. }
  85492. else {
  85493. this._scene.unregisterBeforeRender(this._renderFunction);
  85494. }
  85495. },
  85496. enumerable: true,
  85497. configurable: true
  85498. });
  85499. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  85500. if (x === void 0) { x = 0; }
  85501. if (y === void 0) { y = 0; }
  85502. if (z === void 0) { z = 0; }
  85503. var tmat = BABYLON.Tmp.Matrix[0];
  85504. var parentBone = bone.getParent();
  85505. tmat.copyFrom(bone.getLocalMatrix());
  85506. if (x !== 0 || y !== 0 || z !== 0) {
  85507. var tmat2 = BABYLON.Tmp.Matrix[1];
  85508. BABYLON.Matrix.IdentityToRef(tmat2);
  85509. tmat2.m[12] = x;
  85510. tmat2.m[13] = y;
  85511. tmat2.m[14] = z;
  85512. tmat2.multiplyToRef(tmat, tmat);
  85513. }
  85514. if (parentBone) {
  85515. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  85516. }
  85517. tmat.multiplyToRef(meshMat, tmat);
  85518. position.x = tmat.m[12];
  85519. position.y = tmat.m[13];
  85520. position.z = tmat.m[14];
  85521. };
  85522. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  85523. var len = bones.length;
  85524. var meshPos = this.mesh.position;
  85525. for (var i = 0; i < len; i++) {
  85526. var bone = bones[i];
  85527. var points = this._debugLines[i];
  85528. if (!points) {
  85529. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85530. this._debugLines[i] = points;
  85531. }
  85532. this._getBonePosition(points[0], bone, meshMat);
  85533. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  85534. points[0].subtractInPlace(meshPos);
  85535. points[1].subtractInPlace(meshPos);
  85536. }
  85537. };
  85538. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  85539. var len = bones.length;
  85540. var boneNum = 0;
  85541. var meshPos = this.mesh.position;
  85542. for (var i = len - 1; i >= 0; i--) {
  85543. var childBone = bones[i];
  85544. var parentBone = childBone.getParent();
  85545. if (!parentBone) {
  85546. continue;
  85547. }
  85548. var points = this._debugLines[boneNum];
  85549. if (!points) {
  85550. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85551. this._debugLines[boneNum] = points;
  85552. }
  85553. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  85554. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  85555. points[0].subtractInPlace(meshPos);
  85556. points[1].subtractInPlace(meshPos);
  85557. boneNum++;
  85558. }
  85559. };
  85560. SkeletonViewer.prototype.update = function () {
  85561. if (this.autoUpdateBonesMatrices) {
  85562. this.skeleton.computeAbsoluteTransforms();
  85563. }
  85564. if (this.skeleton.bones[0].length === undefined) {
  85565. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85566. }
  85567. else {
  85568. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85569. }
  85570. if (!this._debugMesh) {
  85571. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  85572. this._debugMesh.renderingGroupId = this.renderingGroupId;
  85573. }
  85574. else {
  85575. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  85576. }
  85577. this._debugMesh.position.copyFrom(this.mesh.position);
  85578. this._debugMesh.color = this.color;
  85579. };
  85580. SkeletonViewer.prototype.dispose = function () {
  85581. if (this._debugMesh) {
  85582. this.isEnabled = false;
  85583. this._debugMesh.dispose();
  85584. this._debugMesh = null;
  85585. }
  85586. };
  85587. return SkeletonViewer;
  85588. }());
  85589. Debug.SkeletonViewer = SkeletonViewer;
  85590. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85591. })(BABYLON || (BABYLON = {}));
  85592. //# sourceMappingURL=babylon.skeletonViewer.js.map
  85593. /**
  85594. * Module Debug contains the (visual) components to debug a scene correctly
  85595. */
  85596. var BABYLON;
  85597. (function (BABYLON) {
  85598. var Debug;
  85599. (function (Debug) {
  85600. /**
  85601. * The Axes viewer will show 3 axes in a specific point in space
  85602. */
  85603. var AxesViewer = /** @class */ (function () {
  85604. function AxesViewer(scene, scaleLines) {
  85605. if (scaleLines === void 0) { scaleLines = 1; }
  85606. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85607. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85608. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85609. this.scaleLines = 1;
  85610. this.scaleLines = scaleLines;
  85611. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  85612. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  85613. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  85614. this._xmesh.renderingGroupId = 2;
  85615. this._ymesh.renderingGroupId = 2;
  85616. this._zmesh.renderingGroupId = 2;
  85617. this._xmesh.material.checkReadyOnlyOnce = true;
  85618. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  85619. this._ymesh.material.checkReadyOnlyOnce = true;
  85620. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  85621. this._zmesh.material.checkReadyOnlyOnce = true;
  85622. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  85623. this.scene = scene;
  85624. }
  85625. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  85626. var scaleLines = this.scaleLines;
  85627. if (this._xmesh) {
  85628. this._xmesh.position.copyFrom(position);
  85629. }
  85630. if (this._ymesh) {
  85631. this._ymesh.position.copyFrom(position);
  85632. }
  85633. if (this._zmesh) {
  85634. this._zmesh.position.copyFrom(position);
  85635. }
  85636. var point2 = this._xline[1];
  85637. point2.x = xaxis.x * scaleLines;
  85638. point2.y = xaxis.y * scaleLines;
  85639. point2.z = xaxis.z * scaleLines;
  85640. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  85641. point2 = this._yline[1];
  85642. point2.x = yaxis.x * scaleLines;
  85643. point2.y = yaxis.y * scaleLines;
  85644. point2.z = yaxis.z * scaleLines;
  85645. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  85646. point2 = this._zline[1];
  85647. point2.x = zaxis.x * scaleLines;
  85648. point2.y = zaxis.y * scaleLines;
  85649. point2.z = zaxis.z * scaleLines;
  85650. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  85651. };
  85652. AxesViewer.prototype.dispose = function () {
  85653. if (this._xmesh) {
  85654. this._xmesh.dispose();
  85655. }
  85656. if (this._ymesh) {
  85657. this._ymesh.dispose();
  85658. }
  85659. if (this._zmesh) {
  85660. this._zmesh.dispose();
  85661. }
  85662. this._xmesh = null;
  85663. this._ymesh = null;
  85664. this._zmesh = null;
  85665. this.scene = null;
  85666. };
  85667. return AxesViewer;
  85668. }());
  85669. Debug.AxesViewer = AxesViewer;
  85670. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85671. })(BABYLON || (BABYLON = {}));
  85672. //# sourceMappingURL=babylon.axesViewer.js.map
  85673. var BABYLON;
  85674. (function (BABYLON) {
  85675. var Debug;
  85676. (function (Debug) {
  85677. /**
  85678. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  85679. */
  85680. var BoneAxesViewer = /** @class */ (function (_super) {
  85681. __extends(BoneAxesViewer, _super);
  85682. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  85683. if (scaleLines === void 0) { scaleLines = 1; }
  85684. var _this = _super.call(this, scene, scaleLines) || this;
  85685. _this.pos = BABYLON.Vector3.Zero();
  85686. _this.xaxis = BABYLON.Vector3.Zero();
  85687. _this.yaxis = BABYLON.Vector3.Zero();
  85688. _this.zaxis = BABYLON.Vector3.Zero();
  85689. _this.mesh = mesh;
  85690. _this.bone = bone;
  85691. return _this;
  85692. }
  85693. BoneAxesViewer.prototype.update = function () {
  85694. if (!this.mesh || !this.bone) {
  85695. return;
  85696. }
  85697. var bone = this.bone;
  85698. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  85699. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  85700. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  85701. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  85702. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  85703. };
  85704. BoneAxesViewer.prototype.dispose = function () {
  85705. if (this.mesh) {
  85706. this.mesh = null;
  85707. this.bone = null;
  85708. _super.prototype.dispose.call(this);
  85709. }
  85710. };
  85711. return BoneAxesViewer;
  85712. }(Debug.AxesViewer));
  85713. Debug.BoneAxesViewer = BoneAxesViewer;
  85714. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85715. })(BABYLON || (BABYLON = {}));
  85716. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  85717. var BABYLON;
  85718. (function (BABYLON) {
  85719. var RayHelper = /** @class */ (function () {
  85720. function RayHelper(ray) {
  85721. this.ray = ray;
  85722. }
  85723. RayHelper.CreateAndShow = function (ray, scene, color) {
  85724. var helper = new RayHelper(ray);
  85725. helper.show(scene, color);
  85726. return helper;
  85727. };
  85728. RayHelper.prototype.show = function (scene, color) {
  85729. if (!this._renderFunction && this.ray) {
  85730. var ray = this.ray;
  85731. this._renderFunction = this._render.bind(this);
  85732. this._scene = scene;
  85733. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  85734. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  85735. if (this._renderFunction) {
  85736. this._scene.registerBeforeRender(this._renderFunction);
  85737. }
  85738. }
  85739. if (color && this._renderLine) {
  85740. this._renderLine.color.copyFrom(color);
  85741. }
  85742. };
  85743. RayHelper.prototype.hide = function () {
  85744. if (this._renderFunction && this._scene) {
  85745. this._scene.unregisterBeforeRender(this._renderFunction);
  85746. this._scene = null;
  85747. this._renderFunction = null;
  85748. if (this._renderLine) {
  85749. this._renderLine.dispose();
  85750. this._renderLine = null;
  85751. }
  85752. this._renderPoints = [];
  85753. }
  85754. };
  85755. RayHelper.prototype._render = function () {
  85756. var ray = this.ray;
  85757. if (!ray) {
  85758. return;
  85759. }
  85760. var point = this._renderPoints[1];
  85761. var len = Math.min(ray.length, 1000000);
  85762. point.copyFrom(ray.direction);
  85763. point.scaleInPlace(len);
  85764. point.addInPlace(ray.origin);
  85765. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  85766. };
  85767. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  85768. this._attachedToMesh = mesh;
  85769. var ray = this.ray;
  85770. if (!ray) {
  85771. return;
  85772. }
  85773. if (!ray.direction) {
  85774. ray.direction = BABYLON.Vector3.Zero();
  85775. }
  85776. if (!ray.origin) {
  85777. ray.origin = BABYLON.Vector3.Zero();
  85778. }
  85779. if (length) {
  85780. ray.length = length;
  85781. }
  85782. if (!meshSpaceOrigin) {
  85783. meshSpaceOrigin = BABYLON.Vector3.Zero();
  85784. }
  85785. if (!meshSpaceDirection) {
  85786. // -1 so that this will work with Mesh.lookAt
  85787. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  85788. }
  85789. if (!this._meshSpaceDirection) {
  85790. this._meshSpaceDirection = meshSpaceDirection.clone();
  85791. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  85792. }
  85793. else {
  85794. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  85795. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  85796. }
  85797. if (!this._updateToMeshFunction) {
  85798. this._updateToMeshFunction = this._updateToMesh.bind(this);
  85799. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  85800. }
  85801. this._updateToMesh();
  85802. };
  85803. RayHelper.prototype.detachFromMesh = function () {
  85804. if (this._attachedToMesh) {
  85805. if (this._updateToMeshFunction) {
  85806. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  85807. }
  85808. this._attachedToMesh = null;
  85809. this._updateToMeshFunction = null;
  85810. }
  85811. };
  85812. RayHelper.prototype._updateToMesh = function () {
  85813. var ray = this.ray;
  85814. if (!this._attachedToMesh || !ray) {
  85815. return;
  85816. }
  85817. if (this._attachedToMesh._isDisposed) {
  85818. this.detachFromMesh();
  85819. return;
  85820. }
  85821. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  85822. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  85823. };
  85824. RayHelper.prototype.dispose = function () {
  85825. this.hide();
  85826. this.detachFromMesh();
  85827. this.ray = null;
  85828. };
  85829. return RayHelper;
  85830. }());
  85831. BABYLON.RayHelper = RayHelper;
  85832. })(BABYLON || (BABYLON = {}));
  85833. //# sourceMappingURL=babylon.rayHelper.js.map
  85834. var BABYLON;
  85835. (function (BABYLON) {
  85836. // load the inspector using require, if not present in the global namespace.
  85837. var DebugLayer = /** @class */ (function () {
  85838. function DebugLayer(scene) {
  85839. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85840. this._scene = scene;
  85841. // load inspector using require, if it doesn't exist on the global namespace.
  85842. }
  85843. /** Creates the inspector window. */
  85844. DebugLayer.prototype._createInspector = function (config) {
  85845. if (config === void 0) { config = {}; }
  85846. var popup = config.popup || false;
  85847. var initialTab = config.initialTab || 0;
  85848. var parentElement = config.parentElement || null;
  85849. if (!this._inspector) {
  85850. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85851. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  85852. } // else nothing to do,; instance is already existing
  85853. };
  85854. DebugLayer.prototype.isVisible = function () {
  85855. if (!this._inspector) {
  85856. return false;
  85857. }
  85858. return true;
  85859. };
  85860. DebugLayer.prototype.hide = function () {
  85861. if (this._inspector) {
  85862. try {
  85863. this._inspector.dispose();
  85864. }
  85865. catch (e) {
  85866. // If the inspector has been removed directly from the inspector tool
  85867. }
  85868. this._inspector = null;
  85869. }
  85870. };
  85871. DebugLayer.prototype.show = function (config) {
  85872. if (config === void 0) { config = {}; }
  85873. if (typeof this.BJSINSPECTOR == 'undefined') {
  85874. // Load inspector and add it to the DOM
  85875. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  85876. }
  85877. else {
  85878. // Otherwise creates the inspector
  85879. this._createInspector(config);
  85880. }
  85881. };
  85882. /**
  85883. * Gets the active tab
  85884. * @return the index of the active tab or -1 if the inspector is hidden
  85885. */
  85886. DebugLayer.prototype.getActiveTab = function () {
  85887. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  85888. };
  85889. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  85890. return DebugLayer;
  85891. }());
  85892. BABYLON.DebugLayer = DebugLayer;
  85893. })(BABYLON || (BABYLON = {}));
  85894. //# sourceMappingURL=babylon.debugLayer.js.map
  85895. var BABYLON;
  85896. (function (BABYLON) {
  85897. var Debug;
  85898. (function (Debug) {
  85899. /**
  85900. * Used to show the physics impostor around the specific mesh.
  85901. */
  85902. var PhysicsViewer = /** @class */ (function () {
  85903. function PhysicsViewer(scene) {
  85904. this._impostors = [];
  85905. this._meshes = [];
  85906. this._numMeshes = 0;
  85907. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85908. var physicEngine = this._scene.getPhysicsEngine();
  85909. if (physicEngine) {
  85910. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  85911. }
  85912. }
  85913. PhysicsViewer.prototype._updateDebugMeshes = function () {
  85914. var plugin = this._physicsEnginePlugin;
  85915. for (var i = 0; i < this._numMeshes; i++) {
  85916. var impostor = this._impostors[i];
  85917. if (!impostor) {
  85918. continue;
  85919. }
  85920. if (impostor.isDisposed) {
  85921. this.hideImpostor(this._impostors[i--]);
  85922. }
  85923. else {
  85924. var mesh = this._meshes[i];
  85925. if (mesh && plugin) {
  85926. plugin.syncMeshWithImpostor(mesh, impostor);
  85927. }
  85928. }
  85929. }
  85930. };
  85931. PhysicsViewer.prototype.showImpostor = function (impostor) {
  85932. if (!this._scene) {
  85933. return;
  85934. }
  85935. for (var i = 0; i < this._numMeshes; i++) {
  85936. if (this._impostors[i] == impostor) {
  85937. return;
  85938. }
  85939. }
  85940. var debugMesh = this._getDebugMesh(impostor, this._scene);
  85941. if (debugMesh) {
  85942. this._impostors[this._numMeshes] = impostor;
  85943. this._meshes[this._numMeshes] = debugMesh;
  85944. if (this._numMeshes === 0) {
  85945. this._renderFunction = this._updateDebugMeshes.bind(this);
  85946. this._scene.registerBeforeRender(this._renderFunction);
  85947. }
  85948. this._numMeshes++;
  85949. }
  85950. };
  85951. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  85952. if (!impostor || !this._scene) {
  85953. return;
  85954. }
  85955. var removed = false;
  85956. for (var i = 0; i < this._numMeshes; i++) {
  85957. if (this._impostors[i] == impostor) {
  85958. var mesh = this._meshes[i];
  85959. if (!mesh) {
  85960. continue;
  85961. }
  85962. this._scene.removeMesh(mesh);
  85963. mesh.dispose();
  85964. this._numMeshes--;
  85965. if (this._numMeshes > 0) {
  85966. this._meshes[i] = this._meshes[this._numMeshes];
  85967. this._impostors[i] = this._impostors[this._numMeshes];
  85968. this._meshes[this._numMeshes] = null;
  85969. this._impostors[this._numMeshes] = null;
  85970. }
  85971. else {
  85972. this._meshes[0] = null;
  85973. this._impostors[0] = null;
  85974. }
  85975. removed = true;
  85976. break;
  85977. }
  85978. }
  85979. if (removed && this._numMeshes === 0) {
  85980. this._scene.unregisterBeforeRender(this._renderFunction);
  85981. }
  85982. };
  85983. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  85984. if (!this._debugMaterial) {
  85985. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  85986. this._debugMaterial.wireframe = true;
  85987. }
  85988. return this._debugMaterial;
  85989. };
  85990. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  85991. if (!this._debugBoxMesh) {
  85992. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  85993. this._debugBoxMesh.renderingGroupId = 1;
  85994. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85995. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  85996. scene.removeMesh(this._debugBoxMesh);
  85997. }
  85998. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  85999. };
  86000. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  86001. if (!this._debugSphereMesh) {
  86002. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  86003. this._debugSphereMesh.renderingGroupId = 1;
  86004. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  86005. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  86006. scene.removeMesh(this._debugSphereMesh);
  86007. }
  86008. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  86009. };
  86010. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  86011. var mesh = null;
  86012. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  86013. mesh = this._getDebugBoxMesh(scene);
  86014. impostor.getBoxSizeToRef(mesh.scaling);
  86015. }
  86016. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  86017. mesh = this._getDebugSphereMesh(scene);
  86018. var radius = impostor.getRadius();
  86019. mesh.scaling.x = radius * 2;
  86020. mesh.scaling.y = radius * 2;
  86021. mesh.scaling.z = radius * 2;
  86022. }
  86023. return mesh;
  86024. };
  86025. PhysicsViewer.prototype.dispose = function () {
  86026. for (var i = 0; i < this._numMeshes; i++) {
  86027. this.hideImpostor(this._impostors[i]);
  86028. }
  86029. if (this._debugBoxMesh) {
  86030. this._debugBoxMesh.dispose();
  86031. }
  86032. if (this._debugSphereMesh) {
  86033. this._debugSphereMesh.dispose();
  86034. }
  86035. if (this._debugMaterial) {
  86036. this._debugMaterial.dispose();
  86037. }
  86038. this._impostors.length = 0;
  86039. this._scene = null;
  86040. this._physicsEnginePlugin = null;
  86041. };
  86042. return PhysicsViewer;
  86043. }());
  86044. Debug.PhysicsViewer = PhysicsViewer;
  86045. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86046. })(BABYLON || (BABYLON = {}));
  86047. //# sourceMappingURL=babylon.physicsViewer.js.map
  86048. var BABYLON;
  86049. (function (BABYLON) {
  86050. var BoundingBoxRenderer = /** @class */ (function () {
  86051. function BoundingBoxRenderer(scene) {
  86052. this.frontColor = new BABYLON.Color3(1, 1, 1);
  86053. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  86054. this.showBackLines = true;
  86055. this.renderList = new BABYLON.SmartArray(32);
  86056. this._vertexBuffers = {};
  86057. this._scene = scene;
  86058. }
  86059. BoundingBoxRenderer.prototype._prepareRessources = function () {
  86060. if (this._colorShader) {
  86061. return;
  86062. }
  86063. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  86064. attributes: [BABYLON.VertexBuffer.PositionKind],
  86065. uniforms: ["world", "viewProjection", "color"]
  86066. });
  86067. var engine = this._scene.getEngine();
  86068. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  86069. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  86070. this._createIndexBuffer();
  86071. };
  86072. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  86073. var engine = this._scene.getEngine();
  86074. this._indexBuffer = 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]);
  86075. };
  86076. BoundingBoxRenderer.prototype._rebuild = function () {
  86077. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86078. if (vb) {
  86079. vb._rebuild();
  86080. }
  86081. this._createIndexBuffer();
  86082. };
  86083. BoundingBoxRenderer.prototype.reset = function () {
  86084. this.renderList.reset();
  86085. };
  86086. BoundingBoxRenderer.prototype.render = function () {
  86087. if (this.renderList.length === 0) {
  86088. return;
  86089. }
  86090. this._prepareRessources();
  86091. if (!this._colorShader.isReady()) {
  86092. return;
  86093. }
  86094. var engine = this._scene.getEngine();
  86095. engine.setDepthWrite(false);
  86096. this._colorShader._preBind();
  86097. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  86098. var boundingBox = this.renderList.data[boundingBoxIndex];
  86099. var min = boundingBox.minimum;
  86100. var max = boundingBox.maximum;
  86101. var diff = max.subtract(min);
  86102. var median = min.add(diff.scale(0.5));
  86103. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  86104. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  86105. .multiply(boundingBox.getWorldMatrix());
  86106. // VBOs
  86107. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  86108. if (this.showBackLines) {
  86109. // Back
  86110. engine.setDepthFunctionToGreaterOrEqual();
  86111. this._scene.resetCachedMaterial();
  86112. this._colorShader.setColor4("color", this.backColor.toColor4());
  86113. this._colorShader.bind(worldMatrix);
  86114. // Draw order
  86115. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86116. }
  86117. // Front
  86118. engine.setDepthFunctionToLess();
  86119. this._scene.resetCachedMaterial();
  86120. this._colorShader.setColor4("color", this.frontColor.toColor4());
  86121. this._colorShader.bind(worldMatrix);
  86122. // Draw order
  86123. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86124. }
  86125. this._colorShader.unbind();
  86126. engine.setDepthFunctionToLessOrEqual();
  86127. engine.setDepthWrite(true);
  86128. };
  86129. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  86130. this._prepareRessources();
  86131. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  86132. return;
  86133. }
  86134. var engine = this._scene.getEngine();
  86135. engine.setDepthWrite(false);
  86136. engine.setColorWrite(false);
  86137. this._colorShader._preBind();
  86138. var boundingBox = mesh._boundingInfo.boundingBox;
  86139. var min = boundingBox.minimum;
  86140. var max = boundingBox.maximum;
  86141. var diff = max.subtract(min);
  86142. var median = min.add(diff.scale(0.5));
  86143. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  86144. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  86145. .multiply(boundingBox.getWorldMatrix());
  86146. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  86147. engine.setDepthFunctionToLess();
  86148. this._scene.resetCachedMaterial();
  86149. this._colorShader.bind(worldMatrix);
  86150. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86151. this._colorShader.unbind();
  86152. engine.setDepthFunctionToLessOrEqual();
  86153. engine.setDepthWrite(true);
  86154. engine.setColorWrite(true);
  86155. };
  86156. BoundingBoxRenderer.prototype.dispose = function () {
  86157. if (!this._colorShader) {
  86158. return;
  86159. }
  86160. this.renderList.dispose();
  86161. this._colorShader.dispose();
  86162. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86163. if (buffer) {
  86164. buffer.dispose();
  86165. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86166. }
  86167. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86168. };
  86169. return BoundingBoxRenderer;
  86170. }());
  86171. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  86172. })(BABYLON || (BABYLON = {}));
  86173. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  86174. var BABYLON;
  86175. (function (BABYLON) {
  86176. /**
  86177. * Renders a layer on top of an existing scene
  86178. */
  86179. var UtilityLayerRenderer = /** @class */ (function () {
  86180. /**
  86181. * Instantiates a UtilityLayerRenderer
  86182. * @param originalScene the original scene that will be rendered on top of
  86183. */
  86184. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  86185. var _this = this;
  86186. this.originalScene = originalScene;
  86187. /**
  86188. * If the utility layer should automatically be rendered on top of existing scene
  86189. */
  86190. this.shouldRender = true;
  86191. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  86192. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  86193. originalScene.getEngine().scenes.pop();
  86194. // Render directly on top of existing scene without clearing
  86195. this.utilityLayerScene.clearColor = new BABYLON.Color4(0, 0, 0, 0);
  86196. this.utilityLayerScene.autoClear = false;
  86197. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  86198. if (_this.shouldRender) {
  86199. _this.render();
  86200. }
  86201. });
  86202. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  86203. _this.dispose();
  86204. });
  86205. }
  86206. /**
  86207. * Renders the utility layers scene on top of the original scene
  86208. */
  86209. UtilityLayerRenderer.prototype.render = function () {
  86210. this._updateCamera();
  86211. this.utilityLayerScene.render();
  86212. };
  86213. /**
  86214. * Disposes of the renderer
  86215. */
  86216. UtilityLayerRenderer.prototype.dispose = function () {
  86217. if (this._afterRenderObserver) {
  86218. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  86219. }
  86220. if (this._sceneDisposeObserver) {
  86221. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  86222. }
  86223. this.utilityLayerScene.dispose();
  86224. };
  86225. UtilityLayerRenderer.prototype._updateCamera = function () {
  86226. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  86227. };
  86228. return UtilityLayerRenderer;
  86229. }());
  86230. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  86231. })(BABYLON || (BABYLON = {}));
  86232. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  86233. var BABYLON;
  86234. (function (BABYLON) {
  86235. /**
  86236. * Defines a target to use with MorphTargetManager
  86237. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  86238. */
  86239. var MorphTarget = /** @class */ (function () {
  86240. /**
  86241. * Creates a new MorphTarget
  86242. * @param name defines the name of the target
  86243. * @param influence defines the influence to use
  86244. */
  86245. function MorphTarget(
  86246. /** defines the name of the target */
  86247. name, influence, scene) {
  86248. if (influence === void 0) { influence = 0; }
  86249. if (scene === void 0) { scene = null; }
  86250. this.name = name;
  86251. /**
  86252. * Gets or sets the list of animations
  86253. */
  86254. this.animations = new Array();
  86255. this._positions = null;
  86256. this._normals = null;
  86257. this._tangents = null;
  86258. /**
  86259. * Observable raised when the influence changes
  86260. */
  86261. this.onInfluenceChanged = new BABYLON.Observable();
  86262. this._animationPropertiesOverride = null;
  86263. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86264. this.influence = influence;
  86265. }
  86266. Object.defineProperty(MorphTarget.prototype, "influence", {
  86267. /**
  86268. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  86269. */
  86270. get: function () {
  86271. return this._influence;
  86272. },
  86273. set: function (influence) {
  86274. if (this._influence === influence) {
  86275. return;
  86276. }
  86277. var previous = this._influence;
  86278. this._influence = influence;
  86279. if (this.onInfluenceChanged.hasObservers) {
  86280. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  86281. }
  86282. },
  86283. enumerable: true,
  86284. configurable: true
  86285. });
  86286. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  86287. /**
  86288. * Gets or sets the animation properties override
  86289. */
  86290. get: function () {
  86291. if (!this._animationPropertiesOverride && this._scene) {
  86292. return this._scene.animationPropertiesOverride;
  86293. }
  86294. return this._animationPropertiesOverride;
  86295. },
  86296. set: function (value) {
  86297. this._animationPropertiesOverride = value;
  86298. },
  86299. enumerable: true,
  86300. configurable: true
  86301. });
  86302. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  86303. /**
  86304. * Gets a boolean defining if the target contains position data
  86305. */
  86306. get: function () {
  86307. return !!this._positions;
  86308. },
  86309. enumerable: true,
  86310. configurable: true
  86311. });
  86312. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  86313. /**
  86314. * Gets a boolean defining if the target contains normal data
  86315. */
  86316. get: function () {
  86317. return !!this._normals;
  86318. },
  86319. enumerable: true,
  86320. configurable: true
  86321. });
  86322. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  86323. /**
  86324. * Gets a boolean defining if the target contains tangent data
  86325. */
  86326. get: function () {
  86327. return !!this._tangents;
  86328. },
  86329. enumerable: true,
  86330. configurable: true
  86331. });
  86332. /**
  86333. * Affects position data to this target
  86334. * @param data defines the position data to use
  86335. */
  86336. MorphTarget.prototype.setPositions = function (data) {
  86337. this._positions = data;
  86338. };
  86339. /**
  86340. * Gets the position data stored in this target
  86341. * @returns a FloatArray containing the position data (or null if not present)
  86342. */
  86343. MorphTarget.prototype.getPositions = function () {
  86344. return this._positions;
  86345. };
  86346. /**
  86347. * Affects normal data to this target
  86348. * @param data defines the normal data to use
  86349. */
  86350. MorphTarget.prototype.setNormals = function (data) {
  86351. this._normals = data;
  86352. };
  86353. /**
  86354. * Gets the normal data stored in this target
  86355. * @returns a FloatArray containing the normal data (or null if not present)
  86356. */
  86357. MorphTarget.prototype.getNormals = function () {
  86358. return this._normals;
  86359. };
  86360. /**
  86361. * Affects tangent data to this target
  86362. * @param data defines the tangent data to use
  86363. */
  86364. MorphTarget.prototype.setTangents = function (data) {
  86365. this._tangents = data;
  86366. };
  86367. /**
  86368. * Gets the tangent data stored in this target
  86369. * @returns a FloatArray containing the tangent data (or null if not present)
  86370. */
  86371. MorphTarget.prototype.getTangents = function () {
  86372. return this._tangents;
  86373. };
  86374. /**
  86375. * Serializes the current target into a Serialization object
  86376. * @returns the serialized object
  86377. */
  86378. MorphTarget.prototype.serialize = function () {
  86379. var serializationObject = {};
  86380. serializationObject.name = this.name;
  86381. serializationObject.influence = this.influence;
  86382. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  86383. if (this.hasNormals) {
  86384. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  86385. }
  86386. if (this.hasTangents) {
  86387. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  86388. }
  86389. // Animations
  86390. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  86391. return serializationObject;
  86392. };
  86393. // Statics
  86394. /**
  86395. * Creates a new target from serialized data
  86396. * @param serializationObject defines the serialized data to use
  86397. * @returns a new MorphTarget
  86398. */
  86399. MorphTarget.Parse = function (serializationObject) {
  86400. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  86401. result.setPositions(serializationObject.positions);
  86402. if (serializationObject.normals) {
  86403. result.setNormals(serializationObject.normals);
  86404. }
  86405. if (serializationObject.tangents) {
  86406. result.setTangents(serializationObject.tangents);
  86407. }
  86408. // Animations
  86409. if (serializationObject.animations) {
  86410. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  86411. var parsedAnimation = serializationObject.animations[animationIndex];
  86412. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  86413. }
  86414. }
  86415. return result;
  86416. };
  86417. /**
  86418. * Creates a MorphTarget from mesh data
  86419. * @param mesh defines the source mesh
  86420. * @param name defines the name to use for the new target
  86421. * @param influence defines the influence to attach to the target
  86422. * @returns a new MorphTarget
  86423. */
  86424. MorphTarget.FromMesh = function (mesh, name, influence) {
  86425. if (!name) {
  86426. name = mesh.name;
  86427. }
  86428. var result = new MorphTarget(name, influence, mesh.getScene());
  86429. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  86430. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  86431. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  86432. }
  86433. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  86434. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  86435. }
  86436. return result;
  86437. };
  86438. return MorphTarget;
  86439. }());
  86440. BABYLON.MorphTarget = MorphTarget;
  86441. })(BABYLON || (BABYLON = {}));
  86442. //# sourceMappingURL=babylon.morphTarget.js.map
  86443. var BABYLON;
  86444. (function (BABYLON) {
  86445. /**
  86446. * This class is used to deform meshes using morphing between different targets
  86447. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  86448. */
  86449. var MorphTargetManager = /** @class */ (function () {
  86450. /**
  86451. * Creates a new MorphTargetManager
  86452. * @param scene defines the current scene
  86453. */
  86454. function MorphTargetManager(scene) {
  86455. if (scene === void 0) { scene = null; }
  86456. this._targets = new Array();
  86457. this._targetObservable = new Array();
  86458. this._activeTargets = new BABYLON.SmartArray(16);
  86459. this._supportsNormals = false;
  86460. this._supportsTangents = false;
  86461. this._vertexCount = 0;
  86462. this._uniqueId = 0;
  86463. this._tempInfluences = new Array();
  86464. if (!scene) {
  86465. scene = BABYLON.Engine.LastCreatedScene;
  86466. }
  86467. this._scene = scene;
  86468. if (this._scene) {
  86469. this._scene.morphTargetManagers.push(this);
  86470. this._uniqueId = this._scene.getUniqueId();
  86471. }
  86472. }
  86473. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  86474. /**
  86475. * Gets the unique ID of this manager
  86476. */
  86477. get: function () {
  86478. return this._uniqueId;
  86479. },
  86480. enumerable: true,
  86481. configurable: true
  86482. });
  86483. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  86484. /**
  86485. * Gets the number of vertices handled by this manager
  86486. */
  86487. get: function () {
  86488. return this._vertexCount;
  86489. },
  86490. enumerable: true,
  86491. configurable: true
  86492. });
  86493. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  86494. /**
  86495. * Gets a boolean indicating if this manager supports morphing of normals
  86496. */
  86497. get: function () {
  86498. return this._supportsNormals;
  86499. },
  86500. enumerable: true,
  86501. configurable: true
  86502. });
  86503. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  86504. /**
  86505. * Gets a boolean indicating if this manager supports morphing of tangents
  86506. */
  86507. get: function () {
  86508. return this._supportsTangents;
  86509. },
  86510. enumerable: true,
  86511. configurable: true
  86512. });
  86513. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  86514. /**
  86515. * Gets the number of targets stored in this manager
  86516. */
  86517. get: function () {
  86518. return this._targets.length;
  86519. },
  86520. enumerable: true,
  86521. configurable: true
  86522. });
  86523. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  86524. /**
  86525. * Gets the number of influencers (ie. the number of targets with influences > 0)
  86526. */
  86527. get: function () {
  86528. return this._activeTargets.length;
  86529. },
  86530. enumerable: true,
  86531. configurable: true
  86532. });
  86533. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  86534. /**
  86535. * Gets the list of influences (one per target)
  86536. */
  86537. get: function () {
  86538. return this._influences;
  86539. },
  86540. enumerable: true,
  86541. configurable: true
  86542. });
  86543. /**
  86544. * Gets the active target at specified index. An active target is a target with an influence > 0
  86545. * @param index defines the index to check
  86546. * @returns the requested target
  86547. */
  86548. MorphTargetManager.prototype.getActiveTarget = function (index) {
  86549. return this._activeTargets.data[index];
  86550. };
  86551. /**
  86552. * Gets the target at specified index
  86553. * @param index defines the index to check
  86554. * @returns the requested target
  86555. */
  86556. MorphTargetManager.prototype.getTarget = function (index) {
  86557. return this._targets[index];
  86558. };
  86559. /**
  86560. * Add a new target to this manager
  86561. * @param target defines the target to add
  86562. */
  86563. MorphTargetManager.prototype.addTarget = function (target) {
  86564. var _this = this;
  86565. this._targets.push(target);
  86566. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  86567. _this._syncActiveTargets(needUpdate);
  86568. }));
  86569. this._syncActiveTargets(true);
  86570. };
  86571. /**
  86572. * Removes a target from the manager
  86573. * @param target defines the target to remove
  86574. */
  86575. MorphTargetManager.prototype.removeTarget = function (target) {
  86576. var index = this._targets.indexOf(target);
  86577. if (index >= 0) {
  86578. this._targets.splice(index, 1);
  86579. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  86580. this._syncActiveTargets(true);
  86581. }
  86582. };
  86583. /**
  86584. * Serializes the current manager into a Serialization object
  86585. * @returns the serialized object
  86586. */
  86587. MorphTargetManager.prototype.serialize = function () {
  86588. var serializationObject = {};
  86589. serializationObject.id = this.uniqueId;
  86590. serializationObject.targets = [];
  86591. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  86592. var target = _a[_i];
  86593. serializationObject.targets.push(target.serialize());
  86594. }
  86595. return serializationObject;
  86596. };
  86597. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  86598. var influenceCount = 0;
  86599. this._activeTargets.reset();
  86600. this._supportsNormals = true;
  86601. this._supportsTangents = true;
  86602. this._vertexCount = 0;
  86603. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  86604. var target = _a[_i];
  86605. this._activeTargets.push(target);
  86606. this._tempInfluences[influenceCount++] = target.influence;
  86607. var positions = target.getPositions();
  86608. if (positions) {
  86609. this._supportsNormals = this._supportsNormals && target.hasNormals;
  86610. this._supportsTangents = this._supportsTangents && target.hasTangents;
  86611. var vertexCount = positions.length / 3;
  86612. if (this._vertexCount === 0) {
  86613. this._vertexCount = vertexCount;
  86614. }
  86615. else if (this._vertexCount !== vertexCount) {
  86616. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  86617. return;
  86618. }
  86619. }
  86620. }
  86621. if (!this._influences || this._influences.length !== influenceCount) {
  86622. this._influences = new Float32Array(influenceCount);
  86623. }
  86624. for (var index = 0; index < influenceCount; index++) {
  86625. this._influences[index] = this._tempInfluences[index];
  86626. }
  86627. if (needUpdate) {
  86628. this.synchronize();
  86629. }
  86630. };
  86631. /**
  86632. * Syncrhonize the targets with all the meshes using this morph target manager
  86633. */
  86634. MorphTargetManager.prototype.synchronize = function () {
  86635. if (!this._scene) {
  86636. return;
  86637. }
  86638. // Flag meshes as dirty to resync with the active targets
  86639. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  86640. var mesh = _a[_i];
  86641. if (mesh.morphTargetManager === this) {
  86642. mesh._syncGeometryWithMorphTargetManager();
  86643. }
  86644. }
  86645. };
  86646. // Statics
  86647. /**
  86648. * Creates a new MorphTargetManager from serialized data
  86649. * @param serializationObject defines the serialized data
  86650. * @param scene defines the hosting scene
  86651. * @returns the new MorphTargetManager
  86652. */
  86653. MorphTargetManager.Parse = function (serializationObject, scene) {
  86654. var result = new MorphTargetManager(scene);
  86655. result._uniqueId = serializationObject.id;
  86656. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  86657. var targetData = _a[_i];
  86658. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  86659. }
  86660. return result;
  86661. };
  86662. return MorphTargetManager;
  86663. }());
  86664. BABYLON.MorphTargetManager = MorphTargetManager;
  86665. })(BABYLON || (BABYLON = {}));
  86666. //# sourceMappingURL=babylon.morphTargetManager.js.map
  86667. var BABYLON;
  86668. (function (BABYLON) {
  86669. var Octree = /** @class */ (function () {
  86670. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  86671. if (maxDepth === void 0) { maxDepth = 2; }
  86672. this.maxDepth = maxDepth;
  86673. this.dynamicContent = new Array();
  86674. this._maxBlockCapacity = maxBlockCapacity || 64;
  86675. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  86676. this._creationFunc = creationFunc;
  86677. }
  86678. // Methods
  86679. Octree.prototype.update = function (worldMin, worldMax, entries) {
  86680. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  86681. };
  86682. Octree.prototype.addMesh = function (entry) {
  86683. for (var index = 0; index < this.blocks.length; index++) {
  86684. var block = this.blocks[index];
  86685. block.addEntry(entry);
  86686. }
  86687. };
  86688. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  86689. this._selectionContent.reset();
  86690. for (var index = 0; index < this.blocks.length; index++) {
  86691. var block = this.blocks[index];
  86692. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  86693. }
  86694. if (allowDuplicate) {
  86695. this._selectionContent.concat(this.dynamicContent);
  86696. }
  86697. else {
  86698. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86699. }
  86700. return this._selectionContent;
  86701. };
  86702. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  86703. this._selectionContent.reset();
  86704. for (var index = 0; index < this.blocks.length; index++) {
  86705. var block = this.blocks[index];
  86706. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  86707. }
  86708. if (allowDuplicate) {
  86709. this._selectionContent.concat(this.dynamicContent);
  86710. }
  86711. else {
  86712. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86713. }
  86714. return this._selectionContent;
  86715. };
  86716. Octree.prototype.intersectsRay = function (ray) {
  86717. this._selectionContent.reset();
  86718. for (var index = 0; index < this.blocks.length; index++) {
  86719. var block = this.blocks[index];
  86720. block.intersectsRay(ray, this._selectionContent);
  86721. }
  86722. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86723. return this._selectionContent;
  86724. };
  86725. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  86726. target.blocks = new Array();
  86727. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  86728. // Segmenting space
  86729. for (var x = 0; x < 2; x++) {
  86730. for (var y = 0; y < 2; y++) {
  86731. for (var z = 0; z < 2; z++) {
  86732. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  86733. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  86734. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  86735. block.addEntries(entries);
  86736. target.blocks.push(block);
  86737. }
  86738. }
  86739. }
  86740. };
  86741. Octree.CreationFuncForMeshes = function (entry, block) {
  86742. var boundingInfo = entry.getBoundingInfo();
  86743. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86744. block.entries.push(entry);
  86745. }
  86746. };
  86747. Octree.CreationFuncForSubMeshes = function (entry, block) {
  86748. var boundingInfo = entry.getBoundingInfo();
  86749. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86750. block.entries.push(entry);
  86751. }
  86752. };
  86753. return Octree;
  86754. }());
  86755. BABYLON.Octree = Octree;
  86756. })(BABYLON || (BABYLON = {}));
  86757. //# sourceMappingURL=babylon.octree.js.map
  86758. var BABYLON;
  86759. (function (BABYLON) {
  86760. var OctreeBlock = /** @class */ (function () {
  86761. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  86762. this.entries = new Array();
  86763. this._boundingVectors = new Array();
  86764. this._capacity = capacity;
  86765. this._depth = depth;
  86766. this._maxDepth = maxDepth;
  86767. this._creationFunc = creationFunc;
  86768. this._minPoint = minPoint;
  86769. this._maxPoint = maxPoint;
  86770. this._boundingVectors.push(minPoint.clone());
  86771. this._boundingVectors.push(maxPoint.clone());
  86772. this._boundingVectors.push(minPoint.clone());
  86773. this._boundingVectors[2].x = maxPoint.x;
  86774. this._boundingVectors.push(minPoint.clone());
  86775. this._boundingVectors[3].y = maxPoint.y;
  86776. this._boundingVectors.push(minPoint.clone());
  86777. this._boundingVectors[4].z = maxPoint.z;
  86778. this._boundingVectors.push(maxPoint.clone());
  86779. this._boundingVectors[5].z = minPoint.z;
  86780. this._boundingVectors.push(maxPoint.clone());
  86781. this._boundingVectors[6].x = minPoint.x;
  86782. this._boundingVectors.push(maxPoint.clone());
  86783. this._boundingVectors[7].y = minPoint.y;
  86784. }
  86785. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  86786. // Property
  86787. get: function () {
  86788. return this._capacity;
  86789. },
  86790. enumerable: true,
  86791. configurable: true
  86792. });
  86793. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  86794. get: function () {
  86795. return this._minPoint;
  86796. },
  86797. enumerable: true,
  86798. configurable: true
  86799. });
  86800. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  86801. get: function () {
  86802. return this._maxPoint;
  86803. },
  86804. enumerable: true,
  86805. configurable: true
  86806. });
  86807. // Methods
  86808. OctreeBlock.prototype.addEntry = function (entry) {
  86809. if (this.blocks) {
  86810. for (var index = 0; index < this.blocks.length; index++) {
  86811. var block = this.blocks[index];
  86812. block.addEntry(entry);
  86813. }
  86814. return;
  86815. }
  86816. this._creationFunc(entry, this);
  86817. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  86818. this.createInnerBlocks();
  86819. }
  86820. };
  86821. OctreeBlock.prototype.addEntries = function (entries) {
  86822. for (var index = 0; index < entries.length; index++) {
  86823. var mesh = entries[index];
  86824. this.addEntry(mesh);
  86825. }
  86826. };
  86827. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  86828. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  86829. if (this.blocks) {
  86830. for (var index = 0; index < this.blocks.length; index++) {
  86831. var block = this.blocks[index];
  86832. block.select(frustumPlanes, selection, allowDuplicate);
  86833. }
  86834. return;
  86835. }
  86836. if (allowDuplicate) {
  86837. selection.concat(this.entries);
  86838. }
  86839. else {
  86840. selection.concatWithNoDuplicate(this.entries);
  86841. }
  86842. }
  86843. };
  86844. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  86845. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  86846. if (this.blocks) {
  86847. for (var index = 0; index < this.blocks.length; index++) {
  86848. var block = this.blocks[index];
  86849. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  86850. }
  86851. return;
  86852. }
  86853. if (allowDuplicate) {
  86854. selection.concat(this.entries);
  86855. }
  86856. else {
  86857. selection.concatWithNoDuplicate(this.entries);
  86858. }
  86859. }
  86860. };
  86861. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  86862. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  86863. if (this.blocks) {
  86864. for (var index = 0; index < this.blocks.length; index++) {
  86865. var block = this.blocks[index];
  86866. block.intersectsRay(ray, selection);
  86867. }
  86868. return;
  86869. }
  86870. selection.concatWithNoDuplicate(this.entries);
  86871. }
  86872. };
  86873. OctreeBlock.prototype.createInnerBlocks = function () {
  86874. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  86875. };
  86876. return OctreeBlock;
  86877. }());
  86878. BABYLON.OctreeBlock = OctreeBlock;
  86879. })(BABYLON || (BABYLON = {}));
  86880. //# sourceMappingURL=babylon.octreeBlock.js.map
  86881. var BABYLON;
  86882. (function (BABYLON) {
  86883. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  86884. __extends(VRDistortionCorrectionPostProcess, _super);
  86885. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  86886. var _this = _super.call(this, name, "vrDistortionCorrection", [
  86887. 'LensCenter',
  86888. 'Scale',
  86889. 'ScaleIn',
  86890. 'HmdWarpParam'
  86891. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  86892. _this._isRightEye = isRightEye;
  86893. _this._distortionFactors = vrMetrics.distortionK;
  86894. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  86895. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  86896. _this.adaptScaleToCurrentViewport = true;
  86897. _this.onSizeChangedObservable.add(function () {
  86898. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  86899. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  86900. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  86901. });
  86902. _this.onApplyObservable.add(function (effect) {
  86903. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  86904. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  86905. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  86906. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  86907. });
  86908. return _this;
  86909. }
  86910. return VRDistortionCorrectionPostProcess;
  86911. }(BABYLON.PostProcess));
  86912. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  86913. })(BABYLON || (BABYLON = {}));
  86914. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  86915. var BABYLON;
  86916. (function (BABYLON) {
  86917. /**
  86918. * Postprocess used to generate anaglyphic rendering
  86919. */
  86920. var AnaglyphPostProcess = /** @class */ (function (_super) {
  86921. __extends(AnaglyphPostProcess, _super);
  86922. /**
  86923. * Creates a new AnaglyphPostProcess
  86924. * @param name defines postprocess name
  86925. * @param options defines creation options or target ratio scale
  86926. * @param rigCameras defines cameras using this postprocess
  86927. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  86928. * @param engine defines hosting engine
  86929. * @param reusable defines if the postprocess will be reused multiple times per frame
  86930. */
  86931. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  86932. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  86933. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86934. _this.onApplyObservable.add(function (effect) {
  86935. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  86936. });
  86937. return _this;
  86938. }
  86939. return AnaglyphPostProcess;
  86940. }(BABYLON.PostProcess));
  86941. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  86942. })(BABYLON || (BABYLON = {}));
  86943. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  86944. var BABYLON;
  86945. (function (BABYLON) {
  86946. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  86947. __extends(StereoscopicInterlacePostProcess, _super);
  86948. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  86949. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  86950. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86951. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86952. _this.onSizeChangedObservable.add(function () {
  86953. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86954. });
  86955. _this.onApplyObservable.add(function (effect) {
  86956. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  86957. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  86958. });
  86959. return _this;
  86960. }
  86961. return StereoscopicInterlacePostProcess;
  86962. }(BABYLON.PostProcess));
  86963. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  86964. })(BABYLON || (BABYLON = {}));
  86965. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  86966. var BABYLON;
  86967. (function (BABYLON) {
  86968. /**
  86969. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  86970. * Screen rotation is taken into account.
  86971. */
  86972. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  86973. function FreeCameraDeviceOrientationInput() {
  86974. var _this = this;
  86975. this._screenOrientationAngle = 0;
  86976. this._screenQuaternion = new BABYLON.Quaternion();
  86977. this._alpha = 0;
  86978. this._beta = 0;
  86979. this._gamma = 0;
  86980. this._orientationChanged = function () {
  86981. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  86982. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  86983. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  86984. };
  86985. this._deviceOrientation = function (evt) {
  86986. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  86987. _this._beta = evt.beta !== null ? evt.beta : 0;
  86988. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  86989. };
  86990. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  86991. this._orientationChanged();
  86992. }
  86993. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  86994. get: function () {
  86995. return this._camera;
  86996. },
  86997. set: function (camera) {
  86998. this._camera = camera;
  86999. if (this._camera != null && !this._camera.rotationQuaternion) {
  87000. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  87001. }
  87002. },
  87003. enumerable: true,
  87004. configurable: true
  87005. });
  87006. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  87007. window.addEventListener("orientationchange", this._orientationChanged);
  87008. window.addEventListener("deviceorientation", this._deviceOrientation);
  87009. //In certain cases, the attach control is called AFTER orientation was changed,
  87010. //So this is needed.
  87011. this._orientationChanged();
  87012. };
  87013. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  87014. window.removeEventListener("orientationchange", this._orientationChanged);
  87015. window.removeEventListener("deviceorientation", this._deviceOrientation);
  87016. };
  87017. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  87018. //if no device orientation provided, don't update the rotation.
  87019. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  87020. if (!this._alpha)
  87021. return;
  87022. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  87023. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  87024. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  87025. //Mirror on XY Plane
  87026. this._camera.rotationQuaternion.z *= -1;
  87027. this._camera.rotationQuaternion.w *= -1;
  87028. };
  87029. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  87030. return "FreeCameraDeviceOrientationInput";
  87031. };
  87032. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  87033. return "deviceOrientation";
  87034. };
  87035. return FreeCameraDeviceOrientationInput;
  87036. }());
  87037. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  87038. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  87039. })(BABYLON || (BABYLON = {}));
  87040. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  87041. var BABYLON;
  87042. (function (BABYLON) {
  87043. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  87044. function ArcRotateCameraVRDeviceOrientationInput() {
  87045. this.alphaCorrection = 1;
  87046. this.betaCorrection = 1;
  87047. this.gammaCorrection = 1;
  87048. this._alpha = 0;
  87049. this._gamma = 0;
  87050. this._dirty = false;
  87051. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  87052. }
  87053. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  87054. this.camera.attachControl(element, noPreventDefault);
  87055. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  87056. };
  87057. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  87058. if (evt.alpha !== null) {
  87059. this._alpha = +evt.alpha | 0;
  87060. }
  87061. if (evt.gamma !== null) {
  87062. this._gamma = +evt.gamma | 0;
  87063. }
  87064. this._dirty = true;
  87065. };
  87066. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  87067. if (this._dirty) {
  87068. this._dirty = false;
  87069. if (this._gamma < 0) {
  87070. this._gamma = 180 + this._gamma;
  87071. }
  87072. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  87073. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  87074. }
  87075. };
  87076. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  87077. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  87078. };
  87079. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  87080. return "ArcRotateCameraVRDeviceOrientationInput";
  87081. };
  87082. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  87083. return "VRDeviceOrientation";
  87084. };
  87085. return ArcRotateCameraVRDeviceOrientationInput;
  87086. }());
  87087. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  87088. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  87089. })(BABYLON || (BABYLON = {}));
  87090. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  87091. var BABYLON;
  87092. (function (BABYLON) {
  87093. var VRCameraMetrics = /** @class */ (function () {
  87094. function VRCameraMetrics() {
  87095. this.compensateDistortion = true;
  87096. }
  87097. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  87098. get: function () {
  87099. return this.hResolution / (2 * this.vResolution);
  87100. },
  87101. enumerable: true,
  87102. configurable: true
  87103. });
  87104. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  87105. get: function () {
  87106. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  87107. },
  87108. enumerable: true,
  87109. configurable: true
  87110. });
  87111. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  87112. get: function () {
  87113. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  87114. var h = (4 * meters) / this.hScreenSize;
  87115. return BABYLON.Matrix.Translation(h, 0, 0);
  87116. },
  87117. enumerable: true,
  87118. configurable: true
  87119. });
  87120. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  87121. get: function () {
  87122. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  87123. var h = (4 * meters) / this.hScreenSize;
  87124. return BABYLON.Matrix.Translation(-h, 0, 0);
  87125. },
  87126. enumerable: true,
  87127. configurable: true
  87128. });
  87129. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  87130. get: function () {
  87131. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  87132. },
  87133. enumerable: true,
  87134. configurable: true
  87135. });
  87136. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  87137. get: function () {
  87138. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  87139. },
  87140. enumerable: true,
  87141. configurable: true
  87142. });
  87143. VRCameraMetrics.GetDefault = function () {
  87144. var result = new VRCameraMetrics();
  87145. result.hResolution = 1280;
  87146. result.vResolution = 800;
  87147. result.hScreenSize = 0.149759993;
  87148. result.vScreenSize = 0.0935999975;
  87149. result.vScreenCenter = 0.0467999987;
  87150. result.eyeToScreenDistance = 0.0410000011;
  87151. result.lensSeparationDistance = 0.0635000020;
  87152. result.interpupillaryDistance = 0.0640000030;
  87153. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  87154. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  87155. result.postProcessScaleFactor = 1.714605507808412;
  87156. result.lensCenterOffset = 0.151976421;
  87157. return result;
  87158. };
  87159. return VRCameraMetrics;
  87160. }());
  87161. BABYLON.VRCameraMetrics = VRCameraMetrics;
  87162. })(BABYLON || (BABYLON = {}));
  87163. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  87164. var BABYLON;
  87165. (function (BABYLON) {
  87166. /**
  87167. * This represents a WebVR camera.
  87168. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  87169. * @example http://doc.babylonjs.com/how_to/webvr_camera
  87170. */
  87171. var WebVRFreeCamera = /** @class */ (function (_super) {
  87172. __extends(WebVRFreeCamera, _super);
  87173. /**
  87174. * Instantiates a WebVRFreeCamera.
  87175. * @param name The name of the WebVRFreeCamera
  87176. * @param position The starting anchor position for the camera
  87177. * @param scene The scene the camera belongs to
  87178. * @param webVROptions a set of customizable options for the webVRCamera
  87179. */
  87180. function WebVRFreeCamera(name, position, scene, webVROptions) {
  87181. if (webVROptions === void 0) { webVROptions = {}; }
  87182. var _this = _super.call(this, name, position, scene) || this;
  87183. _this.webVROptions = webVROptions;
  87184. /**
  87185. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  87186. */
  87187. _this._vrDevice = null;
  87188. /**
  87189. * The rawPose of the vrDevice.
  87190. */
  87191. _this.rawPose = null;
  87192. _this._specsVersion = "1.1";
  87193. _this._attached = false;
  87194. _this._descendants = [];
  87195. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  87196. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  87197. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  87198. _this._standingMatrix = null;
  87199. /**
  87200. * Represents device position in babylon space.
  87201. */
  87202. _this.devicePosition = BABYLON.Vector3.Zero();
  87203. /**
  87204. * Represents device rotation in babylon space.
  87205. */
  87206. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  87207. /**
  87208. * The scale of the device to be used when translating from device space to babylon space.
  87209. */
  87210. _this.deviceScaleFactor = 1;
  87211. _this._deviceToWorld = BABYLON.Matrix.Identity();
  87212. _this._worldToDevice = BABYLON.Matrix.Identity();
  87213. /**
  87214. * References to the webVR controllers for the vrDevice.
  87215. */
  87216. _this.controllers = [];
  87217. /**
  87218. * Emits an event when a controller is attached.
  87219. */
  87220. _this.onControllersAttachedObservable = new BABYLON.Observable();
  87221. /**
  87222. * Emits an event when a controller's mesh has been loaded;
  87223. */
  87224. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  87225. /**
  87226. * If the rig cameras be used as parent instead of this camera.
  87227. */
  87228. _this.rigParenting = true;
  87229. _this._defaultHeight = undefined;
  87230. _this._workingVector = BABYLON.Vector3.Zero();
  87231. _this._oneVector = BABYLON.Vector3.One();
  87232. _this._workingMatrix = BABYLON.Matrix.Identity();
  87233. _this._cache.position = BABYLON.Vector3.Zero();
  87234. if (webVROptions.defaultHeight) {
  87235. _this._defaultHeight = webVROptions.defaultHeight;
  87236. _this.position.y = _this._defaultHeight;
  87237. }
  87238. _this.minZ = 0.1;
  87239. //legacy support - the compensation boolean was removed.
  87240. if (arguments.length === 5) {
  87241. _this.webVROptions = arguments[4];
  87242. }
  87243. // default webVR options
  87244. if (_this.webVROptions.trackPosition == undefined) {
  87245. _this.webVROptions.trackPosition = true;
  87246. }
  87247. if (_this.webVROptions.controllerMeshes == undefined) {
  87248. _this.webVROptions.controllerMeshes = true;
  87249. }
  87250. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  87251. _this.webVROptions.defaultLightingOnControllers = true;
  87252. }
  87253. _this.rotationQuaternion = new BABYLON.Quaternion();
  87254. if (_this.webVROptions && _this.webVROptions.positionScale) {
  87255. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  87256. }
  87257. //enable VR
  87258. var engine = _this.getEngine();
  87259. _this._onVREnabled = function (success) { if (success) {
  87260. _this.initControllers();
  87261. } };
  87262. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  87263. engine.initWebVR().add(function (event) {
  87264. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  87265. return;
  87266. }
  87267. _this._vrDevice = event.vrDisplay;
  87268. //reset the rig parameters.
  87269. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  87270. if (_this._attached) {
  87271. _this.getEngine().enableVR();
  87272. }
  87273. });
  87274. if (typeof (VRFrameData) !== "undefined")
  87275. _this._frameData = new VRFrameData();
  87276. /**
  87277. * The idea behind the following lines:
  87278. * objects that have the camera as parent should actually have the rig cameras as a parent.
  87279. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  87280. * the second will not show it correctly.
  87281. *
  87282. * To solve this - each object that has the camera as parent will be added to a protected array.
  87283. * When the rig camera renders, it will take this array and set all of those to be its children.
  87284. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  87285. * Amazing!
  87286. */
  87287. scene.onBeforeCameraRenderObservable.add(function (camera) {
  87288. if (camera.parent === _this && _this.rigParenting) {
  87289. _this._descendants = _this.getDescendants(true, function (n) {
  87290. // don't take the cameras or the controllers!
  87291. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  87292. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  87293. return !isController && !isRigCamera;
  87294. });
  87295. _this._descendants.forEach(function (node) {
  87296. node.parent = camera;
  87297. });
  87298. }
  87299. });
  87300. scene.onAfterCameraRenderObservable.add(function (camera) {
  87301. if (camera.parent === _this && _this.rigParenting) {
  87302. _this._descendants.forEach(function (node) {
  87303. node.parent = _this;
  87304. });
  87305. }
  87306. });
  87307. return _this;
  87308. }
  87309. /**
  87310. * Gets the device distance from the ground in meters.
  87311. * @returns the distance in meters from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  87312. */
  87313. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  87314. if (this._standingMatrix) {
  87315. // Add standing matrix offset to get real offset from ground in room
  87316. this._standingMatrix.getTranslationToRef(this._workingVector);
  87317. return this._deviceRoomPosition.y + this._workingVector.y;
  87318. }
  87319. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  87320. return this._defaultHeight || 0;
  87321. };
  87322. /**
  87323. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  87324. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  87325. */
  87326. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  87327. var _this = this;
  87328. if (callback === void 0) { callback = function (bool) { }; }
  87329. // Use standing matrix if available
  87330. this.getEngine().initWebVRAsync().then(function (result) {
  87331. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  87332. callback(false);
  87333. }
  87334. else {
  87335. _this._standingMatrix = new BABYLON.Matrix();
  87336. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  87337. if (!_this.getScene().useRightHandedSystem) {
  87338. [2, 6, 8, 9, 14].forEach(function (num) {
  87339. if (_this._standingMatrix) {
  87340. _this._standingMatrix.m[num] *= -1;
  87341. }
  87342. });
  87343. }
  87344. callback(true);
  87345. }
  87346. });
  87347. };
  87348. /**
  87349. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  87350. * @returns A promise with a boolean set to if the standing matrix is supported.
  87351. */
  87352. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  87353. var _this = this;
  87354. return new Promise(function (res, rej) {
  87355. _this.useStandingMatrix(function (supported) {
  87356. res(supported);
  87357. });
  87358. });
  87359. };
  87360. /**
  87361. * Disposes the camera
  87362. */
  87363. WebVRFreeCamera.prototype.dispose = function () {
  87364. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  87365. _super.prototype.dispose.call(this);
  87366. };
  87367. /**
  87368. * Gets a vrController by name.
  87369. * @param name The name of the controller to retreive
  87370. * @returns the controller matching the name specified or null if not found
  87371. */
  87372. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  87373. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  87374. var gp = _a[_i];
  87375. if (gp.hand === name) {
  87376. return gp;
  87377. }
  87378. }
  87379. return null;
  87380. };
  87381. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  87382. /**
  87383. * The controller corrisponding to the users left hand.
  87384. */
  87385. get: function () {
  87386. if (!this._leftController) {
  87387. this._leftController = this.getControllerByName("left");
  87388. }
  87389. return this._leftController;
  87390. },
  87391. enumerable: true,
  87392. configurable: true
  87393. });
  87394. ;
  87395. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  87396. /**
  87397. * The controller corrisponding to the users right hand.
  87398. */
  87399. get: function () {
  87400. if (!this._rightController) {
  87401. this._rightController = this.getControllerByName("right");
  87402. }
  87403. return this._rightController;
  87404. },
  87405. enumerable: true,
  87406. configurable: true
  87407. });
  87408. ;
  87409. /**
  87410. * Casts a ray forward from the vrCamera's gaze.
  87411. * @param length Length of the ray (default: 100)
  87412. * @returns the ray corrisponding to the gaze
  87413. */
  87414. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  87415. if (length === void 0) { length = 100; }
  87416. if (this.leftCamera) {
  87417. // Use left eye to avoid computation to compute center on every call
  87418. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  87419. }
  87420. else {
  87421. return _super.prototype.getForwardRay.call(this, length);
  87422. }
  87423. };
  87424. /**
  87425. * Updates the camera based on device's frame data
  87426. */
  87427. WebVRFreeCamera.prototype._checkInputs = function () {
  87428. if (this._vrDevice && this._vrDevice.isPresenting) {
  87429. this._vrDevice.getFrameData(this._frameData);
  87430. this.updateFromDevice(this._frameData.pose);
  87431. }
  87432. _super.prototype._checkInputs.call(this);
  87433. };
  87434. /**
  87435. * Updates the poseControlled values based on the input device pose.
  87436. * @param poseData Pose coming from the device
  87437. */
  87438. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  87439. if (poseData && poseData.orientation) {
  87440. this.rawPose = poseData;
  87441. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  87442. if (this.getScene().useRightHandedSystem) {
  87443. this._deviceRoomRotationQuaternion.z *= -1;
  87444. this._deviceRoomRotationQuaternion.w *= -1;
  87445. }
  87446. if (this.webVROptions.trackPosition && this.rawPose.position) {
  87447. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  87448. if (this.getScene().useRightHandedSystem) {
  87449. this._deviceRoomPosition.z *= -1;
  87450. }
  87451. }
  87452. }
  87453. };
  87454. /**
  87455. * WebVR's attach control will start broadcasting frames to the device.
  87456. * Note that in certain browsers (chrome for example) this function must be called
  87457. * within a user-interaction callback. Example:
  87458. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  87459. *
  87460. * @param element html element to attach the vrDevice to
  87461. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  87462. */
  87463. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  87464. _super.prototype.attachControl.call(this, element, noPreventDefault);
  87465. this._attached = true;
  87466. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  87467. if (this._vrDevice) {
  87468. this.getEngine().enableVR();
  87469. }
  87470. };
  87471. /**
  87472. * Detaches the camera from the html element and disables VR
  87473. *
  87474. * @param element html element to detach from
  87475. */
  87476. WebVRFreeCamera.prototype.detachControl = function (element) {
  87477. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  87478. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  87479. _super.prototype.detachControl.call(this, element);
  87480. this._attached = false;
  87481. this.getEngine().disableVR();
  87482. };
  87483. /**
  87484. * @returns the name of this class
  87485. */
  87486. WebVRFreeCamera.prototype.getClassName = function () {
  87487. return "WebVRFreeCamera";
  87488. };
  87489. /**
  87490. * Calls resetPose on the vrDisplay
  87491. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  87492. */
  87493. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  87494. //uses the vrDisplay's "resetPose()".
  87495. //pitch and roll won't be affected.
  87496. this._vrDevice.resetPose();
  87497. };
  87498. /**
  87499. * Updates the rig cameras (left and right eye)
  87500. */
  87501. WebVRFreeCamera.prototype._updateRigCameras = function () {
  87502. var camLeft = this._rigCameras[0];
  87503. var camRight = this._rigCameras[1];
  87504. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  87505. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  87506. camLeft.position.copyFrom(this._deviceRoomPosition);
  87507. camRight.position.copyFrom(this._deviceRoomPosition);
  87508. };
  87509. /**
  87510. * Updates the cached values of the camera
  87511. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  87512. */
  87513. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  87514. var _this = this;
  87515. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  87516. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  87517. if (!this.updateCacheCalled) {
  87518. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  87519. this.updateCacheCalled = true;
  87520. this.update();
  87521. }
  87522. // Set working vector to the device position in room space rotated by the new rotation
  87523. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  87524. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  87525. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  87526. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  87527. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  87528. // Add translation from anchor position
  87529. this._deviceToWorld.getTranslationToRef(this._workingVector);
  87530. this._workingVector.addInPlace(this.position);
  87531. this._workingVector.subtractInPlace(this._cache.position);
  87532. this._deviceToWorld.setTranslation(this._workingVector);
  87533. // Set an inverted matrix to be used when updating the camera
  87534. this._deviceToWorld.invertToRef(this._worldToDevice);
  87535. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  87536. this.controllers.forEach(function (controller) {
  87537. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  87538. controller.update();
  87539. });
  87540. }
  87541. if (!ignoreParentClass) {
  87542. _super.prototype._updateCache.call(this);
  87543. }
  87544. this.updateCacheCalled = false;
  87545. };
  87546. /**
  87547. * Updates the current device position and rotation in the babylon world
  87548. */
  87549. WebVRFreeCamera.prototype.update = function () {
  87550. // Get current device position in babylon world
  87551. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  87552. // Get current device rotation in babylon world
  87553. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  87554. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  87555. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  87556. _super.prototype.update.call(this);
  87557. };
  87558. /**
  87559. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  87560. * @returns an identity matrix
  87561. */
  87562. WebVRFreeCamera.prototype._getViewMatrix = function () {
  87563. return BABYLON.Matrix.Identity();
  87564. };
  87565. /**
  87566. * This function is called by the two RIG cameras.
  87567. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  87568. */
  87569. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  87570. var _this = this;
  87571. // Update the parent camera prior to using a child camera to avoid desynchronization
  87572. var parentCamera = this._cameraRigParams["parentCamera"];
  87573. parentCamera._updateCache();
  87574. //WebVR 1.1
  87575. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  87576. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  87577. if (!this.getScene().useRightHandedSystem) {
  87578. [2, 6, 8, 9, 14].forEach(function (num) {
  87579. _this._webvrViewMatrix.m[num] *= -1;
  87580. });
  87581. }
  87582. // update the camera rotation matrix
  87583. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  87584. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  87585. // Computing target and final matrix
  87586. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  87587. // should the view matrix be updated with scale and position offset?
  87588. if (parentCamera.deviceScaleFactor !== 1) {
  87589. this._webvrViewMatrix.invert();
  87590. // scale the position, if set
  87591. if (parentCamera.deviceScaleFactor) {
  87592. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  87593. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  87594. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  87595. }
  87596. this._webvrViewMatrix.invert();
  87597. }
  87598. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  87599. // Compute global position
  87600. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  87601. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  87602. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  87603. this._workingMatrix.getTranslationToRef(this._globalPosition);
  87604. this._markSyncedWithParent();
  87605. return this._webvrViewMatrix;
  87606. };
  87607. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  87608. var _this = this;
  87609. var parentCamera = this.parent;
  87610. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  87611. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  87612. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  87613. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  87614. //babylon compatible matrix
  87615. if (!this.getScene().useRightHandedSystem) {
  87616. [8, 9, 10, 11].forEach(function (num) {
  87617. _this._projectionMatrix.m[num] *= -1;
  87618. });
  87619. }
  87620. return this._projectionMatrix;
  87621. };
  87622. /**
  87623. * Initializes the controllers and their meshes
  87624. */
  87625. WebVRFreeCamera.prototype.initControllers = function () {
  87626. var _this = this;
  87627. this.controllers = [];
  87628. var manager = this.getScene().gamepadManager;
  87629. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  87630. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  87631. var webVrController = gamepad;
  87632. if (webVrController.defaultModel) {
  87633. webVrController.defaultModel.setEnabled(false);
  87634. }
  87635. if (webVrController.hand === "right") {
  87636. _this._rightController = null;
  87637. }
  87638. if (webVrController.hand === "left") {
  87639. _this._leftController = null;
  87640. }
  87641. var controllerIndex = _this.controllers.indexOf(webVrController);
  87642. if (controllerIndex !== -1) {
  87643. _this.controllers.splice(controllerIndex, 1);
  87644. }
  87645. }
  87646. });
  87647. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  87648. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  87649. var webVrController_1 = gamepad;
  87650. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  87651. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  87652. if (_this.webVROptions.controllerMeshes) {
  87653. if (webVrController_1.defaultModel) {
  87654. webVrController_1.defaultModel.setEnabled(true);
  87655. }
  87656. else {
  87657. // Load the meshes
  87658. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  87659. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  87660. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  87661. if (_this.webVROptions.defaultLightingOnControllers) {
  87662. if (!_this._lightOnControllers) {
  87663. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  87664. }
  87665. var activateLightOnSubMeshes_1 = function (mesh, light) {
  87666. var children = mesh.getChildren();
  87667. if (children.length !== 0) {
  87668. children.forEach(function (mesh) {
  87669. light.includedOnlyMeshes.push(mesh);
  87670. activateLightOnSubMeshes_1(mesh, light);
  87671. });
  87672. }
  87673. };
  87674. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  87675. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  87676. }
  87677. });
  87678. }
  87679. }
  87680. webVrController_1.attachToPoseControlledCamera(_this);
  87681. // since this is async - sanity check. Is the controller already stored?
  87682. if (_this.controllers.indexOf(webVrController_1) === -1) {
  87683. //add to the controllers array
  87684. _this.controllers.push(webVrController_1);
  87685. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  87686. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  87687. // So we're overriding setting left & right manually to be sure
  87688. var firstViveWandDetected = false;
  87689. for (var i = 0; i < _this.controllers.length; i++) {
  87690. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  87691. if (!firstViveWandDetected) {
  87692. firstViveWandDetected = true;
  87693. _this.controllers[i].hand = "left";
  87694. }
  87695. else {
  87696. _this.controllers[i].hand = "right";
  87697. }
  87698. }
  87699. }
  87700. //did we find enough controllers? Great! let the developer know.
  87701. if (_this.controllers.length >= 2) {
  87702. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  87703. }
  87704. }
  87705. }
  87706. });
  87707. };
  87708. return WebVRFreeCamera;
  87709. }(BABYLON.FreeCamera));
  87710. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  87711. })(BABYLON || (BABYLON = {}));
  87712. //# sourceMappingURL=babylon.webVRCamera.js.map
  87713. var BABYLON;
  87714. (function (BABYLON) {
  87715. // We're mainly based on the logic defined into the FreeCamera code
  87716. /**
  87717. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  87718. * being tilted forward or back and left or right.
  87719. */
  87720. var DeviceOrientationCamera = /** @class */ (function (_super) {
  87721. __extends(DeviceOrientationCamera, _super);
  87722. /**
  87723. * Creates a new device orientation camera
  87724. * @param name The name of the camera
  87725. * @param position The start position camera
  87726. * @param scene The scene the camera belongs to
  87727. */
  87728. function DeviceOrientationCamera(name, position, scene) {
  87729. var _this = _super.call(this, name, position, scene) || this;
  87730. _this._quaternionCache = new BABYLON.Quaternion();
  87731. _this.inputs.addDeviceOrientation();
  87732. return _this;
  87733. }
  87734. /**
  87735. * Gets the current instance class name ("DeviceOrientationCamera").
  87736. * This helps avoiding instanceof at run time.
  87737. * @returns the class name
  87738. */
  87739. DeviceOrientationCamera.prototype.getClassName = function () {
  87740. return "DeviceOrientationCamera";
  87741. };
  87742. /**
  87743. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  87744. */
  87745. DeviceOrientationCamera.prototype._checkInputs = function () {
  87746. _super.prototype._checkInputs.call(this);
  87747. this._quaternionCache.copyFrom(this.rotationQuaternion);
  87748. if (this._initialQuaternion) {
  87749. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87750. }
  87751. };
  87752. /**
  87753. * Reset the camera to its default orientation on the specified axis only.
  87754. * @param axis The axis to reset
  87755. */
  87756. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  87757. var _this = this;
  87758. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  87759. //can only work if this camera has a rotation quaternion already.
  87760. if (!this.rotationQuaternion)
  87761. return;
  87762. if (!this._initialQuaternion) {
  87763. this._initialQuaternion = new BABYLON.Quaternion();
  87764. }
  87765. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  87766. ['x', 'y', 'z'].forEach(function (axisName) {
  87767. if (!axis[axisName]) {
  87768. _this._initialQuaternion[axisName] = 0;
  87769. }
  87770. else {
  87771. _this._initialQuaternion[axisName] *= -1;
  87772. }
  87773. });
  87774. this._initialQuaternion.normalize();
  87775. //force rotation update
  87776. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87777. };
  87778. return DeviceOrientationCamera;
  87779. }(BABYLON.FreeCamera));
  87780. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  87781. })(BABYLON || (BABYLON = {}));
  87782. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  87783. var BABYLON;
  87784. (function (BABYLON) {
  87785. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  87786. __extends(VRDeviceOrientationFreeCamera, _super);
  87787. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87788. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87789. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87790. var _this = _super.call(this, name, position, scene) || this;
  87791. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87792. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87793. return _this;
  87794. }
  87795. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  87796. return "VRDeviceOrientationFreeCamera";
  87797. };
  87798. return VRDeviceOrientationFreeCamera;
  87799. }(BABYLON.DeviceOrientationCamera));
  87800. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  87801. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  87802. __extends(VRDeviceOrientationGamepadCamera, _super);
  87803. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87804. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87805. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87806. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  87807. _this.inputs.addGamepad();
  87808. return _this;
  87809. }
  87810. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  87811. return "VRDeviceOrientationGamepadCamera";
  87812. };
  87813. return VRDeviceOrientationGamepadCamera;
  87814. }(VRDeviceOrientationFreeCamera));
  87815. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  87816. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  87817. __extends(VRDeviceOrientationArcRotateCamera, _super);
  87818. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  87819. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87820. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87821. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87822. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87823. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87824. _this.inputs.addVRDeviceOrientation();
  87825. return _this;
  87826. }
  87827. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  87828. return "VRDeviceOrientationArcRotateCamera";
  87829. };
  87830. return VRDeviceOrientationArcRotateCamera;
  87831. }(BABYLON.ArcRotateCamera));
  87832. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  87833. })(BABYLON || (BABYLON = {}));
  87834. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  87835. var BABYLON;
  87836. (function (BABYLON) {
  87837. /**
  87838. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  87839. */
  87840. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  87841. __extends(AnaglyphFreeCamera, _super);
  87842. /**
  87843. * Creates a new AnaglyphFreeCamera
  87844. * @param name defines camera name
  87845. * @param position defines initial position
  87846. * @param interaxialDistance defines distance between each color axis
  87847. * @param scene defines the hosting scene
  87848. */
  87849. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  87850. var _this = _super.call(this, name, position, scene) || this;
  87851. _this.interaxialDistance = interaxialDistance;
  87852. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87853. return _this;
  87854. }
  87855. /**
  87856. * Gets camera class name
  87857. * @returns AnaglyphFreeCamera
  87858. */
  87859. AnaglyphFreeCamera.prototype.getClassName = function () {
  87860. return "AnaglyphFreeCamera";
  87861. };
  87862. return AnaglyphFreeCamera;
  87863. }(BABYLON.FreeCamera));
  87864. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  87865. /**
  87866. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  87867. */
  87868. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  87869. __extends(AnaglyphArcRotateCamera, _super);
  87870. /**
  87871. * Creates a new AnaglyphArcRotateCamera
  87872. * @param name defines camera name
  87873. * @param alpha defines alpha angle (in radians)
  87874. * @param beta defines beta angle (in radians)
  87875. * @param radius defines radius
  87876. * @param target defines camera target
  87877. * @param interaxialDistance defines distance between each color axis
  87878. * @param scene defines the hosting scene
  87879. */
  87880. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  87881. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87882. _this.interaxialDistance = interaxialDistance;
  87883. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87884. return _this;
  87885. }
  87886. /**
  87887. * Gets camera class name
  87888. * @returns AnaglyphArcRotateCamera
  87889. */
  87890. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  87891. return "AnaglyphArcRotateCamera";
  87892. };
  87893. return AnaglyphArcRotateCamera;
  87894. }(BABYLON.ArcRotateCamera));
  87895. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  87896. /**
  87897. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  87898. */
  87899. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  87900. __extends(AnaglyphGamepadCamera, _super);
  87901. /**
  87902. * Creates a new AnaglyphGamepadCamera
  87903. * @param name defines camera name
  87904. * @param position defines initial position
  87905. * @param interaxialDistance defines distance between each color axis
  87906. * @param scene defines the hosting scene
  87907. */
  87908. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  87909. var _this = _super.call(this, name, position, scene) || this;
  87910. _this.interaxialDistance = interaxialDistance;
  87911. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87912. return _this;
  87913. }
  87914. /**
  87915. * Gets camera class name
  87916. * @returns AnaglyphGamepadCamera
  87917. */
  87918. AnaglyphGamepadCamera.prototype.getClassName = function () {
  87919. return "AnaglyphGamepadCamera";
  87920. };
  87921. return AnaglyphGamepadCamera;
  87922. }(BABYLON.GamepadCamera));
  87923. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  87924. /**
  87925. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  87926. */
  87927. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  87928. __extends(AnaglyphUniversalCamera, _super);
  87929. /**
  87930. * Creates a new AnaglyphUniversalCamera
  87931. * @param name defines camera name
  87932. * @param position defines initial position
  87933. * @param interaxialDistance defines distance between each color axis
  87934. * @param scene defines the hosting scene
  87935. */
  87936. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  87937. var _this = _super.call(this, name, position, scene) || this;
  87938. _this.interaxialDistance = interaxialDistance;
  87939. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87940. return _this;
  87941. }
  87942. /**
  87943. * Gets camera class name
  87944. * @returns AnaglyphUniversalCamera
  87945. */
  87946. AnaglyphUniversalCamera.prototype.getClassName = function () {
  87947. return "AnaglyphUniversalCamera";
  87948. };
  87949. return AnaglyphUniversalCamera;
  87950. }(BABYLON.UniversalCamera));
  87951. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  87952. /**
  87953. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  87954. */
  87955. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  87956. __extends(StereoscopicFreeCamera, _super);
  87957. /**
  87958. * Creates a new StereoscopicFreeCamera
  87959. * @param name defines camera name
  87960. * @param position defines initial position
  87961. * @param interaxialDistance defines distance between each color axis
  87962. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87963. * @param scene defines the hosting scene
  87964. */
  87965. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87966. var _this = _super.call(this, name, position, scene) || this;
  87967. _this.interaxialDistance = interaxialDistance;
  87968. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87969. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87970. return _this;
  87971. }
  87972. /**
  87973. * Gets camera class name
  87974. * @returns StereoscopicFreeCamera
  87975. */
  87976. StereoscopicFreeCamera.prototype.getClassName = function () {
  87977. return "StereoscopicFreeCamera";
  87978. };
  87979. return StereoscopicFreeCamera;
  87980. }(BABYLON.FreeCamera));
  87981. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  87982. /**
  87983. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  87984. */
  87985. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  87986. __extends(StereoscopicArcRotateCamera, _super);
  87987. /**
  87988. * Creates a new StereoscopicArcRotateCamera
  87989. * @param name defines camera name
  87990. * @param alpha defines alpha angle (in radians)
  87991. * @param beta defines beta angle (in radians)
  87992. * @param radius defines radius
  87993. * @param target defines camera target
  87994. * @param interaxialDistance defines distance between each color axis
  87995. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87996. * @param scene defines the hosting scene
  87997. */
  87998. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  87999. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  88000. _this.interaxialDistance = interaxialDistance;
  88001. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  88002. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  88003. return _this;
  88004. }
  88005. /**
  88006. * Gets camera class name
  88007. * @returns StereoscopicArcRotateCamera
  88008. */
  88009. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  88010. return "StereoscopicArcRotateCamera";
  88011. };
  88012. return StereoscopicArcRotateCamera;
  88013. }(BABYLON.ArcRotateCamera));
  88014. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  88015. /**
  88016. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  88017. */
  88018. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  88019. __extends(StereoscopicGamepadCamera, _super);
  88020. /**
  88021. * Creates a new StereoscopicGamepadCamera
  88022. * @param name defines camera name
  88023. * @param position defines initial position
  88024. * @param interaxialDistance defines distance between each color axis
  88025. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  88026. * @param scene defines the hosting scene
  88027. */
  88028. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  88029. var _this = _super.call(this, name, position, scene) || this;
  88030. _this.interaxialDistance = interaxialDistance;
  88031. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  88032. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  88033. return _this;
  88034. }
  88035. /**
  88036. * Gets camera class name
  88037. * @returns StereoscopicGamepadCamera
  88038. */
  88039. StereoscopicGamepadCamera.prototype.getClassName = function () {
  88040. return "StereoscopicGamepadCamera";
  88041. };
  88042. return StereoscopicGamepadCamera;
  88043. }(BABYLON.GamepadCamera));
  88044. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  88045. /**
  88046. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  88047. */
  88048. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  88049. __extends(StereoscopicUniversalCamera, _super);
  88050. /**
  88051. * Creates a new StereoscopicUniversalCamera
  88052. * @param name defines camera name
  88053. * @param position defines initial position
  88054. * @param interaxialDistance defines distance between each color axis
  88055. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  88056. * @param scene defines the hosting scene
  88057. */
  88058. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  88059. var _this = _super.call(this, name, position, scene) || this;
  88060. _this.interaxialDistance = interaxialDistance;
  88061. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  88062. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  88063. return _this;
  88064. }
  88065. /**
  88066. * Gets camera class name
  88067. * @returns StereoscopicUniversalCamera
  88068. */
  88069. StereoscopicUniversalCamera.prototype.getClassName = function () {
  88070. return "StereoscopicUniversalCamera";
  88071. };
  88072. return StereoscopicUniversalCamera;
  88073. }(BABYLON.UniversalCamera));
  88074. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  88075. })(BABYLON || (BABYLON = {}));
  88076. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  88077. var BABYLON;
  88078. (function (BABYLON) {
  88079. var VRExperienceHelperGazer = /** @class */ (function () {
  88080. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  88081. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  88082. this.scene = scene;
  88083. this._pointerDownOnMeshAsked = false;
  88084. this._isActionableMesh = false;
  88085. this._teleportationRequestInitiated = false;
  88086. this._teleportationBackRequestInitiated = false;
  88087. this._rotationRightAsked = false;
  88088. this._rotationLeftAsked = false;
  88089. this._dpadPressed = true;
  88090. this._activePointer = false;
  88091. this._id = VRExperienceHelperGazer._idCounter++;
  88092. // Gaze tracker
  88093. if (!gazeTrackerToClone) {
  88094. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  88095. this._gazeTracker.bakeCurrentTransformIntoVertices();
  88096. this._gazeTracker.isPickable = false;
  88097. this._gazeTracker.isVisible = false;
  88098. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  88099. targetMat.specularColor = BABYLON.Color3.Black();
  88100. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  88101. targetMat.backFaceCulling = false;
  88102. this._gazeTracker.material = targetMat;
  88103. }
  88104. else {
  88105. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  88106. }
  88107. }
  88108. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  88109. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  88110. };
  88111. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  88112. this._pointerDownOnMeshAsked = true;
  88113. if (this._currentHit) {
  88114. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  88115. }
  88116. };
  88117. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  88118. if (this._currentHit) {
  88119. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  88120. }
  88121. this._pointerDownOnMeshAsked = false;
  88122. };
  88123. VRExperienceHelperGazer.prototype._activatePointer = function () {
  88124. this._activePointer = true;
  88125. };
  88126. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  88127. this._activePointer = false;
  88128. };
  88129. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  88130. if (distance === void 0) { distance = 100; }
  88131. };
  88132. VRExperienceHelperGazer.prototype.dispose = function () {
  88133. this._interactionsEnabled = false;
  88134. this._teleportationEnabled = false;
  88135. if (this._gazeTracker) {
  88136. this._gazeTracker.dispose();
  88137. }
  88138. };
  88139. VRExperienceHelperGazer._idCounter = 0;
  88140. return VRExperienceHelperGazer;
  88141. }());
  88142. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  88143. __extends(VRExperienceHelperControllerGazer, _super);
  88144. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  88145. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  88146. _this.webVRController = webVRController;
  88147. // Laser pointer
  88148. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  88149. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  88150. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  88151. laserPointerMaterial.alpha = 0.6;
  88152. _this._laserPointer.material = laserPointerMaterial;
  88153. _this._laserPointer.rotation.x = Math.PI / 2;
  88154. _this._laserPointer.position.z = -0.5;
  88155. _this._laserPointer.isVisible = false;
  88156. if (!webVRController.mesh) {
  88157. // Create an empty mesh that is used prior to loading the high quality model
  88158. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  88159. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  88160. preloadPointerPose.rotation.x = -0.7;
  88161. preloadMesh.addChild(preloadPointerPose);
  88162. webVRController.attachToMesh(preloadMesh);
  88163. }
  88164. _this._setLaserPointerParent(webVRController.mesh);
  88165. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  88166. _this._setLaserPointerParent(mesh);
  88167. });
  88168. return _this;
  88169. }
  88170. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  88171. return this.webVRController.getForwardRay(length);
  88172. };
  88173. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  88174. _super.prototype._activatePointer.call(this);
  88175. this._laserPointer.isVisible = true;
  88176. };
  88177. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  88178. _super.prototype._deactivatePointer.call(this);
  88179. this._laserPointer.isVisible = false;
  88180. };
  88181. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  88182. this._laserPointer.material.emissiveColor = color;
  88183. };
  88184. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  88185. var makeNotPick = function (root) {
  88186. root.name += " laserPointer";
  88187. root.getChildMeshes().forEach(function (c) {
  88188. makeNotPick(c);
  88189. });
  88190. };
  88191. makeNotPick(mesh);
  88192. var childMeshes = mesh.getChildMeshes();
  88193. this.webVRController._pointingPoseNode = null;
  88194. for (var i = 0; i < childMeshes.length; i++) {
  88195. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  88196. mesh = childMeshes[i];
  88197. this.webVRController._pointingPoseNode = mesh;
  88198. break;
  88199. }
  88200. }
  88201. this._laserPointer.parent = mesh;
  88202. };
  88203. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  88204. if (distance === void 0) { distance = 100; }
  88205. this._laserPointer.scaling.y = distance;
  88206. this._laserPointer.position.z = -distance / 2;
  88207. };
  88208. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  88209. _super.prototype.dispose.call(this);
  88210. this._laserPointer.dispose();
  88211. if (this._meshAttachedObserver) {
  88212. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  88213. }
  88214. };
  88215. return VRExperienceHelperControllerGazer;
  88216. }(VRExperienceHelperGazer));
  88217. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  88218. __extends(VRExperienceHelperCameraGazer, _super);
  88219. function VRExperienceHelperCameraGazer(getCamera, scene) {
  88220. var _this = _super.call(this, scene) || this;
  88221. _this.getCamera = getCamera;
  88222. return _this;
  88223. }
  88224. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  88225. var camera = this.getCamera();
  88226. if (camera) {
  88227. return camera.getForwardRay(length);
  88228. }
  88229. else {
  88230. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  88231. }
  88232. };
  88233. return VRExperienceHelperCameraGazer;
  88234. }(VRExperienceHelperGazer));
  88235. /**
  88236. * Helps to quickly add VR support to an existing scene.
  88237. * See http://doc.babylonjs.com/how_to/webvr_helper
  88238. */
  88239. var VRExperienceHelper = /** @class */ (function () {
  88240. /**
  88241. * Instantiates a VRExperienceHelper.
  88242. * Helps to quickly add VR support to an existing scene.
  88243. * @param scene The scene the VRExperienceHelper belongs to.
  88244. * @param webVROptions Options to modify the vr experience helper's behavior.
  88245. */
  88246. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  88247. if (webVROptions === void 0) { webVROptions = {}; }
  88248. var _this = this;
  88249. this.webVROptions = webVROptions;
  88250. // Can the system support WebVR, even if a headset isn't plugged in?
  88251. this._webVRsupported = false;
  88252. // If WebVR is supported, is a headset plugged in and are we ready to present?
  88253. this._webVRready = false;
  88254. // Are we waiting for the requestPresent callback to complete?
  88255. this._webVRrequesting = false;
  88256. // Are we presenting to the headset right now?
  88257. this._webVRpresenting = false;
  88258. // Are we presenting in the fullscreen fallback?
  88259. this._fullscreenVRpresenting = false;
  88260. /**
  88261. * Observable raised when entering VR.
  88262. */
  88263. this.onEnteringVRObservable = new BABYLON.Observable();
  88264. /**
  88265. * Observable raised when exiting VR.
  88266. */
  88267. this.onExitingVRObservable = new BABYLON.Observable();
  88268. /**
  88269. * Observable raised when controller mesh is loaded.
  88270. */
  88271. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  88272. this._useCustomVRButton = false;
  88273. this._teleportationRequested = false;
  88274. this._teleportActive = false;
  88275. this._floorMeshesCollection = [];
  88276. this._rotationAllowed = true;
  88277. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  88278. this._isDefaultTeleportationTarget = true;
  88279. this._teleportationFillColor = "#444444";
  88280. this._teleportationBorderColor = "#FFFFFF";
  88281. this._rotationAngle = 0;
  88282. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  88283. this._padSensibilityUp = 0.65;
  88284. this._padSensibilityDown = 0.35;
  88285. this.leftController = null;
  88286. this.rightController = null;
  88287. /**
  88288. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  88289. */
  88290. this.onNewMeshSelected = new BABYLON.Observable();
  88291. /**
  88292. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  88293. */
  88294. this.onNewMeshPicked = new BABYLON.Observable();
  88295. /**
  88296. * Observable raised before camera teleportation
  88297. */
  88298. this.onBeforeCameraTeleport = new BABYLON.Observable();
  88299. /**
  88300. * Observable raised after camera teleportation
  88301. */
  88302. this.onAfterCameraTeleport = new BABYLON.Observable();
  88303. /**
  88304. * Observable raised when current selected mesh gets unselected
  88305. */
  88306. this.onSelectedMeshUnselected = new BABYLON.Observable();
  88307. /**
  88308. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  88309. */
  88310. this.teleportationEnabled = true;
  88311. this._teleportationInitialized = false;
  88312. this._interactionsEnabled = false;
  88313. this._interactionsRequested = false;
  88314. this._displayGaze = true;
  88315. this._displayLaserPointer = true;
  88316. this._onResize = function () {
  88317. _this.moveButtonToBottomRight();
  88318. if (_this._fullscreenVRpresenting && _this._webVRready) {
  88319. _this.exitVR();
  88320. }
  88321. };
  88322. this._onFullscreenChange = function () {
  88323. if (document.fullscreen !== undefined) {
  88324. _this._fullscreenVRpresenting = document.fullscreen;
  88325. }
  88326. else if (document.mozFullScreen !== undefined) {
  88327. _this._fullscreenVRpresenting = document.mozFullScreen;
  88328. }
  88329. else if (document.webkitIsFullScreen !== undefined) {
  88330. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  88331. }
  88332. else if (document.msIsFullScreen !== undefined) {
  88333. _this._fullscreenVRpresenting = document.msIsFullScreen;
  88334. }
  88335. if (!_this._fullscreenVRpresenting && _this._canvas) {
  88336. _this.exitVR();
  88337. if (!_this._useCustomVRButton) {
  88338. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  88339. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  88340. }
  88341. }
  88342. };
  88343. this.beforeRender = function () {
  88344. if (_this.leftController && _this.leftController._activePointer) {
  88345. _this._castRayAndSelectObject(_this.leftController);
  88346. }
  88347. if (_this.rightController && _this.rightController._activePointer) {
  88348. _this._castRayAndSelectObject(_this.rightController);
  88349. }
  88350. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  88351. _this._castRayAndSelectObject(_this._cameraGazer);
  88352. }
  88353. else {
  88354. _this._cameraGazer._gazeTracker.isVisible = false;
  88355. }
  88356. };
  88357. this._onNewGamepadConnected = function (gamepad) {
  88358. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  88359. if (gamepad.leftStick) {
  88360. gamepad.onleftstickchanged(function (stickValues) {
  88361. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  88362. // Listening to classic/xbox gamepad only if no VR controller is active
  88363. if ((!_this.leftController && !_this.rightController) ||
  88364. ((_this.leftController && !_this.leftController._activePointer) &&
  88365. (_this.rightController && !_this.rightController._activePointer))) {
  88366. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  88367. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  88368. }
  88369. }
  88370. });
  88371. }
  88372. if (gamepad.rightStick) {
  88373. gamepad.onrightstickchanged(function (stickValues) {
  88374. if (_this._teleportationInitialized) {
  88375. _this._checkRotate(stickValues, _this._cameraGazer);
  88376. }
  88377. });
  88378. }
  88379. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  88380. gamepad.onbuttondown(function (buttonPressed) {
  88381. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  88382. _this._cameraGazer._selectionPointerDown();
  88383. }
  88384. });
  88385. gamepad.onbuttonup(function (buttonPressed) {
  88386. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  88387. _this._cameraGazer._selectionPointerUp();
  88388. }
  88389. });
  88390. }
  88391. }
  88392. else {
  88393. var webVRController = gamepad;
  88394. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  88395. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  88396. _this.rightController = controller;
  88397. }
  88398. else {
  88399. _this.leftController = controller;
  88400. }
  88401. _this._tryEnableInteractionOnController(controller);
  88402. }
  88403. };
  88404. // This only succeeds if the controller's mesh exists for the controller so this must be called whenever new controller is connected or when mesh is loaded
  88405. this._tryEnableInteractionOnController = function (controller) {
  88406. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  88407. _this._enableInteractionOnController(controller);
  88408. }
  88409. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  88410. _this._enableTeleportationOnController(controller);
  88411. }
  88412. };
  88413. this._onNewGamepadDisconnected = function (gamepad) {
  88414. if (gamepad instanceof BABYLON.WebVRController) {
  88415. if (gamepad.hand === "left" && _this.leftController != null) {
  88416. _this.leftController.dispose();
  88417. _this.leftController = null;
  88418. }
  88419. if (gamepad.hand === "right" && _this.rightController != null) {
  88420. _this.rightController.dispose();
  88421. _this.rightController = null;
  88422. }
  88423. }
  88424. };
  88425. this._workingVector = BABYLON.Vector3.Zero();
  88426. this._workingQuaternion = BABYLON.Quaternion.Identity();
  88427. this._workingMatrix = BABYLON.Matrix.Identity();
  88428. this._scene = scene;
  88429. this._canvas = scene.getEngine().getRenderingCanvas();
  88430. // Parse options
  88431. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  88432. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  88433. }
  88434. if (webVROptions.createDeviceOrientationCamera === undefined) {
  88435. webVROptions.createDeviceOrientationCamera = true;
  88436. }
  88437. if (webVROptions.laserToggle === undefined) {
  88438. webVROptions.laserToggle = true;
  88439. }
  88440. if (webVROptions.defaultHeight === undefined) {
  88441. webVROptions.defaultHeight = 1.7;
  88442. }
  88443. if (webVROptions.useCustomVRButton) {
  88444. this._useCustomVRButton = true;
  88445. if (webVROptions.customVRButton) {
  88446. this._btnVR = webVROptions.customVRButton;
  88447. }
  88448. }
  88449. if (webVROptions.rayLength) {
  88450. this._rayLength = webVROptions.rayLength;
  88451. }
  88452. this._defaultHeight = webVROptions.defaultHeight;
  88453. if (webVROptions.positionScale) {
  88454. this._rayLength *= webVROptions.positionScale;
  88455. this._defaultHeight *= webVROptions.positionScale;
  88456. }
  88457. // Set position
  88458. if (this._scene.activeCamera) {
  88459. this._position = this._scene.activeCamera.position.clone();
  88460. }
  88461. else {
  88462. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  88463. }
  88464. // Set non-vr camera
  88465. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  88466. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  88467. // Copy data from existing camera
  88468. if (this._scene.activeCamera) {
  88469. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88470. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  88471. // Set rotation from previous camera
  88472. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  88473. var targetCamera = this._scene.activeCamera;
  88474. if (targetCamera.rotationQuaternion) {
  88475. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  88476. }
  88477. else {
  88478. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  88479. }
  88480. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  88481. }
  88482. }
  88483. this._scene.activeCamera = this._deviceOrientationCamera;
  88484. if (this._canvas) {
  88485. this._scene.activeCamera.attachControl(this._canvas);
  88486. }
  88487. }
  88488. else {
  88489. this._existingCamera = this._scene.activeCamera;
  88490. }
  88491. // Create VR cameras
  88492. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  88493. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  88494. }
  88495. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  88496. this._webVRCamera.useStandingMatrix();
  88497. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  88498. // Create default button
  88499. if (!this._useCustomVRButton) {
  88500. this._btnVR = document.createElement("BUTTON");
  88501. this._btnVR.className = "babylonVRicon";
  88502. this._btnVR.id = "babylonVRiconbtn";
  88503. this._btnVR.title = "Click to switch to VR";
  88504. var css = ".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";
  88505. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  88506. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  88507. // css += ".babylonVRicon.vrdisplaysupported { }";
  88508. // css += ".babylonVRicon.vrdisplayready { }";
  88509. // css += ".babylonVRicon.vrdisplayrequesting { }";
  88510. var style = document.createElement('style');
  88511. style.appendChild(document.createTextNode(css));
  88512. document.getElementsByTagName('head')[0].appendChild(style);
  88513. this.moveButtonToBottomRight();
  88514. }
  88515. // VR button click event
  88516. if (this._btnVR) {
  88517. this._btnVR.addEventListener("click", function () {
  88518. if (!_this.isInVRMode) {
  88519. _this.enterVR();
  88520. }
  88521. else {
  88522. _this.exitVR();
  88523. }
  88524. });
  88525. }
  88526. // Window events
  88527. window.addEventListener("resize", this._onResize);
  88528. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  88529. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  88530. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  88531. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  88532. // Display vr button when headset is connected
  88533. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  88534. this.displayVRButton();
  88535. }
  88536. else {
  88537. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  88538. if (e.vrDisplay) {
  88539. _this.displayVRButton();
  88540. }
  88541. });
  88542. }
  88543. // Exiting VR mode using 'ESC' key on desktop
  88544. this._onKeyDown = function (event) {
  88545. if (event.keyCode === 27 && _this.isInVRMode) {
  88546. _this.exitVR();
  88547. }
  88548. };
  88549. document.addEventListener("keydown", this._onKeyDown);
  88550. // Exiting VR mode double tapping the touch screen
  88551. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  88552. if (_this.isInVRMode) {
  88553. _this.exitVR();
  88554. if (_this._fullscreenVRpresenting) {
  88555. _this._scene.getEngine().switchFullscreen(true);
  88556. }
  88557. }
  88558. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  88559. // Listen for WebVR display changes
  88560. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  88561. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  88562. this._onVRRequestPresentStart = function () {
  88563. _this._webVRrequesting = true;
  88564. _this.updateButtonVisibility();
  88565. };
  88566. this._onVRRequestPresentComplete = function (success) {
  88567. _this._webVRrequesting = false;
  88568. _this.updateButtonVisibility();
  88569. };
  88570. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  88571. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  88572. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  88573. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88574. scene.onDisposeObservable.add(function () {
  88575. _this.dispose();
  88576. });
  88577. // Gamepad connection events
  88578. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  88579. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  88580. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  88581. this.updateButtonVisibility();
  88582. //create easing functions
  88583. this._circleEase = new BABYLON.CircleEase();
  88584. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88585. if (this.webVROptions.floorMeshes) {
  88586. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  88587. }
  88588. }
  88589. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  88590. /** Return this.onEnteringVRObservable
  88591. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  88592. */
  88593. get: function () {
  88594. return this.onEnteringVRObservable;
  88595. },
  88596. enumerable: true,
  88597. configurable: true
  88598. });
  88599. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  88600. /** Return this.onExitingVRObservable
  88601. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  88602. */
  88603. get: function () {
  88604. return this.onExitingVRObservable;
  88605. },
  88606. enumerable: true,
  88607. configurable: true
  88608. });
  88609. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  88610. /** Return this.onControllerMeshLoadedObservable
  88611. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  88612. */
  88613. get: function () {
  88614. return this.onControllerMeshLoadedObservable;
  88615. },
  88616. enumerable: true,
  88617. configurable: true
  88618. });
  88619. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  88620. /**
  88621. * The mesh used to display where the user is going to teleport.
  88622. */
  88623. get: function () {
  88624. return this._teleportationTarget;
  88625. },
  88626. /**
  88627. * Sets the mesh to be used to display where the user is going to teleport.
  88628. */
  88629. set: function (value) {
  88630. if (value) {
  88631. value.name = "teleportationTarget";
  88632. this._isDefaultTeleportationTarget = false;
  88633. this._teleportationTarget = value;
  88634. }
  88635. },
  88636. enumerable: true,
  88637. configurable: true
  88638. });
  88639. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  88640. /**
  88641. * The mesh used to display where the user is selecting,
  88642. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  88643. * See http://doc.babylonjs.com/resources/baking_transformations
  88644. */
  88645. get: function () {
  88646. return this._cameraGazer._gazeTracker;
  88647. },
  88648. set: function (value) {
  88649. if (value) {
  88650. this._cameraGazer._gazeTracker = value;
  88651. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  88652. this._cameraGazer._gazeTracker.isPickable = false;
  88653. this._cameraGazer._gazeTracker.isVisible = false;
  88654. this._cameraGazer._gazeTracker.name = "gazeTracker";
  88655. if (this.leftController) {
  88656. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  88657. }
  88658. if (this.rightController) {
  88659. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  88660. }
  88661. }
  88662. },
  88663. enumerable: true,
  88664. configurable: true
  88665. });
  88666. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  88667. /**
  88668. * If the ray of the gaze should be displayed.
  88669. */
  88670. get: function () {
  88671. return this._displayGaze;
  88672. },
  88673. /**
  88674. * Sets if the ray of the gaze should be displayed.
  88675. */
  88676. set: function (value) {
  88677. this._displayGaze = value;
  88678. if (!value) {
  88679. this._cameraGazer._gazeTracker.isVisible = false;
  88680. if (this.leftController) {
  88681. this.leftController._gazeTracker.isVisible = false;
  88682. }
  88683. if (this.rightController) {
  88684. this.rightController._gazeTracker.isVisible = false;
  88685. }
  88686. }
  88687. },
  88688. enumerable: true,
  88689. configurable: true
  88690. });
  88691. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  88692. /**
  88693. * If the ray of the LaserPointer should be displayed.
  88694. */
  88695. get: function () {
  88696. return this._displayLaserPointer;
  88697. },
  88698. /**
  88699. * Sets if the ray of the LaserPointer should be displayed.
  88700. */
  88701. set: function (value) {
  88702. this._displayLaserPointer = value;
  88703. if (!value) {
  88704. if (this.rightController) {
  88705. this.rightController._deactivatePointer();
  88706. this.rightController._gazeTracker.isVisible = false;
  88707. }
  88708. if (this.leftController) {
  88709. this.leftController._deactivatePointer();
  88710. this.leftController._gazeTracker.isVisible = false;
  88711. }
  88712. }
  88713. else {
  88714. if (this.rightController) {
  88715. this.rightController._activatePointer();
  88716. }
  88717. if (this.leftController) {
  88718. this.leftController._activatePointer();
  88719. }
  88720. }
  88721. },
  88722. enumerable: true,
  88723. configurable: true
  88724. });
  88725. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  88726. /**
  88727. * The deviceOrientationCamera used as the camera when not in VR.
  88728. */
  88729. get: function () {
  88730. return this._deviceOrientationCamera;
  88731. },
  88732. enumerable: true,
  88733. configurable: true
  88734. });
  88735. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  88736. /**
  88737. * Based on the current WebVR support, returns the current VR camera used.
  88738. */
  88739. get: function () {
  88740. if (this._webVRready) {
  88741. return this._webVRCamera;
  88742. }
  88743. else {
  88744. return this._scene.activeCamera;
  88745. }
  88746. },
  88747. enumerable: true,
  88748. configurable: true
  88749. });
  88750. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  88751. /**
  88752. * The webVRCamera which is used when in VR.
  88753. */
  88754. get: function () {
  88755. return this._webVRCamera;
  88756. },
  88757. enumerable: true,
  88758. configurable: true
  88759. });
  88760. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  88761. /**
  88762. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  88763. */
  88764. get: function () {
  88765. return this._vrDeviceOrientationCamera;
  88766. },
  88767. enumerable: true,
  88768. configurable: true
  88769. });
  88770. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  88771. get: function () {
  88772. var result = this._cameraGazer._teleportationRequestInitiated
  88773. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  88774. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  88775. return result;
  88776. },
  88777. enumerable: true,
  88778. configurable: true
  88779. });
  88780. // Raised when one of the controller has loaded successfully its associated default mesh
  88781. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  88782. if (this.leftController && this.leftController.webVRController == webVRController) {
  88783. if (webVRController.mesh) {
  88784. this.leftController._setLaserPointerParent(webVRController.mesh);
  88785. }
  88786. }
  88787. if (this.rightController && this.rightController.webVRController == webVRController) {
  88788. if (webVRController.mesh) {
  88789. this.rightController._setLaserPointerParent(webVRController.mesh);
  88790. }
  88791. }
  88792. try {
  88793. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  88794. }
  88795. catch (err) {
  88796. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  88797. }
  88798. };
  88799. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  88800. /**
  88801. * Gets a value indicating if we are currently in VR mode.
  88802. */
  88803. get: function () {
  88804. return this._webVRpresenting || this._fullscreenVRpresenting;
  88805. },
  88806. enumerable: true,
  88807. configurable: true
  88808. });
  88809. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  88810. var vrDisplay = this._scene.getEngine().getVRDevice();
  88811. if (vrDisplay) {
  88812. var wasPresenting = this._webVRpresenting;
  88813. // A VR display is connected
  88814. this._webVRpresenting = vrDisplay.isPresenting;
  88815. if (wasPresenting && !this._webVRpresenting)
  88816. this.exitVR();
  88817. }
  88818. else {
  88819. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  88820. }
  88821. this.updateButtonVisibility();
  88822. };
  88823. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  88824. this._webVRsupported = eventArgs.vrSupported;
  88825. this._webVRready = !!eventArgs.vrDisplay;
  88826. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  88827. this.updateButtonVisibility();
  88828. };
  88829. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  88830. if (this._canvas && !this._useCustomVRButton) {
  88831. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  88832. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  88833. }
  88834. };
  88835. VRExperienceHelper.prototype.displayVRButton = function () {
  88836. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  88837. document.body.appendChild(this._btnVR);
  88838. this._btnVRDisplayed = true;
  88839. }
  88840. };
  88841. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  88842. if (!this._btnVR || this._useCustomVRButton) {
  88843. return;
  88844. }
  88845. this._btnVR.className = "babylonVRicon";
  88846. if (this.isInVRMode) {
  88847. this._btnVR.className += " vrdisplaypresenting";
  88848. }
  88849. else {
  88850. if (this._webVRready)
  88851. this._btnVR.className += " vrdisplayready";
  88852. if (this._webVRsupported)
  88853. this._btnVR.className += " vrdisplaysupported";
  88854. if (this._webVRrequesting)
  88855. this._btnVR.className += " vrdisplayrequesting";
  88856. }
  88857. };
  88858. /**
  88859. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  88860. * Otherwise, will use the fullscreen API.
  88861. */
  88862. VRExperienceHelper.prototype.enterVR = function () {
  88863. if (this.onEnteringVRObservable) {
  88864. try {
  88865. this.onEnteringVRObservable.notifyObservers(this);
  88866. }
  88867. catch (err) {
  88868. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  88869. }
  88870. }
  88871. if (this._scene.activeCamera) {
  88872. this._position = this._scene.activeCamera.position.clone();
  88873. // make sure that we return to the last active camera
  88874. this._existingCamera = this._scene.activeCamera;
  88875. }
  88876. if (this._webVRrequesting)
  88877. return;
  88878. // If WebVR is supported and a headset is connected
  88879. if (this._webVRready) {
  88880. if (!this._webVRpresenting) {
  88881. this._webVRCamera.position = this._position;
  88882. this._scene.activeCamera = this._webVRCamera;
  88883. }
  88884. }
  88885. else if (this._vrDeviceOrientationCamera) {
  88886. this._vrDeviceOrientationCamera.position = this._position;
  88887. if (this._scene.activeCamera) {
  88888. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88889. }
  88890. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  88891. this._scene.getEngine().switchFullscreen(true);
  88892. this.updateButtonVisibility();
  88893. }
  88894. if (this._scene.activeCamera && this._canvas) {
  88895. this._scene.activeCamera.attachControl(this._canvas);
  88896. }
  88897. if (this._interactionsEnabled) {
  88898. this._scene.registerBeforeRender(this.beforeRender);
  88899. }
  88900. };
  88901. /**
  88902. * Attempt to exit VR, or fullscreen.
  88903. */
  88904. VRExperienceHelper.prototype.exitVR = function () {
  88905. if (this.onExitingVRObservable) {
  88906. try {
  88907. this.onExitingVRObservable.notifyObservers(this);
  88908. }
  88909. catch (err) {
  88910. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  88911. }
  88912. }
  88913. if (this._webVRpresenting) {
  88914. this._scene.getEngine().disableVR();
  88915. }
  88916. if (this._scene.activeCamera) {
  88917. this._position = this._scene.activeCamera.position.clone();
  88918. }
  88919. if (this._deviceOrientationCamera) {
  88920. this._deviceOrientationCamera.position = this._position;
  88921. this._scene.activeCamera = this._deviceOrientationCamera;
  88922. if (this._canvas) {
  88923. this._scene.activeCamera.attachControl(this._canvas);
  88924. }
  88925. }
  88926. else if (this._existingCamera) {
  88927. this._existingCamera.position = this._position;
  88928. this._scene.activeCamera = this._existingCamera;
  88929. }
  88930. this.updateButtonVisibility();
  88931. if (this._interactionsEnabled) {
  88932. this._scene.unregisterBeforeRender(this.beforeRender);
  88933. }
  88934. // resize to update width and height when exiting vr exits fullscreen
  88935. this._scene.getEngine().resize();
  88936. };
  88937. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  88938. /**
  88939. * The position of the vr experience helper.
  88940. */
  88941. get: function () {
  88942. return this._position;
  88943. },
  88944. /**
  88945. * Sets the position of the vr experience helper.
  88946. */
  88947. set: function (value) {
  88948. this._position = value;
  88949. if (this._scene.activeCamera) {
  88950. this._scene.activeCamera.position = value;
  88951. }
  88952. },
  88953. enumerable: true,
  88954. configurable: true
  88955. });
  88956. /**
  88957. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  88958. */
  88959. VRExperienceHelper.prototype.enableInteractions = function () {
  88960. var _this = this;
  88961. if (!this._interactionsEnabled) {
  88962. this._interactionsRequested = true;
  88963. if (this.leftController) {
  88964. this._enableInteractionOnController(this.leftController);
  88965. }
  88966. if (this.rightController) {
  88967. this._enableInteractionOnController(this.rightController);
  88968. }
  88969. this.raySelectionPredicate = function (mesh) {
  88970. return mesh.isVisible;
  88971. };
  88972. this.meshSelectionPredicate = function (mesh) {
  88973. return true;
  88974. };
  88975. this._raySelectionPredicate = function (mesh) {
  88976. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  88977. && mesh.name.indexOf("teleportationTarget") === -1
  88978. && mesh.name.indexOf("torusTeleportation") === -1
  88979. && mesh.name.indexOf("laserPointer") === -1)) {
  88980. return _this.raySelectionPredicate(mesh);
  88981. }
  88982. return false;
  88983. };
  88984. this._interactionsEnabled = true;
  88985. }
  88986. };
  88987. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  88988. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  88989. if (this._floorMeshesCollection[i].id === mesh.id) {
  88990. return true;
  88991. }
  88992. }
  88993. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  88994. return true;
  88995. }
  88996. return false;
  88997. };
  88998. /**
  88999. * Adds a floor mesh to be used for teleportation.
  89000. * @param floorMesh the mesh to be used for teleportation.
  89001. */
  89002. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  89003. if (!this._floorMeshesCollection) {
  89004. return;
  89005. }
  89006. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  89007. return;
  89008. }
  89009. this._floorMeshesCollection.push(floorMesh);
  89010. };
  89011. /**
  89012. * Removes a floor mesh from being used for teleportation.
  89013. * @param floorMesh the mesh to be removed.
  89014. */
  89015. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  89016. if (!this._floorMeshesCollection) {
  89017. return;
  89018. }
  89019. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  89020. if (meshIndex !== -1) {
  89021. this._floorMeshesCollection.splice(meshIndex, 1);
  89022. }
  89023. };
  89024. /**
  89025. * Enables interactions and teleportation using the VR controllers and gaze.
  89026. * @param vrTeleportationOptions options to modify teleportation behavior.
  89027. */
  89028. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  89029. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  89030. if (!this._teleportationInitialized) {
  89031. this._teleportationRequested = true;
  89032. this.enableInteractions();
  89033. if (vrTeleportationOptions.floorMeshName) {
  89034. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  89035. }
  89036. if (vrTeleportationOptions.floorMeshes) {
  89037. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  89038. }
  89039. if (this.leftController != null) {
  89040. this._enableTeleportationOnController(this.leftController);
  89041. }
  89042. if (this.rightController != null) {
  89043. this._enableTeleportationOnController(this.rightController);
  89044. }
  89045. // Creates an image processing post process for the vignette not relying
  89046. // on the main scene configuration for image processing to reduce setup and spaces
  89047. // (gamma/linear) conflicts.
  89048. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  89049. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  89050. imageProcessingConfiguration.vignetteEnabled = true;
  89051. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  89052. this._webVRCamera.detachPostProcess(this._postProcessMove);
  89053. this._teleportationInitialized = true;
  89054. if (this._isDefaultTeleportationTarget) {
  89055. this._createTeleportationCircles();
  89056. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  89057. }
  89058. }
  89059. };
  89060. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  89061. var _this = this;
  89062. var controllerMesh = controller.webVRController.mesh;
  89063. if (controllerMesh) {
  89064. controller._interactionsEnabled = true;
  89065. controller._activatePointer();
  89066. if (this.webVROptions.laserToggle) {
  89067. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  89068. // Enabling / disabling laserPointer
  89069. if (_this._displayLaserPointer && stateObject.value === 1) {
  89070. if (controller._activePointer) {
  89071. controller._deactivatePointer();
  89072. }
  89073. else {
  89074. controller._activatePointer();
  89075. }
  89076. if (_this.displayGaze) {
  89077. controller._gazeTracker.isVisible = controller._activePointer;
  89078. }
  89079. }
  89080. });
  89081. }
  89082. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  89083. if (!controller._pointerDownOnMeshAsked) {
  89084. if (stateObject.value > _this._padSensibilityUp) {
  89085. controller._selectionPointerDown();
  89086. }
  89087. }
  89088. else if (stateObject.value < _this._padSensibilityDown) {
  89089. controller._selectionPointerUp();
  89090. }
  89091. });
  89092. }
  89093. };
  89094. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  89095. // Dont teleport if another gaze already requested teleportation
  89096. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  89097. return;
  89098. }
  89099. if (!gazer._teleportationRequestInitiated) {
  89100. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  89101. gazer._activatePointer();
  89102. gazer._teleportationRequestInitiated = true;
  89103. }
  89104. }
  89105. else {
  89106. // Listening to the proper controller values changes to confirm teleportation
  89107. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  89108. if (this._teleportActive) {
  89109. this._teleportCamera(this._haloCenter);
  89110. }
  89111. gazer._teleportationRequestInitiated = false;
  89112. }
  89113. }
  89114. };
  89115. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  89116. // Only rotate when user is not currently selecting a teleportation location
  89117. if (gazer._teleportationRequestInitiated) {
  89118. return;
  89119. }
  89120. if (!gazer._rotationLeftAsked) {
  89121. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  89122. gazer._rotationLeftAsked = true;
  89123. if (this._rotationAllowed) {
  89124. this._rotateCamera(false);
  89125. }
  89126. }
  89127. }
  89128. else {
  89129. if (stateObject.x > -this._padSensibilityDown) {
  89130. gazer._rotationLeftAsked = false;
  89131. }
  89132. }
  89133. if (!gazer._rotationRightAsked) {
  89134. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  89135. gazer._rotationRightAsked = true;
  89136. if (this._rotationAllowed) {
  89137. this._rotateCamera(true);
  89138. }
  89139. }
  89140. }
  89141. else {
  89142. if (stateObject.x < this._padSensibilityDown) {
  89143. gazer._rotationRightAsked = false;
  89144. }
  89145. }
  89146. };
  89147. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  89148. // Only teleport backwards when user is not currently selecting a teleportation location
  89149. if (gazer._teleportationRequestInitiated) {
  89150. return;
  89151. }
  89152. // Teleport backwards
  89153. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  89154. if (!gazer._teleportationBackRequestInitiated) {
  89155. if (!this.currentVRCamera) {
  89156. return;
  89157. }
  89158. // Get rotation and position of the current camera
  89159. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  89160. var position = this.currentVRCamera.position;
  89161. // If the camera has device position, use that instead
  89162. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  89163. rotation = this.currentVRCamera.deviceRotationQuaternion;
  89164. position = this.currentVRCamera.devicePosition;
  89165. }
  89166. // Get matrix with only the y rotation of the device rotation
  89167. rotation.toEulerAnglesToRef(this._workingVector);
  89168. this._workingVector.z = 0;
  89169. this._workingVector.x = 0;
  89170. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  89171. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  89172. // Rotate backwards ray by device rotation to cast at the ground behind the user
  89173. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  89174. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  89175. var ray = new BABYLON.Ray(position, this._workingVector);
  89176. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  89177. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  89178. this._teleportCamera(hit.pickedPoint);
  89179. }
  89180. gazer._teleportationBackRequestInitiated = true;
  89181. }
  89182. }
  89183. else {
  89184. gazer._teleportationBackRequestInitiated = false;
  89185. }
  89186. };
  89187. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  89188. var _this = this;
  89189. var controllerMesh = controller.webVRController.mesh;
  89190. if (controllerMesh) {
  89191. if (!controller._interactionsEnabled) {
  89192. this._enableInteractionOnController(controller);
  89193. }
  89194. controller._interactionsEnabled = true;
  89195. controller._teleportationEnabled = true;
  89196. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  89197. controller._dpadPressed = false;
  89198. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  89199. controller._dpadPressed = stateObject.pressed;
  89200. if (!controller._dpadPressed) {
  89201. controller._rotationLeftAsked = false;
  89202. controller._rotationRightAsked = false;
  89203. controller._teleportationBackRequestInitiated = false;
  89204. }
  89205. });
  89206. }
  89207. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  89208. if (_this.teleportationEnabled) {
  89209. _this._checkTeleportBackwards(stateObject, controller);
  89210. _this._checkTeleportWithRay(stateObject, controller);
  89211. }
  89212. _this._checkRotate(stateObject, controller);
  89213. });
  89214. }
  89215. };
  89216. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  89217. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  89218. this._teleportationTarget.isPickable = false;
  89219. var length = 512;
  89220. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  89221. dynamicTexture.hasAlpha = true;
  89222. var context = dynamicTexture.getContext();
  89223. var centerX = length / 2;
  89224. var centerY = length / 2;
  89225. var radius = 200;
  89226. context.beginPath();
  89227. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  89228. context.fillStyle = this._teleportationFillColor;
  89229. context.fill();
  89230. context.lineWidth = 10;
  89231. context.strokeStyle = this._teleportationBorderColor;
  89232. context.stroke();
  89233. context.closePath();
  89234. dynamicTexture.update();
  89235. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  89236. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  89237. this._teleportationTarget.material = teleportationCircleMaterial;
  89238. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  89239. torus.isPickable = false;
  89240. torus.parent = this._teleportationTarget;
  89241. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  89242. var keys = [];
  89243. keys.push({
  89244. frame: 0,
  89245. value: 0
  89246. });
  89247. keys.push({
  89248. frame: 30,
  89249. value: 0.4
  89250. });
  89251. keys.push({
  89252. frame: 60,
  89253. value: 0
  89254. });
  89255. animationInnerCircle.setKeys(keys);
  89256. var easingFunction = new BABYLON.SineEase();
  89257. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  89258. animationInnerCircle.setEasingFunction(easingFunction);
  89259. torus.animations = [];
  89260. torus.animations.push(animationInnerCircle);
  89261. this._scene.beginAnimation(torus, 0, 60, true);
  89262. this._hideTeleportationTarget();
  89263. };
  89264. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  89265. this._teleportActive = true;
  89266. if (this._teleportationInitialized) {
  89267. this._teleportationTarget.isVisible = true;
  89268. if (this._isDefaultTeleportationTarget) {
  89269. this._teleportationTarget.getChildren()[0].isVisible = true;
  89270. }
  89271. }
  89272. };
  89273. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  89274. this._teleportActive = false;
  89275. if (this._teleportationInitialized) {
  89276. this._teleportationTarget.isVisible = false;
  89277. if (this._isDefaultTeleportationTarget) {
  89278. this._teleportationTarget.getChildren()[0].isVisible = false;
  89279. }
  89280. }
  89281. };
  89282. VRExperienceHelper.prototype._rotateCamera = function (right) {
  89283. var _this = this;
  89284. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  89285. return;
  89286. }
  89287. if (right) {
  89288. this._rotationAngle++;
  89289. }
  89290. else {
  89291. this._rotationAngle--;
  89292. }
  89293. this.currentVRCamera.animations = [];
  89294. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  89295. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89296. var animationRotationKeys = [];
  89297. animationRotationKeys.push({
  89298. frame: 0,
  89299. value: this.currentVRCamera.rotationQuaternion
  89300. });
  89301. animationRotationKeys.push({
  89302. frame: 6,
  89303. value: target
  89304. });
  89305. animationRotation.setKeys(animationRotationKeys);
  89306. animationRotation.setEasingFunction(this._circleEase);
  89307. this.currentVRCamera.animations.push(animationRotation);
  89308. this._postProcessMove.animations = [];
  89309. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89310. var vignetteWeightKeys = [];
  89311. vignetteWeightKeys.push({
  89312. frame: 0,
  89313. value: 0
  89314. });
  89315. vignetteWeightKeys.push({
  89316. frame: 3,
  89317. value: 4
  89318. });
  89319. vignetteWeightKeys.push({
  89320. frame: 6,
  89321. value: 0
  89322. });
  89323. animationPP.setKeys(vignetteWeightKeys);
  89324. animationPP.setEasingFunction(this._circleEase);
  89325. this._postProcessMove.animations.push(animationPP);
  89326. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89327. var vignetteStretchKeys = [];
  89328. vignetteStretchKeys.push({
  89329. frame: 0,
  89330. value: 0
  89331. });
  89332. vignetteStretchKeys.push({
  89333. frame: 3,
  89334. value: 10
  89335. });
  89336. vignetteStretchKeys.push({
  89337. frame: 6,
  89338. value: 0
  89339. });
  89340. animationPP2.setKeys(vignetteStretchKeys);
  89341. animationPP2.setEasingFunction(this._circleEase);
  89342. this._postProcessMove.animations.push(animationPP2);
  89343. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  89344. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  89345. this._postProcessMove.samples = 4;
  89346. this._webVRCamera.attachPostProcess(this._postProcessMove);
  89347. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  89348. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  89349. });
  89350. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  89351. };
  89352. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  89353. if (hit.pickedPoint) {
  89354. if (gazer._teleportationRequestInitiated) {
  89355. this._displayTeleportationTarget();
  89356. this._haloCenter.copyFrom(hit.pickedPoint);
  89357. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  89358. }
  89359. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  89360. if (pickNormal) {
  89361. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  89362. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  89363. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  89364. }
  89365. this._teleportationTarget.position.y += 0.1;
  89366. }
  89367. };
  89368. VRExperienceHelper.prototype._teleportCamera = function (location) {
  89369. var _this = this;
  89370. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  89371. return;
  89372. }
  89373. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  89374. // offset of the headset from the anchor.
  89375. if (this.webVRCamera.leftCamera) {
  89376. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  89377. this._workingVector.subtractInPlace(this.webVRCamera.position);
  89378. location.subtractToRef(this._workingVector, this._workingVector);
  89379. }
  89380. else {
  89381. this._workingVector.copyFrom(location);
  89382. }
  89383. // Add height to account for user's height offset
  89384. if (this.isInVRMode) {
  89385. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  89386. }
  89387. else {
  89388. this._workingVector.y += this._defaultHeight;
  89389. }
  89390. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  89391. // Create animation from the camera's position to the new location
  89392. this.currentVRCamera.animations = [];
  89393. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89394. var animationCameraTeleportationKeys = [{
  89395. frame: 0,
  89396. value: this.currentVRCamera.position
  89397. },
  89398. {
  89399. frame: 11,
  89400. value: this._workingVector
  89401. }
  89402. ];
  89403. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  89404. animationCameraTeleportation.setEasingFunction(this._circleEase);
  89405. this.currentVRCamera.animations.push(animationCameraTeleportation);
  89406. this._postProcessMove.animations = [];
  89407. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89408. var vignetteWeightKeys = [];
  89409. vignetteWeightKeys.push({
  89410. frame: 0,
  89411. value: 0
  89412. });
  89413. vignetteWeightKeys.push({
  89414. frame: 5,
  89415. value: 8
  89416. });
  89417. vignetteWeightKeys.push({
  89418. frame: 11,
  89419. value: 0
  89420. });
  89421. animationPP.setKeys(vignetteWeightKeys);
  89422. this._postProcessMove.animations.push(animationPP);
  89423. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89424. var vignetteStretchKeys = [];
  89425. vignetteStretchKeys.push({
  89426. frame: 0,
  89427. value: 0
  89428. });
  89429. vignetteStretchKeys.push({
  89430. frame: 5,
  89431. value: 10
  89432. });
  89433. vignetteStretchKeys.push({
  89434. frame: 11,
  89435. value: 0
  89436. });
  89437. animationPP2.setKeys(vignetteStretchKeys);
  89438. this._postProcessMove.animations.push(animationPP2);
  89439. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  89440. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  89441. this._webVRCamera.attachPostProcess(this._postProcessMove);
  89442. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  89443. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  89444. });
  89445. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  89446. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  89447. });
  89448. this._hideTeleportationTarget();
  89449. };
  89450. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  89451. if (normal) {
  89452. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  89453. if (angle < Math.PI / 2) {
  89454. normal.scaleInPlace(-1);
  89455. }
  89456. }
  89457. return normal;
  89458. };
  89459. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  89460. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  89461. return;
  89462. }
  89463. var ray = gazer._getForwardRay(this._rayLength);
  89464. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  89465. if (hit) {
  89466. // Populate the contrllers mesh that can be used for drag/drop
  89467. if (gazer._laserPointer) {
  89468. hit.originMesh = gazer._laserPointer.parent;
  89469. }
  89470. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  89471. }
  89472. gazer._currentHit = hit;
  89473. // Moving the gazeTracker on the mesh face targetted
  89474. if (hit && hit.pickedPoint) {
  89475. if (this._displayGaze) {
  89476. var multiplier = 1;
  89477. gazer._gazeTracker.isVisible = true;
  89478. if (gazer._isActionableMesh) {
  89479. multiplier = 3;
  89480. }
  89481. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  89482. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  89483. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  89484. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  89485. // To avoid z-fighting
  89486. var deltaFighting = 0.002;
  89487. if (pickNormal) {
  89488. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  89489. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  89490. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  89491. }
  89492. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  89493. if (gazer._gazeTracker.position.x < 0) {
  89494. gazer._gazeTracker.position.x += deltaFighting;
  89495. }
  89496. else {
  89497. gazer._gazeTracker.position.x -= deltaFighting;
  89498. }
  89499. if (gazer._gazeTracker.position.y < 0) {
  89500. gazer._gazeTracker.position.y += deltaFighting;
  89501. }
  89502. else {
  89503. gazer._gazeTracker.position.y -= deltaFighting;
  89504. }
  89505. if (gazer._gazeTracker.position.z < 0) {
  89506. gazer._gazeTracker.position.z += deltaFighting;
  89507. }
  89508. else {
  89509. gazer._gazeTracker.position.z -= deltaFighting;
  89510. }
  89511. }
  89512. // Changing the size of the laser pointer based on the distance from the targetted point
  89513. gazer._updatePointerDistance(hit.distance);
  89514. }
  89515. else {
  89516. gazer._updatePointerDistance();
  89517. gazer._gazeTracker.isVisible = false;
  89518. }
  89519. if (hit && hit.pickedMesh) {
  89520. // The object selected is the floor, we're in a teleportation scenario
  89521. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  89522. // Moving the teleportation area to this targetted point
  89523. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  89524. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  89525. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89526. }
  89527. gazer._currentMeshSelected = null;
  89528. if (gazer._teleportationRequestInitiated) {
  89529. this._moveTeleportationSelectorTo(hit, gazer, ray);
  89530. }
  89531. return;
  89532. }
  89533. // If not, we're in a selection scenario
  89534. //this._teleportationAllowed = false;
  89535. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  89536. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  89537. this.onNewMeshPicked.notifyObservers(hit);
  89538. gazer._currentMeshSelected = hit.pickedMesh;
  89539. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  89540. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  89541. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  89542. gazer._isActionableMesh = true;
  89543. }
  89544. else {
  89545. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89546. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89547. gazer._isActionableMesh = false;
  89548. }
  89549. try {
  89550. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  89551. }
  89552. catch (err) {
  89553. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  89554. }
  89555. }
  89556. else {
  89557. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89558. gazer._currentMeshSelected = null;
  89559. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89560. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89561. }
  89562. }
  89563. }
  89564. else {
  89565. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89566. gazer._currentMeshSelected = null;
  89567. //this._teleportationAllowed = false;
  89568. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89569. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89570. }
  89571. };
  89572. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  89573. if (mesh) {
  89574. this.onSelectedMeshUnselected.notifyObservers(mesh);
  89575. }
  89576. };
  89577. /**
  89578. * Sets the color of the laser ray from the vr controllers.
  89579. * @param color new color for the ray.
  89580. */
  89581. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  89582. if (this.leftController) {
  89583. this.leftController._setLaserPointerColor(color);
  89584. }
  89585. if (this.rightController) {
  89586. this.rightController._setLaserPointerColor(color);
  89587. }
  89588. };
  89589. /**
  89590. * Sets the color of the ray from the vr headsets gaze.
  89591. * @param color new color for the ray.
  89592. */
  89593. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  89594. if (!this._cameraGazer._gazeTracker.material) {
  89595. return;
  89596. }
  89597. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  89598. if (this.leftController) {
  89599. this.leftController._gazeTracker.material.emissiveColor = color;
  89600. }
  89601. if (this.rightController) {
  89602. this.rightController._gazeTracker.material.emissiveColor = color;
  89603. }
  89604. };
  89605. /**
  89606. * Exits VR and disposes of the vr experience helper
  89607. */
  89608. VRExperienceHelper.prototype.dispose = function () {
  89609. if (this.isInVRMode) {
  89610. this.exitVR();
  89611. }
  89612. if (this._postProcessMove) {
  89613. this._postProcessMove.dispose();
  89614. }
  89615. if (this._webVRCamera) {
  89616. this._webVRCamera.dispose();
  89617. }
  89618. if (this._vrDeviceOrientationCamera) {
  89619. this._vrDeviceOrientationCamera.dispose();
  89620. }
  89621. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  89622. document.body.removeChild(this._btnVR);
  89623. }
  89624. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  89625. this._deviceOrientationCamera.dispose();
  89626. }
  89627. if (this._cameraGazer) {
  89628. this._cameraGazer.dispose();
  89629. }
  89630. if (this.leftController) {
  89631. this.leftController.dispose();
  89632. }
  89633. if (this.rightController) {
  89634. this.rightController.dispose();
  89635. }
  89636. if (this._teleportationTarget) {
  89637. this._teleportationTarget.dispose();
  89638. }
  89639. this._floorMeshesCollection = [];
  89640. document.removeEventListener("keydown", this._onKeyDown);
  89641. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  89642. window.removeEventListener("resize", this._onResize);
  89643. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  89644. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  89645. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  89646. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  89647. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  89648. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  89649. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  89650. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  89651. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  89652. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  89653. this._scene.unregisterBeforeRender(this.beforeRender);
  89654. };
  89655. /**
  89656. * Gets the name of the VRExperienceHelper class
  89657. * @returns "VRExperienceHelper"
  89658. */
  89659. VRExperienceHelper.prototype.getClassName = function () {
  89660. return "VRExperienceHelper";
  89661. };
  89662. return VRExperienceHelper;
  89663. }());
  89664. BABYLON.VRExperienceHelper = VRExperienceHelper;
  89665. })(BABYLON || (BABYLON = {}));
  89666. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  89667. // Mainly based on these 2 articles :
  89668. // 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
  89669. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  89670. var BABYLON;
  89671. (function (BABYLON) {
  89672. /**
  89673. * Defines the potential axis of a Joystick
  89674. */
  89675. var JoystickAxis;
  89676. (function (JoystickAxis) {
  89677. /** X axis */
  89678. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  89679. /** Y axis */
  89680. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  89681. /** Z axis */
  89682. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  89683. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  89684. /**
  89685. * Class used to define virtual joystick (used in touch mode)
  89686. */
  89687. var VirtualJoystick = /** @class */ (function () {
  89688. /**
  89689. * Creates a new virtual joystick
  89690. * @param leftJoystick defines that the joystick is for left hand (false by default)
  89691. */
  89692. function VirtualJoystick(leftJoystick) {
  89693. var _this = this;
  89694. if (leftJoystick) {
  89695. this._leftJoystick = true;
  89696. }
  89697. else {
  89698. this._leftJoystick = false;
  89699. }
  89700. VirtualJoystick._globalJoystickIndex++;
  89701. // By default left & right arrow keys are moving the X
  89702. // and up & down keys are moving the Y
  89703. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89704. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89705. this.reverseLeftRight = false;
  89706. this.reverseUpDown = false;
  89707. // collections of pointers
  89708. this._touches = new BABYLON.StringDictionary();
  89709. this.deltaPosition = BABYLON.Vector3.Zero();
  89710. this._joystickSensibility = 25;
  89711. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89712. this._onResize = function (evt) {
  89713. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89714. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89715. if (VirtualJoystick.vjCanvas) {
  89716. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  89717. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  89718. }
  89719. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  89720. };
  89721. // injecting a canvas element on top of the canvas 3D game
  89722. if (!VirtualJoystick.vjCanvas) {
  89723. window.addEventListener("resize", this._onResize, false);
  89724. VirtualJoystick.vjCanvas = document.createElement("canvas");
  89725. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89726. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89727. VirtualJoystick.vjCanvas.width = window.innerWidth;
  89728. VirtualJoystick.vjCanvas.height = window.innerHeight;
  89729. VirtualJoystick.vjCanvas.style.width = "100%";
  89730. VirtualJoystick.vjCanvas.style.height = "100%";
  89731. VirtualJoystick.vjCanvas.style.position = "absolute";
  89732. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  89733. VirtualJoystick.vjCanvas.style.top = "0px";
  89734. VirtualJoystick.vjCanvas.style.left = "0px";
  89735. VirtualJoystick.vjCanvas.style.zIndex = "5";
  89736. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  89737. // Support for jQuery PEP polyfill
  89738. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  89739. var context = VirtualJoystick.vjCanvas.getContext('2d');
  89740. if (!context) {
  89741. throw new Error("Unable to create canvas for virtual joystick");
  89742. }
  89743. VirtualJoystick.vjCanvasContext = context;
  89744. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  89745. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89746. document.body.appendChild(VirtualJoystick.vjCanvas);
  89747. }
  89748. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  89749. this.pressed = false;
  89750. // default joystick color
  89751. this._joystickColor = "cyan";
  89752. this._joystickPointerID = -1;
  89753. // current joystick position
  89754. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  89755. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  89756. // origin joystick position
  89757. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  89758. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  89759. this._onPointerDownHandlerRef = function (evt) {
  89760. _this._onPointerDown(evt);
  89761. };
  89762. this._onPointerMoveHandlerRef = function (evt) {
  89763. _this._onPointerMove(evt);
  89764. };
  89765. this._onPointerUpHandlerRef = function (evt) {
  89766. _this._onPointerUp(evt);
  89767. };
  89768. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  89769. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  89770. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  89771. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  89772. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  89773. evt.preventDefault(); // Disables system menu
  89774. }, false);
  89775. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89776. }
  89777. /**
  89778. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  89779. * @param newJoystickSensibility defines the new sensibility
  89780. */
  89781. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  89782. this._joystickSensibility = newJoystickSensibility;
  89783. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89784. };
  89785. VirtualJoystick.prototype._onPointerDown = function (e) {
  89786. var positionOnScreenCondition;
  89787. e.preventDefault();
  89788. if (this._leftJoystick === true) {
  89789. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  89790. }
  89791. else {
  89792. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  89793. }
  89794. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  89795. // First contact will be dedicated to the virtual joystick
  89796. this._joystickPointerID = e.pointerId;
  89797. this._joystickPointerStartPos.x = e.clientX;
  89798. this._joystickPointerStartPos.y = e.clientY;
  89799. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  89800. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  89801. this._deltaJoystickVector.x = 0;
  89802. this._deltaJoystickVector.y = 0;
  89803. this.pressed = true;
  89804. this._touches.add(e.pointerId.toString(), e);
  89805. }
  89806. else {
  89807. // You can only trigger the action buttons with a joystick declared
  89808. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  89809. this._action();
  89810. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  89811. }
  89812. }
  89813. };
  89814. VirtualJoystick.prototype._onPointerMove = function (e) {
  89815. // If the current pointer is the one associated to the joystick (first touch contact)
  89816. if (this._joystickPointerID == e.pointerId) {
  89817. this._joystickPointerPos.x = e.clientX;
  89818. this._joystickPointerPos.y = e.clientY;
  89819. this._deltaJoystickVector = this._joystickPointerPos.clone();
  89820. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  89821. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  89822. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  89823. switch (this._axisTargetedByLeftAndRight) {
  89824. case JoystickAxis.X:
  89825. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  89826. break;
  89827. case JoystickAxis.Y:
  89828. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  89829. break;
  89830. case JoystickAxis.Z:
  89831. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  89832. break;
  89833. }
  89834. var directionUpDown = this.reverseUpDown ? 1 : -1;
  89835. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  89836. switch (this._axisTargetedByUpAndDown) {
  89837. case JoystickAxis.X:
  89838. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  89839. break;
  89840. case JoystickAxis.Y:
  89841. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  89842. break;
  89843. case JoystickAxis.Z:
  89844. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  89845. break;
  89846. }
  89847. }
  89848. else {
  89849. var data = this._touches.get(e.pointerId.toString());
  89850. if (data) {
  89851. data.x = e.clientX;
  89852. data.y = e.clientY;
  89853. }
  89854. }
  89855. };
  89856. VirtualJoystick.prototype._onPointerUp = function (e) {
  89857. if (this._joystickPointerID == e.pointerId) {
  89858. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  89859. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  89860. this._joystickPointerID = -1;
  89861. this.pressed = false;
  89862. }
  89863. else {
  89864. var touch = this._touches.get(e.pointerId.toString());
  89865. if (touch) {
  89866. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89867. }
  89868. }
  89869. this._deltaJoystickVector.x = 0;
  89870. this._deltaJoystickVector.y = 0;
  89871. this._touches.remove(e.pointerId.toString());
  89872. };
  89873. /**
  89874. * Change the color of the virtual joystick
  89875. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  89876. */
  89877. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  89878. this._joystickColor = newColor;
  89879. };
  89880. /**
  89881. * Defines a callback to call when the joystick is touched
  89882. * @param action defines the callback
  89883. */
  89884. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  89885. this._action = action;
  89886. };
  89887. /**
  89888. * Defines which axis you'd like to control for left & right
  89889. * @param axis defines the axis to use
  89890. */
  89891. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  89892. switch (axis) {
  89893. case JoystickAxis.X:
  89894. case JoystickAxis.Y:
  89895. case JoystickAxis.Z:
  89896. this._axisTargetedByLeftAndRight = axis;
  89897. break;
  89898. default:
  89899. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89900. break;
  89901. }
  89902. };
  89903. /**
  89904. * Defines which axis you'd like to control for up & down
  89905. * @param axis defines the axis to use
  89906. */
  89907. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  89908. switch (axis) {
  89909. case JoystickAxis.X:
  89910. case JoystickAxis.Y:
  89911. case JoystickAxis.Z:
  89912. this._axisTargetedByUpAndDown = axis;
  89913. break;
  89914. default:
  89915. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89916. break;
  89917. }
  89918. };
  89919. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  89920. var _this = this;
  89921. if (this.pressed) {
  89922. this._touches.forEach(function (key, touch) {
  89923. if (touch.pointerId === _this._joystickPointerID) {
  89924. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  89925. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  89926. VirtualJoystick.vjCanvasContext.beginPath();
  89927. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89928. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89929. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  89930. VirtualJoystick.vjCanvasContext.stroke();
  89931. VirtualJoystick.vjCanvasContext.closePath();
  89932. VirtualJoystick.vjCanvasContext.beginPath();
  89933. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89934. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89935. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  89936. VirtualJoystick.vjCanvasContext.stroke();
  89937. VirtualJoystick.vjCanvasContext.closePath();
  89938. VirtualJoystick.vjCanvasContext.beginPath();
  89939. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89940. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  89941. VirtualJoystick.vjCanvasContext.stroke();
  89942. VirtualJoystick.vjCanvasContext.closePath();
  89943. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  89944. }
  89945. else {
  89946. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89947. VirtualJoystick.vjCanvasContext.beginPath();
  89948. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  89949. VirtualJoystick.vjCanvasContext.beginPath();
  89950. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  89951. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89952. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  89953. VirtualJoystick.vjCanvasContext.stroke();
  89954. VirtualJoystick.vjCanvasContext.closePath();
  89955. touch.prevX = touch.x;
  89956. touch.prevY = touch.y;
  89957. }
  89958. ;
  89959. });
  89960. }
  89961. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89962. };
  89963. /**
  89964. * Release internal HTML canvas
  89965. */
  89966. VirtualJoystick.prototype.releaseCanvas = function () {
  89967. if (VirtualJoystick.vjCanvas) {
  89968. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  89969. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  89970. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  89971. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  89972. window.removeEventListener("resize", this._onResize);
  89973. document.body.removeChild(VirtualJoystick.vjCanvas);
  89974. VirtualJoystick.vjCanvas = null;
  89975. }
  89976. };
  89977. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  89978. VirtualJoystick._globalJoystickIndex = 0;
  89979. return VirtualJoystick;
  89980. }());
  89981. BABYLON.VirtualJoystick = VirtualJoystick;
  89982. })(BABYLON || (BABYLON = {}));
  89983. //# sourceMappingURL=babylon.virtualJoystick.js.map
  89984. var BABYLON;
  89985. (function (BABYLON) {
  89986. // We're mainly based on the logic defined into the FreeCamera code
  89987. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  89988. __extends(VirtualJoysticksCamera, _super);
  89989. function VirtualJoysticksCamera(name, position, scene) {
  89990. var _this = _super.call(this, name, position, scene) || this;
  89991. _this.inputs.addVirtualJoystick();
  89992. return _this;
  89993. }
  89994. VirtualJoysticksCamera.prototype.getClassName = function () {
  89995. return "VirtualJoysticksCamera";
  89996. };
  89997. return VirtualJoysticksCamera;
  89998. }(BABYLON.FreeCamera));
  89999. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  90000. })(BABYLON || (BABYLON = {}));
  90001. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  90002. var BABYLON;
  90003. (function (BABYLON) {
  90004. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  90005. function FreeCameraVirtualJoystickInput() {
  90006. }
  90007. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  90008. return this._leftjoystick;
  90009. };
  90010. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  90011. return this._rightjoystick;
  90012. };
  90013. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  90014. if (this._leftjoystick) {
  90015. var camera = this.camera;
  90016. var speed = camera._computeLocalCameraSpeed() * 50;
  90017. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  90018. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  90019. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  90020. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  90021. if (!this._leftjoystick.pressed) {
  90022. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  90023. }
  90024. if (!this._rightjoystick.pressed) {
  90025. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  90026. }
  90027. }
  90028. };
  90029. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  90030. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  90031. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  90032. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  90033. this._leftjoystick.setJoystickSensibility(0.15);
  90034. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  90035. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  90036. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  90037. this._rightjoystick.reverseUpDown = true;
  90038. this._rightjoystick.setJoystickSensibility(0.05);
  90039. this._rightjoystick.setJoystickColor("yellow");
  90040. };
  90041. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  90042. this._leftjoystick.releaseCanvas();
  90043. this._rightjoystick.releaseCanvas();
  90044. };
  90045. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  90046. return "FreeCameraVirtualJoystickInput";
  90047. };
  90048. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  90049. return "virtualJoystick";
  90050. };
  90051. return FreeCameraVirtualJoystickInput;
  90052. }());
  90053. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  90054. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  90055. })(BABYLON || (BABYLON = {}));
  90056. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  90057. var BABYLON;
  90058. (function (BABYLON) {
  90059. var SimplificationSettings = /** @class */ (function () {
  90060. function SimplificationSettings(quality, distance, optimizeMesh) {
  90061. this.quality = quality;
  90062. this.distance = distance;
  90063. this.optimizeMesh = optimizeMesh;
  90064. }
  90065. return SimplificationSettings;
  90066. }());
  90067. BABYLON.SimplificationSettings = SimplificationSettings;
  90068. var SimplificationQueue = /** @class */ (function () {
  90069. function SimplificationQueue() {
  90070. this.running = false;
  90071. this._simplificationArray = [];
  90072. }
  90073. SimplificationQueue.prototype.addTask = function (task) {
  90074. this._simplificationArray.push(task);
  90075. };
  90076. SimplificationQueue.prototype.executeNext = function () {
  90077. var task = this._simplificationArray.pop();
  90078. if (task) {
  90079. this.running = true;
  90080. this.runSimplification(task);
  90081. }
  90082. else {
  90083. this.running = false;
  90084. }
  90085. };
  90086. SimplificationQueue.prototype.runSimplification = function (task) {
  90087. var _this = this;
  90088. if (task.parallelProcessing) {
  90089. //parallel simplifier
  90090. task.settings.forEach(function (setting) {
  90091. var simplifier = _this.getSimplifier(task);
  90092. simplifier.simplify(setting, function (newMesh) {
  90093. task.mesh.addLODLevel(setting.distance, newMesh);
  90094. newMesh.isVisible = true;
  90095. //check if it is the last
  90096. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  90097. //all done, run the success callback.
  90098. task.successCallback();
  90099. }
  90100. _this.executeNext();
  90101. });
  90102. });
  90103. }
  90104. else {
  90105. //single simplifier.
  90106. var simplifier = this.getSimplifier(task);
  90107. var runDecimation = function (setting, callback) {
  90108. simplifier.simplify(setting, function (newMesh) {
  90109. task.mesh.addLODLevel(setting.distance, newMesh);
  90110. newMesh.isVisible = true;
  90111. //run the next quality level
  90112. callback();
  90113. });
  90114. };
  90115. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  90116. runDecimation(task.settings[loop.index], function () {
  90117. loop.executeNext();
  90118. });
  90119. }, function () {
  90120. //execution ended, run the success callback.
  90121. if (task.successCallback) {
  90122. task.successCallback();
  90123. }
  90124. _this.executeNext();
  90125. });
  90126. }
  90127. };
  90128. SimplificationQueue.prototype.getSimplifier = function (task) {
  90129. switch (task.simplificationType) {
  90130. case SimplificationType.QUADRATIC:
  90131. default:
  90132. return new QuadraticErrorSimplification(task.mesh);
  90133. }
  90134. };
  90135. return SimplificationQueue;
  90136. }());
  90137. BABYLON.SimplificationQueue = SimplificationQueue;
  90138. /**
  90139. * The implemented types of simplification
  90140. * At the moment only Quadratic Error Decimation is implemented
  90141. */
  90142. var SimplificationType;
  90143. (function (SimplificationType) {
  90144. /** Quadratic error decimation */
  90145. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  90146. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  90147. var DecimationTriangle = /** @class */ (function () {
  90148. function DecimationTriangle(vertices) {
  90149. this.vertices = vertices;
  90150. this.error = new Array(4);
  90151. this.deleted = false;
  90152. this.isDirty = false;
  90153. this.deletePending = false;
  90154. this.borderFactor = 0;
  90155. }
  90156. return DecimationTriangle;
  90157. }());
  90158. BABYLON.DecimationTriangle = DecimationTriangle;
  90159. var DecimationVertex = /** @class */ (function () {
  90160. function DecimationVertex(position, id) {
  90161. this.position = position;
  90162. this.id = id;
  90163. this.isBorder = true;
  90164. this.q = new QuadraticMatrix();
  90165. this.triangleCount = 0;
  90166. this.triangleStart = 0;
  90167. this.originalOffsets = [];
  90168. }
  90169. DecimationVertex.prototype.updatePosition = function (newPosition) {
  90170. this.position.copyFrom(newPosition);
  90171. };
  90172. return DecimationVertex;
  90173. }());
  90174. BABYLON.DecimationVertex = DecimationVertex;
  90175. var QuadraticMatrix = /** @class */ (function () {
  90176. function QuadraticMatrix(data) {
  90177. this.data = new Array(10);
  90178. for (var i = 0; i < 10; ++i) {
  90179. if (data && data[i]) {
  90180. this.data[i] = data[i];
  90181. }
  90182. else {
  90183. this.data[i] = 0;
  90184. }
  90185. }
  90186. }
  90187. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  90188. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  90189. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  90190. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  90191. return det;
  90192. };
  90193. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  90194. for (var i = 0; i < 10; ++i) {
  90195. this.data[i] += matrix.data[i];
  90196. }
  90197. };
  90198. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  90199. for (var i = 0; i < 10; ++i) {
  90200. this.data[i] += data[i];
  90201. }
  90202. };
  90203. QuadraticMatrix.prototype.add = function (matrix) {
  90204. var m = new QuadraticMatrix();
  90205. for (var i = 0; i < 10; ++i) {
  90206. m.data[i] = this.data[i] + matrix.data[i];
  90207. }
  90208. return m;
  90209. };
  90210. QuadraticMatrix.FromData = function (a, b, c, d) {
  90211. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  90212. };
  90213. //returning an array to avoid garbage collection
  90214. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  90215. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  90216. };
  90217. return QuadraticMatrix;
  90218. }());
  90219. BABYLON.QuadraticMatrix = QuadraticMatrix;
  90220. var Reference = /** @class */ (function () {
  90221. function Reference(vertexId, triangleId) {
  90222. this.vertexId = vertexId;
  90223. this.triangleId = triangleId;
  90224. }
  90225. return Reference;
  90226. }());
  90227. BABYLON.Reference = Reference;
  90228. /**
  90229. * An implementation of the Quadratic Error simplification algorithm.
  90230. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  90231. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  90232. * @author RaananW
  90233. */
  90234. var QuadraticErrorSimplification = /** @class */ (function () {
  90235. function QuadraticErrorSimplification(_mesh) {
  90236. this._mesh = _mesh;
  90237. this.syncIterations = 5000;
  90238. this.aggressiveness = 7;
  90239. this.decimationIterations = 100;
  90240. this.boundingBoxEpsilon = BABYLON.Epsilon;
  90241. }
  90242. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  90243. var _this = this;
  90244. this.initDecimatedMesh();
  90245. //iterating through the submeshes array, one after the other.
  90246. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  90247. _this.initWithMesh(loop.index, function () {
  90248. _this.runDecimation(settings, loop.index, function () {
  90249. loop.executeNext();
  90250. });
  90251. }, settings.optimizeMesh);
  90252. }, function () {
  90253. setTimeout(function () {
  90254. successCallback(_this._reconstructedMesh);
  90255. }, 0);
  90256. });
  90257. };
  90258. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  90259. var _this = this;
  90260. var targetCount = ~~(this.triangles.length * settings.quality);
  90261. var deletedTriangles = 0;
  90262. var triangleCount = this.triangles.length;
  90263. var iterationFunction = function (iteration, callback) {
  90264. setTimeout(function () {
  90265. if (iteration % 5 === 0) {
  90266. _this.updateMesh(iteration === 0);
  90267. }
  90268. for (var i = 0; i < _this.triangles.length; ++i) {
  90269. _this.triangles[i].isDirty = false;
  90270. }
  90271. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  90272. var trianglesIterator = function (i) {
  90273. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  90274. var t = _this.triangles[tIdx];
  90275. if (!t)
  90276. return;
  90277. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  90278. return;
  90279. }
  90280. for (var j = 0; j < 3; ++j) {
  90281. if (t.error[j] < threshold) {
  90282. var deleted0 = [];
  90283. var deleted1 = [];
  90284. var v0 = t.vertices[j];
  90285. var v1 = t.vertices[(j + 1) % 3];
  90286. if (v0.isBorder || v1.isBorder)
  90287. continue;
  90288. var p = BABYLON.Vector3.Zero();
  90289. var n = BABYLON.Vector3.Zero();
  90290. var uv = BABYLON.Vector2.Zero();
  90291. var color = new BABYLON.Color4(0, 0, 0, 1);
  90292. _this.calculateError(v0, v1, p, n, uv, color);
  90293. var delTr = new Array();
  90294. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  90295. continue;
  90296. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  90297. continue;
  90298. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  90299. continue;
  90300. var uniqueArray = new Array();
  90301. delTr.forEach(function (deletedT) {
  90302. if (uniqueArray.indexOf(deletedT) === -1) {
  90303. deletedT.deletePending = true;
  90304. uniqueArray.push(deletedT);
  90305. }
  90306. });
  90307. if (uniqueArray.length % 2 !== 0) {
  90308. continue;
  90309. }
  90310. v0.q = v1.q.add(v0.q);
  90311. v0.updatePosition(p);
  90312. var tStart = _this.references.length;
  90313. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  90314. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  90315. var tCount = _this.references.length - tStart;
  90316. if (tCount <= v0.triangleCount) {
  90317. if (tCount) {
  90318. for (var c = 0; c < tCount; c++) {
  90319. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  90320. }
  90321. }
  90322. }
  90323. else {
  90324. v0.triangleStart = tStart;
  90325. }
  90326. v0.triangleCount = tCount;
  90327. break;
  90328. }
  90329. }
  90330. };
  90331. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  90332. }, 0);
  90333. };
  90334. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  90335. if (triangleCount - deletedTriangles <= targetCount)
  90336. loop.breakLoop();
  90337. else {
  90338. iterationFunction(loop.index, function () {
  90339. loop.executeNext();
  90340. });
  90341. }
  90342. }, function () {
  90343. setTimeout(function () {
  90344. //reconstruct this part of the mesh
  90345. _this.reconstructMesh(submeshIndex);
  90346. successCallback();
  90347. }, 0);
  90348. });
  90349. };
  90350. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  90351. var _this = this;
  90352. this.vertices = [];
  90353. this.triangles = [];
  90354. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  90355. var indices = this._mesh.getIndices();
  90356. var submesh = this._mesh.subMeshes[submeshIndex];
  90357. var findInVertices = function (positionToSearch) {
  90358. if (optimizeMesh) {
  90359. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  90360. if (_this.vertices[ii].position.equals(positionToSearch)) {
  90361. return _this.vertices[ii];
  90362. }
  90363. }
  90364. }
  90365. return null;
  90366. };
  90367. var vertexReferences = [];
  90368. var vertexInit = function (i) {
  90369. if (!positionData) {
  90370. return;
  90371. }
  90372. var offset = i + submesh.verticesStart;
  90373. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  90374. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  90375. vertex.originalOffsets.push(offset);
  90376. if (vertex.id === _this.vertices.length) {
  90377. _this.vertices.push(vertex);
  90378. }
  90379. vertexReferences.push(vertex.id);
  90380. };
  90381. //var totalVertices = mesh.getTotalVertices();
  90382. var totalVertices = submesh.verticesCount;
  90383. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  90384. var indicesInit = function (i) {
  90385. if (!indices) {
  90386. return;
  90387. }
  90388. var offset = (submesh.indexStart / 3) + i;
  90389. var pos = (offset * 3);
  90390. var i0 = indices[pos + 0];
  90391. var i1 = indices[pos + 1];
  90392. var i2 = indices[pos + 2];
  90393. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  90394. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  90395. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  90396. var triangle = new DecimationTriangle([v0, v1, v2]);
  90397. triangle.originalOffset = pos;
  90398. _this.triangles.push(triangle);
  90399. };
  90400. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  90401. _this.init(callback);
  90402. });
  90403. });
  90404. };
  90405. QuadraticErrorSimplification.prototype.init = function (callback) {
  90406. var _this = this;
  90407. var triangleInit1 = function (i) {
  90408. var t = _this.triangles[i];
  90409. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  90410. for (var j = 0; j < 3; j++) {
  90411. 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))));
  90412. }
  90413. };
  90414. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  90415. var triangleInit2 = function (i) {
  90416. var t = _this.triangles[i];
  90417. for (var j = 0; j < 3; ++j) {
  90418. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  90419. }
  90420. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  90421. };
  90422. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  90423. callback();
  90424. });
  90425. });
  90426. };
  90427. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  90428. var newTriangles = [];
  90429. var i;
  90430. for (i = 0; i < this.vertices.length; ++i) {
  90431. this.vertices[i].triangleCount = 0;
  90432. }
  90433. var t;
  90434. var j;
  90435. for (i = 0; i < this.triangles.length; ++i) {
  90436. if (!this.triangles[i].deleted) {
  90437. t = this.triangles[i];
  90438. for (j = 0; j < 3; ++j) {
  90439. t.vertices[j].triangleCount = 1;
  90440. }
  90441. newTriangles.push(t);
  90442. }
  90443. }
  90444. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  90445. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  90446. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  90447. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  90448. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  90449. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  90450. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  90451. var vertexCount = 0;
  90452. for (i = 0; i < this.vertices.length; ++i) {
  90453. var vertex = this.vertices[i];
  90454. vertex.id = vertexCount;
  90455. if (vertex.triangleCount) {
  90456. vertex.originalOffsets.forEach(function (originalOffset) {
  90457. if (!normalData) {
  90458. return;
  90459. }
  90460. newPositionData.push(vertex.position.x);
  90461. newPositionData.push(vertex.position.y);
  90462. newPositionData.push(vertex.position.z);
  90463. newNormalData.push(normalData[originalOffset * 3]);
  90464. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  90465. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  90466. if (uvs && uvs.length) {
  90467. newUVsData.push(uvs[(originalOffset * 2)]);
  90468. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  90469. }
  90470. else if (colorsData && colorsData.length) {
  90471. newColorsData.push(colorsData[(originalOffset * 4)]);
  90472. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  90473. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  90474. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  90475. }
  90476. ++vertexCount;
  90477. });
  90478. }
  90479. }
  90480. var startingIndex = this._reconstructedMesh.getTotalIndices();
  90481. var startingVertex = this._reconstructedMesh.getTotalVertices();
  90482. var submeshesArray = this._reconstructedMesh.subMeshes;
  90483. this._reconstructedMesh.subMeshes = [];
  90484. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  90485. var originalIndices = this._mesh.getIndices();
  90486. for (i = 0; i < newTriangles.length; ++i) {
  90487. t = newTriangles[i]; //now get the new referencing point for each vertex
  90488. [0, 1, 2].forEach(function (idx) {
  90489. var id = originalIndices[t.originalOffset + idx];
  90490. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  90491. if (offset < 0)
  90492. offset = 0;
  90493. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  90494. });
  90495. }
  90496. //overwriting the old vertex buffers and indices.
  90497. this._reconstructedMesh.setIndices(newIndicesArray);
  90498. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  90499. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  90500. if (newUVsData.length > 0)
  90501. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  90502. if (newColorsData.length > 0)
  90503. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  90504. //create submesh
  90505. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  90506. if (submeshIndex > 0) {
  90507. this._reconstructedMesh.subMeshes = [];
  90508. submeshesArray.forEach(function (submesh) {
  90509. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  90510. });
  90511. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  90512. }
  90513. };
  90514. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  90515. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  90516. this._reconstructedMesh.material = this._mesh.material;
  90517. this._reconstructedMesh.parent = this._mesh.parent;
  90518. this._reconstructedMesh.isVisible = false;
  90519. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  90520. };
  90521. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  90522. for (var i = 0; i < vertex1.triangleCount; ++i) {
  90523. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  90524. if (t.deleted)
  90525. continue;
  90526. var s = this.references[vertex1.triangleStart + i].vertexId;
  90527. var v1 = t.vertices[(s + 1) % 3];
  90528. var v2 = t.vertices[(s + 2) % 3];
  90529. if ((v1 === vertex2 || v2 === vertex2)) {
  90530. deletedArray[i] = true;
  90531. delTr.push(t);
  90532. continue;
  90533. }
  90534. var d1 = v1.position.subtract(point);
  90535. d1 = d1.normalize();
  90536. var d2 = v2.position.subtract(point);
  90537. d2 = d2.normalize();
  90538. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  90539. return true;
  90540. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  90541. deletedArray[i] = false;
  90542. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  90543. return true;
  90544. }
  90545. return false;
  90546. };
  90547. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  90548. var newDeleted = deletedTriangles;
  90549. for (var i = 0; i < vertex.triangleCount; ++i) {
  90550. var ref = this.references[vertex.triangleStart + i];
  90551. var t = this.triangles[ref.triangleId];
  90552. if (t.deleted)
  90553. continue;
  90554. if (deletedArray[i] && t.deletePending) {
  90555. t.deleted = true;
  90556. newDeleted++;
  90557. continue;
  90558. }
  90559. t.vertices[ref.vertexId] = origVertex;
  90560. t.isDirty = true;
  90561. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  90562. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  90563. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  90564. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  90565. this.references.push(ref);
  90566. }
  90567. return newDeleted;
  90568. };
  90569. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  90570. for (var i = 0; i < this.vertices.length; ++i) {
  90571. var vCount = [];
  90572. var vId = [];
  90573. var v = this.vertices[i];
  90574. var j;
  90575. for (j = 0; j < v.triangleCount; ++j) {
  90576. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  90577. for (var ii = 0; ii < 3; ii++) {
  90578. var ofs = 0;
  90579. var vv = triangle.vertices[ii];
  90580. while (ofs < vCount.length) {
  90581. if (vId[ofs] === vv.id)
  90582. break;
  90583. ++ofs;
  90584. }
  90585. if (ofs === vCount.length) {
  90586. vCount.push(1);
  90587. vId.push(vv.id);
  90588. }
  90589. else {
  90590. vCount[ofs]++;
  90591. }
  90592. }
  90593. }
  90594. for (j = 0; j < vCount.length; ++j) {
  90595. if (vCount[j] === 1) {
  90596. this.vertices[vId[j]].isBorder = true;
  90597. }
  90598. else {
  90599. this.vertices[vId[j]].isBorder = false;
  90600. }
  90601. }
  90602. }
  90603. };
  90604. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  90605. if (identifyBorders === void 0) { identifyBorders = false; }
  90606. var i;
  90607. if (!identifyBorders) {
  90608. var newTrianglesVector = [];
  90609. for (i = 0; i < this.triangles.length; ++i) {
  90610. if (!this.triangles[i].deleted) {
  90611. newTrianglesVector.push(this.triangles[i]);
  90612. }
  90613. }
  90614. this.triangles = newTrianglesVector;
  90615. }
  90616. for (i = 0; i < this.vertices.length; ++i) {
  90617. this.vertices[i].triangleCount = 0;
  90618. this.vertices[i].triangleStart = 0;
  90619. }
  90620. var t;
  90621. var j;
  90622. var v;
  90623. for (i = 0; i < this.triangles.length; ++i) {
  90624. t = this.triangles[i];
  90625. for (j = 0; j < 3; ++j) {
  90626. v = t.vertices[j];
  90627. v.triangleCount++;
  90628. }
  90629. }
  90630. var tStart = 0;
  90631. for (i = 0; i < this.vertices.length; ++i) {
  90632. this.vertices[i].triangleStart = tStart;
  90633. tStart += this.vertices[i].triangleCount;
  90634. this.vertices[i].triangleCount = 0;
  90635. }
  90636. var newReferences = new Array(this.triangles.length * 3);
  90637. for (i = 0; i < this.triangles.length; ++i) {
  90638. t = this.triangles[i];
  90639. for (j = 0; j < 3; ++j) {
  90640. v = t.vertices[j];
  90641. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  90642. v.triangleCount++;
  90643. }
  90644. }
  90645. this.references = newReferences;
  90646. if (identifyBorders) {
  90647. this.identifyBorder();
  90648. }
  90649. };
  90650. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  90651. var x = point.x;
  90652. var y = point.y;
  90653. var z = point.z;
  90654. 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
  90655. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  90656. };
  90657. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  90658. var q = vertex1.q.add(vertex2.q);
  90659. var border = vertex1.isBorder && vertex2.isBorder;
  90660. var error = 0;
  90661. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  90662. if (qDet !== 0 && !border) {
  90663. if (!pointResult) {
  90664. pointResult = BABYLON.Vector3.Zero();
  90665. }
  90666. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  90667. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  90668. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  90669. error = this.vertexError(q, pointResult);
  90670. }
  90671. else {
  90672. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  90673. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  90674. var error1 = this.vertexError(q, vertex1.position);
  90675. var error2 = this.vertexError(q, vertex2.position);
  90676. var error3 = this.vertexError(q, p3);
  90677. error = Math.min(error1, error2, error3);
  90678. if (error === error1) {
  90679. if (pointResult) {
  90680. pointResult.copyFrom(vertex1.position);
  90681. }
  90682. }
  90683. else if (error === error2) {
  90684. if (pointResult) {
  90685. pointResult.copyFrom(vertex2.position);
  90686. }
  90687. }
  90688. else {
  90689. if (pointResult) {
  90690. pointResult.copyFrom(p3);
  90691. }
  90692. }
  90693. }
  90694. return error;
  90695. };
  90696. return QuadraticErrorSimplification;
  90697. }());
  90698. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  90699. })(BABYLON || (BABYLON = {}));
  90700. //# sourceMappingURL=babylon.meshSimplification.js.map
  90701. var BABYLON;
  90702. (function (BABYLON) {
  90703. var MeshLODLevel = /** @class */ (function () {
  90704. function MeshLODLevel(distance, mesh) {
  90705. this.distance = distance;
  90706. this.mesh = mesh;
  90707. }
  90708. return MeshLODLevel;
  90709. }());
  90710. BABYLON.MeshLODLevel = MeshLODLevel;
  90711. })(BABYLON || (BABYLON = {}));
  90712. //# sourceMappingURL=babylon.meshLODLevel.js.map
  90713. var BABYLON;
  90714. (function (BABYLON) {
  90715. /**
  90716. * Defines the root class used to create scene optimization to use with SceneOptimizer
  90717. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90718. */
  90719. var SceneOptimization = /** @class */ (function () {
  90720. /**
  90721. * Creates the SceneOptimization object
  90722. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90723. * @param desc defines the description associated with the optimization
  90724. */
  90725. function SceneOptimization(
  90726. /**
  90727. * Defines the priority of this optimization (0 by default which means first in the list)
  90728. */
  90729. priority) {
  90730. if (priority === void 0) { priority = 0; }
  90731. this.priority = priority;
  90732. }
  90733. /**
  90734. * Gets a string describing the action executed by the current optimization
  90735. * @returns description string
  90736. */
  90737. SceneOptimization.prototype.getDescription = function () {
  90738. return "";
  90739. };
  90740. /**
  90741. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90742. * @param scene defines the current scene where to apply this optimization
  90743. * @param optimizer defines the current optimizer
  90744. * @returns true if everything that can be done was applied
  90745. */
  90746. SceneOptimization.prototype.apply = function (scene, optimizer) {
  90747. return true;
  90748. };
  90749. ;
  90750. return SceneOptimization;
  90751. }());
  90752. BABYLON.SceneOptimization = SceneOptimization;
  90753. /**
  90754. * Defines an optimization used to reduce the size of render target textures
  90755. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90756. */
  90757. var TextureOptimization = /** @class */ (function (_super) {
  90758. __extends(TextureOptimization, _super);
  90759. /**
  90760. * Creates the TextureOptimization object
  90761. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90762. * @param maximumSize defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter
  90763. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90764. */
  90765. function TextureOptimization(
  90766. /**
  90767. * Defines the priority of this optimization (0 by default which means first in the list)
  90768. */
  90769. priority,
  90770. /**
  90771. * Defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter
  90772. */
  90773. maximumSize,
  90774. /**
  90775. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90776. */
  90777. step) {
  90778. if (priority === void 0) { priority = 0; }
  90779. if (maximumSize === void 0) { maximumSize = 1024; }
  90780. if (step === void 0) { step = 0.5; }
  90781. var _this = _super.call(this, priority) || this;
  90782. _this.priority = priority;
  90783. _this.maximumSize = maximumSize;
  90784. _this.step = step;
  90785. return _this;
  90786. }
  90787. /**
  90788. * Gets a string describing the action executed by the current optimization
  90789. * @returns description string
  90790. */
  90791. TextureOptimization.prototype.getDescription = function () {
  90792. return "Reducing render target texture size to " + this.maximumSize;
  90793. };
  90794. /**
  90795. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90796. * @param scene defines the current scene where to apply this optimization
  90797. * @param optimizer defines the current optimizer
  90798. * @returns true if everything that can be done was applied
  90799. */
  90800. TextureOptimization.prototype.apply = function (scene, optimizer) {
  90801. var allDone = true;
  90802. for (var index = 0; index < scene.textures.length; index++) {
  90803. var texture = scene.textures[index];
  90804. if (!texture.canRescale || texture.getContext) {
  90805. continue;
  90806. }
  90807. var currentSize = texture.getSize();
  90808. var maxDimension = Math.max(currentSize.width, currentSize.height);
  90809. if (maxDimension > this.maximumSize) {
  90810. texture.scale(this.step);
  90811. allDone = false;
  90812. }
  90813. }
  90814. return allDone;
  90815. };
  90816. return TextureOptimization;
  90817. }(SceneOptimization));
  90818. BABYLON.TextureOptimization = TextureOptimization;
  90819. /**
  90820. * Defines an optimization used to increase or decrease the rendering resolution
  90821. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90822. */
  90823. var HardwareScalingOptimization = /** @class */ (function (_super) {
  90824. __extends(HardwareScalingOptimization, _super);
  90825. /**
  90826. * Creates the HardwareScalingOptimization object
  90827. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90828. * @param maximumScale defines the maximum scale to use (2 by default)
  90829. * @param step defines the step to use between two passes (0.5 by default)
  90830. */
  90831. function HardwareScalingOptimization(
  90832. /**
  90833. * Defines the priority of this optimization (0 by default which means first in the list)
  90834. */
  90835. priority,
  90836. /**
  90837. * Defines the maximum scale to use (2 by default)
  90838. */
  90839. maximumScale,
  90840. /**
  90841. * Defines the step to use between two passes (0.5 by default)
  90842. */
  90843. step) {
  90844. if (priority === void 0) { priority = 0; }
  90845. if (maximumScale === void 0) { maximumScale = 2; }
  90846. if (step === void 0) { step = 0.25; }
  90847. var _this = _super.call(this, priority) || this;
  90848. _this.priority = priority;
  90849. _this.maximumScale = maximumScale;
  90850. _this.step = step;
  90851. _this._currentScale = -1;
  90852. _this._directionOffset = 1;
  90853. return _this;
  90854. }
  90855. /**
  90856. * Gets a string describing the action executed by the current optimization
  90857. * @return description string
  90858. */
  90859. HardwareScalingOptimization.prototype.getDescription = function () {
  90860. return "Setting hardware scaling level to " + this._currentScale;
  90861. };
  90862. /**
  90863. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90864. * @param scene defines the current scene where to apply this optimization
  90865. * @param optimizer defines the current optimizer
  90866. * @returns true if everything that can be done was applied
  90867. */
  90868. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  90869. if (this._currentScale === -1) {
  90870. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  90871. if (this._currentScale > this.maximumScale) {
  90872. this._directionOffset = -1;
  90873. }
  90874. }
  90875. this._currentScale += this._directionOffset * this.step;
  90876. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  90877. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  90878. };
  90879. ;
  90880. return HardwareScalingOptimization;
  90881. }(SceneOptimization));
  90882. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  90883. /**
  90884. * Defines an optimization used to remove shadows
  90885. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90886. */
  90887. var ShadowsOptimization = /** @class */ (function (_super) {
  90888. __extends(ShadowsOptimization, _super);
  90889. function ShadowsOptimization() {
  90890. return _super !== null && _super.apply(this, arguments) || this;
  90891. }
  90892. /**
  90893. * Gets a string describing the action executed by the current optimization
  90894. * @return description string
  90895. */
  90896. ShadowsOptimization.prototype.getDescription = function () {
  90897. return "Turning shadows on/off";
  90898. };
  90899. /**
  90900. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90901. * @param scene defines the current scene where to apply this optimization
  90902. * @param optimizer defines the current optimizer
  90903. * @returns true if everything that can be done was applied
  90904. */
  90905. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  90906. scene.shadowsEnabled = optimizer.isInImprovementMode;
  90907. return true;
  90908. };
  90909. ;
  90910. return ShadowsOptimization;
  90911. }(SceneOptimization));
  90912. BABYLON.ShadowsOptimization = ShadowsOptimization;
  90913. /**
  90914. * Defines an optimization used to turn post-processes off
  90915. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90916. */
  90917. var PostProcessesOptimization = /** @class */ (function (_super) {
  90918. __extends(PostProcessesOptimization, _super);
  90919. function PostProcessesOptimization() {
  90920. return _super !== null && _super.apply(this, arguments) || this;
  90921. }
  90922. /**
  90923. * Gets a string describing the action executed by the current optimization
  90924. * @return description string
  90925. */
  90926. PostProcessesOptimization.prototype.getDescription = function () {
  90927. return "Turning post-processes on/off";
  90928. };
  90929. /**
  90930. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90931. * @param scene defines the current scene where to apply this optimization
  90932. * @param optimizer defines the current optimizer
  90933. * @returns true if everything that can be done was applied
  90934. */
  90935. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  90936. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  90937. return true;
  90938. };
  90939. ;
  90940. return PostProcessesOptimization;
  90941. }(SceneOptimization));
  90942. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  90943. /**
  90944. * Defines an optimization used to turn lens flares off
  90945. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90946. */
  90947. var LensFlaresOptimization = /** @class */ (function (_super) {
  90948. __extends(LensFlaresOptimization, _super);
  90949. function LensFlaresOptimization() {
  90950. return _super !== null && _super.apply(this, arguments) || this;
  90951. }
  90952. /**
  90953. * Gets a string describing the action executed by the current optimization
  90954. * @return description string
  90955. */
  90956. LensFlaresOptimization.prototype.getDescription = function () {
  90957. return "Turning lens flares on/off";
  90958. };
  90959. /**
  90960. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90961. * @param scene defines the current scene where to apply this optimization
  90962. * @param optimizer defines the current optimizer
  90963. * @returns true if everything that can be done was applied
  90964. */
  90965. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  90966. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  90967. return true;
  90968. };
  90969. ;
  90970. return LensFlaresOptimization;
  90971. }(SceneOptimization));
  90972. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  90973. /**
  90974. * Defines an optimization based on user defined callback.
  90975. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90976. */
  90977. var CustomOptimization = /** @class */ (function (_super) {
  90978. __extends(CustomOptimization, _super);
  90979. function CustomOptimization() {
  90980. return _super !== null && _super.apply(this, arguments) || this;
  90981. }
  90982. /**
  90983. * Gets a string describing the action executed by the current optimization
  90984. * @returns description string
  90985. */
  90986. CustomOptimization.prototype.getDescription = function () {
  90987. if (this.onGetDescription) {
  90988. return this.onGetDescription();
  90989. }
  90990. return "Running user defined callback";
  90991. };
  90992. /**
  90993. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90994. * @param scene defines the current scene where to apply this optimization
  90995. * @param optimizer defines the current optimizer
  90996. * @returns true if everything that can be done was applied
  90997. */
  90998. CustomOptimization.prototype.apply = function (scene, optimizer) {
  90999. if (this.onApply) {
  91000. return this.onApply(scene, optimizer);
  91001. }
  91002. return true;
  91003. };
  91004. ;
  91005. return CustomOptimization;
  91006. }(SceneOptimization));
  91007. BABYLON.CustomOptimization = CustomOptimization;
  91008. /**
  91009. * Defines an optimization used to turn particles off
  91010. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91011. */
  91012. var ParticlesOptimization = /** @class */ (function (_super) {
  91013. __extends(ParticlesOptimization, _super);
  91014. function ParticlesOptimization() {
  91015. return _super !== null && _super.apply(this, arguments) || this;
  91016. }
  91017. /**
  91018. * Gets a string describing the action executed by the current optimization
  91019. * @return description string
  91020. */
  91021. ParticlesOptimization.prototype.getDescription = function () {
  91022. return "Turning particles on/off";
  91023. };
  91024. /**
  91025. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91026. * @param scene defines the current scene where to apply this optimization
  91027. * @param optimizer defines the current optimizer
  91028. * @returns true if everything that can be done was applied
  91029. */
  91030. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  91031. scene.particlesEnabled = optimizer.isInImprovementMode;
  91032. return true;
  91033. };
  91034. ;
  91035. return ParticlesOptimization;
  91036. }(SceneOptimization));
  91037. BABYLON.ParticlesOptimization = ParticlesOptimization;
  91038. /**
  91039. * Defines an optimization used to turn render targets off
  91040. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91041. */
  91042. var RenderTargetsOptimization = /** @class */ (function (_super) {
  91043. __extends(RenderTargetsOptimization, _super);
  91044. function RenderTargetsOptimization() {
  91045. return _super !== null && _super.apply(this, arguments) || this;
  91046. }
  91047. /**
  91048. * Gets a string describing the action executed by the current optimization
  91049. * @return description string
  91050. */
  91051. RenderTargetsOptimization.prototype.getDescription = function () {
  91052. return "Turning render targets off";
  91053. };
  91054. /**
  91055. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91056. * @param scene defines the current scene where to apply this optimization
  91057. * @param optimizer defines the current optimizer
  91058. * @returns true if everything that can be done was applied
  91059. */
  91060. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  91061. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  91062. return true;
  91063. };
  91064. ;
  91065. return RenderTargetsOptimization;
  91066. }(SceneOptimization));
  91067. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  91068. /**
  91069. * Defines an optimization used to merge meshes with compatible materials
  91070. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91071. */
  91072. var MergeMeshesOptimization = /** @class */ (function (_super) {
  91073. __extends(MergeMeshesOptimization, _super);
  91074. function MergeMeshesOptimization() {
  91075. var _this = _super !== null && _super.apply(this, arguments) || this;
  91076. _this._canBeMerged = function (abstractMesh) {
  91077. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  91078. return false;
  91079. }
  91080. var mesh = abstractMesh;
  91081. if (!mesh.isVisible || !mesh.isEnabled()) {
  91082. return false;
  91083. }
  91084. if (mesh.instances.length > 0) {
  91085. return false;
  91086. }
  91087. if (mesh.skeleton || mesh.hasLODLevels) {
  91088. return false;
  91089. }
  91090. if (mesh.parent) {
  91091. return false;
  91092. }
  91093. return true;
  91094. };
  91095. return _this;
  91096. }
  91097. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  91098. /**
  91099. * Gets or sets a boolean which defines if optimization octree has to be updated
  91100. */
  91101. get: function () {
  91102. return MergeMeshesOptimization._UpdateSelectionTree;
  91103. },
  91104. /**
  91105. * Gets or sets a boolean which defines if optimization octree has to be updated
  91106. */
  91107. set: function (value) {
  91108. MergeMeshesOptimization._UpdateSelectionTree = value;
  91109. },
  91110. enumerable: true,
  91111. configurable: true
  91112. });
  91113. /**
  91114. * Gets a string describing the action executed by the current optimization
  91115. * @return description string
  91116. */
  91117. MergeMeshesOptimization.prototype.getDescription = function () {
  91118. return "Merging similar meshes together";
  91119. };
  91120. /**
  91121. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91122. * @param scene defines the current scene where to apply this optimization
  91123. * @param optimizer defines the current optimizer
  91124. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  91125. * @returns true if everything that can be done was applied
  91126. */
  91127. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  91128. var globalPool = scene.meshes.slice(0);
  91129. var globalLength = globalPool.length;
  91130. for (var index = 0; index < globalLength; index++) {
  91131. var currentPool = new Array();
  91132. var current = globalPool[index];
  91133. // Checks
  91134. if (!this._canBeMerged(current)) {
  91135. continue;
  91136. }
  91137. currentPool.push(current);
  91138. // Find compatible meshes
  91139. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  91140. var otherMesh = globalPool[subIndex];
  91141. if (!this._canBeMerged(otherMesh)) {
  91142. continue;
  91143. }
  91144. if (otherMesh.material !== current.material) {
  91145. continue;
  91146. }
  91147. if (otherMesh.checkCollisions !== current.checkCollisions) {
  91148. continue;
  91149. }
  91150. currentPool.push(otherMesh);
  91151. globalLength--;
  91152. globalPool.splice(subIndex, 1);
  91153. subIndex--;
  91154. }
  91155. if (currentPool.length < 2) {
  91156. continue;
  91157. }
  91158. // Merge meshes
  91159. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  91160. }
  91161. if (updateSelectionTree != undefined) {
  91162. if (updateSelectionTree) {
  91163. scene.createOrUpdateSelectionOctree();
  91164. }
  91165. }
  91166. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  91167. scene.createOrUpdateSelectionOctree();
  91168. }
  91169. return true;
  91170. };
  91171. ;
  91172. MergeMeshesOptimization._UpdateSelectionTree = false;
  91173. return MergeMeshesOptimization;
  91174. }(SceneOptimization));
  91175. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  91176. /**
  91177. * Defines a list of options used by SceneOptimizer
  91178. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91179. */
  91180. var SceneOptimizerOptions = /** @class */ (function () {
  91181. /**
  91182. * Creates a new list of options used by SceneOptimizer
  91183. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  91184. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  91185. */
  91186. function SceneOptimizerOptions(
  91187. /**
  91188. * Defines the target frame rate to reach (60 by default)
  91189. */
  91190. targetFrameRate,
  91191. /**
  91192. * Defines the interval between two checkes (2000ms by default)
  91193. */
  91194. trackerDuration) {
  91195. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  91196. if (trackerDuration === void 0) { trackerDuration = 2000; }
  91197. this.targetFrameRate = targetFrameRate;
  91198. this.trackerDuration = trackerDuration;
  91199. /**
  91200. * Gets the list of optimizations to apply
  91201. */
  91202. this.optimizations = new Array();
  91203. }
  91204. /**
  91205. * Add a new optimization
  91206. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  91207. * @returns the current SceneOptimizerOptions
  91208. */
  91209. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  91210. this.optimizations.push(optimization);
  91211. return this;
  91212. };
  91213. /**
  91214. * Add a new custom optimization
  91215. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  91216. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  91217. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  91218. * @returns the current SceneOptimizerOptions
  91219. */
  91220. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  91221. if (priority === void 0) { priority = 0; }
  91222. var optimization = new CustomOptimization(priority);
  91223. optimization.onApply = onApply;
  91224. optimization.onGetDescription = onGetDescription;
  91225. this.optimizations.push(optimization);
  91226. return this;
  91227. };
  91228. /**
  91229. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  91230. * @param targetFrameRate defines the target frame rate (60 by default)
  91231. * @returns a SceneOptimizerOptions object
  91232. */
  91233. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  91234. var result = new SceneOptimizerOptions(targetFrameRate);
  91235. var priority = 0;
  91236. result.addOptimization(new MergeMeshesOptimization(priority));
  91237. result.addOptimization(new ShadowsOptimization(priority));
  91238. result.addOptimization(new LensFlaresOptimization(priority));
  91239. // Next priority
  91240. priority++;
  91241. result.addOptimization(new PostProcessesOptimization(priority));
  91242. result.addOptimization(new ParticlesOptimization(priority));
  91243. // Next priority
  91244. priority++;
  91245. result.addOptimization(new TextureOptimization(priority, 1024));
  91246. return result;
  91247. };
  91248. /**
  91249. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  91250. * @param targetFrameRate defines the target frame rate (60 by default)
  91251. * @returns a SceneOptimizerOptions object
  91252. */
  91253. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  91254. var result = new SceneOptimizerOptions(targetFrameRate);
  91255. var priority = 0;
  91256. result.addOptimization(new MergeMeshesOptimization(priority));
  91257. result.addOptimization(new ShadowsOptimization(priority));
  91258. result.addOptimization(new LensFlaresOptimization(priority));
  91259. // Next priority
  91260. priority++;
  91261. result.addOptimization(new PostProcessesOptimization(priority));
  91262. result.addOptimization(new ParticlesOptimization(priority));
  91263. // Next priority
  91264. priority++;
  91265. result.addOptimization(new TextureOptimization(priority, 512));
  91266. // Next priority
  91267. priority++;
  91268. result.addOptimization(new RenderTargetsOptimization(priority));
  91269. // Next priority
  91270. priority++;
  91271. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  91272. return result;
  91273. };
  91274. /**
  91275. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  91276. * @param targetFrameRate defines the target frame rate (60 by default)
  91277. * @returns a SceneOptimizerOptions object
  91278. */
  91279. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  91280. var result = new SceneOptimizerOptions(targetFrameRate);
  91281. var priority = 0;
  91282. result.addOptimization(new MergeMeshesOptimization(priority));
  91283. result.addOptimization(new ShadowsOptimization(priority));
  91284. result.addOptimization(new LensFlaresOptimization(priority));
  91285. // Next priority
  91286. priority++;
  91287. result.addOptimization(new PostProcessesOptimization(priority));
  91288. result.addOptimization(new ParticlesOptimization(priority));
  91289. // Next priority
  91290. priority++;
  91291. result.addOptimization(new TextureOptimization(priority, 256));
  91292. // Next priority
  91293. priority++;
  91294. result.addOptimization(new RenderTargetsOptimization(priority));
  91295. // Next priority
  91296. priority++;
  91297. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  91298. return result;
  91299. };
  91300. return SceneOptimizerOptions;
  91301. }());
  91302. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  91303. /**
  91304. * Class used to run optimizations in order to reach a target frame rate
  91305. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91306. */
  91307. var SceneOptimizer = /** @class */ (function () {
  91308. /**
  91309. * Creates a new SceneOptimizer
  91310. * @param scene defines the scene to work on
  91311. * @param options defines the options to use with the SceneOptimizer
  91312. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  91313. * @param improvementMode defines if the scene optimizer must run the maximum optimization while staying over a target frame instead of trying to reach the target framerate (false by default)
  91314. */
  91315. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  91316. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  91317. if (improvementMode === void 0) { improvementMode = false; }
  91318. var _this = this;
  91319. this._isRunning = false;
  91320. this._currentPriorityLevel = 0;
  91321. this._targetFrameRate = 60;
  91322. this._trackerDuration = 2000;
  91323. this._currentFrameRate = 0;
  91324. this._improvementMode = false;
  91325. /**
  91326. * Defines an observable called when the optimizer reaches the target frame rate
  91327. */
  91328. this.onSuccessObservable = new BABYLON.Observable();
  91329. /**
  91330. * Defines an observable called when the optimizer enables an optimization
  91331. */
  91332. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  91333. /**
  91334. * Defines an observable called when the optimizer is not able to reach the target frame rate
  91335. */
  91336. this.onFailureObservable = new BABYLON.Observable();
  91337. if (!options) {
  91338. this._options = new SceneOptimizerOptions();
  91339. }
  91340. else {
  91341. this._options = options;
  91342. }
  91343. if (this._options.targetFrameRate) {
  91344. this._targetFrameRate = this._options.targetFrameRate;
  91345. }
  91346. if (this._options.trackerDuration) {
  91347. this._trackerDuration = this._options.trackerDuration;
  91348. }
  91349. if (autoGeneratePriorities) {
  91350. var priority = 0;
  91351. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  91352. var optim = _a[_i];
  91353. optim.priority = priority++;
  91354. }
  91355. }
  91356. this._improvementMode = improvementMode;
  91357. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91358. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  91359. _this._sceneDisposeObserver = null;
  91360. _this.dispose();
  91361. });
  91362. }
  91363. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  91364. /**
  91365. * Gets a boolean indicating if the optimizer is in improvement mode
  91366. */
  91367. get: function () {
  91368. return this._improvementMode;
  91369. },
  91370. enumerable: true,
  91371. configurable: true
  91372. });
  91373. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  91374. /**
  91375. * Gets the current priority level (0 at start)
  91376. */
  91377. get: function () {
  91378. return this._currentPriorityLevel;
  91379. },
  91380. enumerable: true,
  91381. configurable: true
  91382. });
  91383. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  91384. /**
  91385. * Gets the current frame rate checked by the SceneOptimizer
  91386. */
  91387. get: function () {
  91388. return this._currentFrameRate;
  91389. },
  91390. enumerable: true,
  91391. configurable: true
  91392. });
  91393. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  91394. /**
  91395. * Gets or sets the current target frame rate (60 by default)
  91396. */
  91397. get: function () {
  91398. return this._targetFrameRate;
  91399. },
  91400. /**
  91401. * Gets or sets the current target frame rate (60 by default)
  91402. */
  91403. set: function (value) {
  91404. this._targetFrameRate = value;
  91405. },
  91406. enumerable: true,
  91407. configurable: true
  91408. });
  91409. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  91410. /**
  91411. * Gets or sets the current interval between two checks (every 2000ms by default)
  91412. */
  91413. get: function () {
  91414. return this._trackerDuration;
  91415. },
  91416. /**
  91417. * Gets or sets the current interval between two checks (every 2000ms by default)
  91418. */
  91419. set: function (value) {
  91420. this._trackerDuration = value;
  91421. },
  91422. enumerable: true,
  91423. configurable: true
  91424. });
  91425. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  91426. /**
  91427. * Gets the list of active optimizations
  91428. */
  91429. get: function () {
  91430. return this._options.optimizations;
  91431. },
  91432. enumerable: true,
  91433. configurable: true
  91434. });
  91435. /**
  91436. * Stops the current optimizer
  91437. */
  91438. SceneOptimizer.prototype.stop = function () {
  91439. this._isRunning = false;
  91440. };
  91441. /**
  91442. * Reset the optimizer to initial step (current priority level = 0)
  91443. */
  91444. SceneOptimizer.prototype.reset = function () {
  91445. this._currentPriorityLevel = 0;
  91446. };
  91447. /**
  91448. * Start the optimizer. By default it will try to reach a specific framerate
  91449. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  91450. */
  91451. SceneOptimizer.prototype.start = function () {
  91452. var _this = this;
  91453. if (this._isRunning) {
  91454. return;
  91455. }
  91456. this._isRunning = true;
  91457. // Let's wait for the scene to be ready before running our check
  91458. this._scene.executeWhenReady(function () {
  91459. setTimeout(function () {
  91460. _this._checkCurrentState();
  91461. }, _this._trackerDuration);
  91462. });
  91463. };
  91464. SceneOptimizer.prototype._checkCurrentState = function () {
  91465. var _this = this;
  91466. if (!this._isRunning) {
  91467. return;
  91468. }
  91469. var scene = this._scene;
  91470. var options = this._options;
  91471. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  91472. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  91473. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  91474. this._isRunning = false;
  91475. this.onSuccessObservable.notifyObservers(this);
  91476. return;
  91477. }
  91478. // Apply current level of optimizations
  91479. var allDone = true;
  91480. var noOptimizationApplied = true;
  91481. for (var index = 0; index < options.optimizations.length; index++) {
  91482. var optimization = options.optimizations[index];
  91483. if (optimization.priority === this._currentPriorityLevel) {
  91484. noOptimizationApplied = false;
  91485. allDone = allDone && optimization.apply(scene, this);
  91486. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  91487. }
  91488. }
  91489. // If no optimization was applied, this is a failure :(
  91490. if (noOptimizationApplied) {
  91491. this._isRunning = false;
  91492. this.onFailureObservable.notifyObservers(this);
  91493. return;
  91494. }
  91495. // If all optimizations were done, move to next level
  91496. if (allDone) {
  91497. this._currentPriorityLevel++;
  91498. }
  91499. // Let's the system running for a specific amount of time before checking FPS
  91500. scene.executeWhenReady(function () {
  91501. setTimeout(function () {
  91502. _this._checkCurrentState();
  91503. }, _this._trackerDuration);
  91504. });
  91505. };
  91506. /**
  91507. * Release all resources
  91508. */
  91509. SceneOptimizer.prototype.dispose = function () {
  91510. this.stop();
  91511. this.onSuccessObservable.clear();
  91512. this.onFailureObservable.clear();
  91513. this.onNewOptimizationAppliedObservable.clear();
  91514. if (this._sceneDisposeObserver) {
  91515. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  91516. }
  91517. };
  91518. /**
  91519. * Helper function to create a SceneOptimizer with one single line of code
  91520. * @param scene defines the scene to work on
  91521. * @param options defines the options to use with the SceneOptimizer
  91522. * @param onSuccess defines a callback to call on success
  91523. * @param onFailure defines a callback to call on failure
  91524. * @returns the new SceneOptimizer object
  91525. */
  91526. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  91527. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  91528. if (onSuccess) {
  91529. optimizer.onSuccessObservable.add(function () {
  91530. onSuccess();
  91531. });
  91532. }
  91533. if (onFailure) {
  91534. optimizer.onFailureObservable.add(function () {
  91535. onFailure();
  91536. });
  91537. }
  91538. optimizer.start();
  91539. return optimizer;
  91540. };
  91541. return SceneOptimizer;
  91542. }());
  91543. BABYLON.SceneOptimizer = SceneOptimizer;
  91544. })(BABYLON || (BABYLON = {}));
  91545. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  91546. var BABYLON;
  91547. (function (BABYLON) {
  91548. var OutlineRenderer = /** @class */ (function () {
  91549. function OutlineRenderer(scene) {
  91550. this.zOffset = 1;
  91551. this._scene = scene;
  91552. }
  91553. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  91554. var _this = this;
  91555. if (useOverlay === void 0) { useOverlay = false; }
  91556. var scene = this._scene;
  91557. var engine = this._scene.getEngine();
  91558. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91559. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  91560. return;
  91561. }
  91562. var mesh = subMesh.getRenderingMesh();
  91563. var material = subMesh.getMaterial();
  91564. if (!material || !scene.activeCamera) {
  91565. return;
  91566. }
  91567. engine.enableEffect(this._effect);
  91568. // Logarithmic depth
  91569. if (material.useLogarithmicDepth) {
  91570. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  91571. }
  91572. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  91573. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  91574. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  91575. // Bones
  91576. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91577. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91578. }
  91579. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  91580. // Alpha test
  91581. if (material && material.needAlphaTesting()) {
  91582. var alphaTexture = material.getAlphaTestTexture();
  91583. if (alphaTexture) {
  91584. this._effect.setTexture("diffuseSampler", alphaTexture);
  91585. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  91586. }
  91587. }
  91588. engine.setZOffset(-this.zOffset);
  91589. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  91590. engine.setZOffset(0);
  91591. };
  91592. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  91593. var defines = [];
  91594. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  91595. var mesh = subMesh.getMesh();
  91596. var material = subMesh.getMaterial();
  91597. if (material) {
  91598. // Alpha test
  91599. if (material.needAlphaTesting()) {
  91600. defines.push("#define ALPHATEST");
  91601. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91602. attribs.push(BABYLON.VertexBuffer.UVKind);
  91603. defines.push("#define UV1");
  91604. }
  91605. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  91606. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91607. defines.push("#define UV2");
  91608. }
  91609. }
  91610. //Logarithmic depth
  91611. if (material.useLogarithmicDepth) {
  91612. defines.push("#define LOGARITHMICDEPTH");
  91613. }
  91614. }
  91615. // Bones
  91616. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91617. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91618. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91619. if (mesh.numBoneInfluencers > 4) {
  91620. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91621. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91622. }
  91623. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91624. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  91625. }
  91626. else {
  91627. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91628. }
  91629. // Instances
  91630. if (useInstances) {
  91631. defines.push("#define INSTANCES");
  91632. attribs.push("world0");
  91633. attribs.push("world1");
  91634. attribs.push("world2");
  91635. attribs.push("world3");
  91636. }
  91637. // Get correct effect
  91638. var join = defines.join("\n");
  91639. if (this._cachedDefines !== join) {
  91640. this._cachedDefines = join;
  91641. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  91642. }
  91643. return this._effect.isReady();
  91644. };
  91645. return OutlineRenderer;
  91646. }());
  91647. BABYLON.OutlineRenderer = OutlineRenderer;
  91648. })(BABYLON || (BABYLON = {}));
  91649. //# sourceMappingURL=babylon.outlineRenderer.js.map
  91650. var BABYLON;
  91651. (function (BABYLON) {
  91652. var FaceAdjacencies = /** @class */ (function () {
  91653. function FaceAdjacencies() {
  91654. this.edges = new Array();
  91655. this.edgesConnectedCount = 0;
  91656. }
  91657. return FaceAdjacencies;
  91658. }());
  91659. var EdgesRenderer = /** @class */ (function () {
  91660. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  91661. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  91662. if (epsilon === void 0) { epsilon = 0.95; }
  91663. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  91664. this.edgesWidthScalerForOrthographic = 1000.0;
  91665. this.edgesWidthScalerForPerspective = 50.0;
  91666. this._linesPositions = new Array();
  91667. this._linesNormals = new Array();
  91668. this._linesIndices = new Array();
  91669. this._buffers = {};
  91670. this._checkVerticesInsteadOfIndices = false;
  91671. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  91672. this.isEnabled = true;
  91673. this._source = source;
  91674. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  91675. this._epsilon = epsilon;
  91676. this._prepareRessources();
  91677. this._generateEdgesLines();
  91678. }
  91679. EdgesRenderer.prototype._prepareRessources = function () {
  91680. if (this._lineShader) {
  91681. return;
  91682. }
  91683. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  91684. attributes: ["position", "normal"],
  91685. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  91686. });
  91687. this._lineShader.disableDepthWrite = true;
  91688. this._lineShader.backFaceCulling = false;
  91689. };
  91690. EdgesRenderer.prototype._rebuild = function () {
  91691. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91692. if (buffer) {
  91693. buffer._rebuild();
  91694. }
  91695. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91696. if (buffer) {
  91697. buffer._rebuild();
  91698. }
  91699. var scene = this._source.getScene();
  91700. var engine = scene.getEngine();
  91701. this._ib = engine.createIndexBuffer(this._linesIndices);
  91702. };
  91703. EdgesRenderer.prototype.dispose = function () {
  91704. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91705. if (buffer) {
  91706. buffer.dispose();
  91707. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  91708. }
  91709. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91710. if (buffer) {
  91711. buffer.dispose();
  91712. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  91713. }
  91714. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  91715. this._lineShader.dispose();
  91716. };
  91717. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  91718. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  91719. return 0;
  91720. }
  91721. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  91722. return 1;
  91723. }
  91724. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  91725. return 2;
  91726. }
  91727. return -1;
  91728. };
  91729. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  91730. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  91731. return 0;
  91732. }
  91733. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  91734. return 1;
  91735. }
  91736. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  91737. return 2;
  91738. }
  91739. return -1;
  91740. };
  91741. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  91742. var needToCreateLine;
  91743. if (edge === undefined) {
  91744. needToCreateLine = true;
  91745. }
  91746. else {
  91747. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  91748. needToCreateLine = dotProduct < this._epsilon;
  91749. }
  91750. if (needToCreateLine) {
  91751. var offset = this._linesPositions.length / 3;
  91752. var normal = p0.subtract(p1);
  91753. normal.normalize();
  91754. // Positions
  91755. this._linesPositions.push(p0.x);
  91756. this._linesPositions.push(p0.y);
  91757. this._linesPositions.push(p0.z);
  91758. this._linesPositions.push(p0.x);
  91759. this._linesPositions.push(p0.y);
  91760. this._linesPositions.push(p0.z);
  91761. this._linesPositions.push(p1.x);
  91762. this._linesPositions.push(p1.y);
  91763. this._linesPositions.push(p1.z);
  91764. this._linesPositions.push(p1.x);
  91765. this._linesPositions.push(p1.y);
  91766. this._linesPositions.push(p1.z);
  91767. // Normals
  91768. this._linesNormals.push(p1.x);
  91769. this._linesNormals.push(p1.y);
  91770. this._linesNormals.push(p1.z);
  91771. this._linesNormals.push(-1);
  91772. this._linesNormals.push(p1.x);
  91773. this._linesNormals.push(p1.y);
  91774. this._linesNormals.push(p1.z);
  91775. this._linesNormals.push(1);
  91776. this._linesNormals.push(p0.x);
  91777. this._linesNormals.push(p0.y);
  91778. this._linesNormals.push(p0.z);
  91779. this._linesNormals.push(-1);
  91780. this._linesNormals.push(p0.x);
  91781. this._linesNormals.push(p0.y);
  91782. this._linesNormals.push(p0.z);
  91783. this._linesNormals.push(1);
  91784. // Indices
  91785. this._linesIndices.push(offset);
  91786. this._linesIndices.push(offset + 1);
  91787. this._linesIndices.push(offset + 2);
  91788. this._linesIndices.push(offset);
  91789. this._linesIndices.push(offset + 2);
  91790. this._linesIndices.push(offset + 3);
  91791. }
  91792. };
  91793. EdgesRenderer.prototype._generateEdgesLines = function () {
  91794. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  91795. var indices = this._source.getIndices();
  91796. if (!indices || !positions) {
  91797. return;
  91798. }
  91799. // First let's find adjacencies
  91800. var adjacencies = new Array();
  91801. var faceNormals = new Array();
  91802. var index;
  91803. var faceAdjacencies;
  91804. // Prepare faces
  91805. for (index = 0; index < indices.length; index += 3) {
  91806. faceAdjacencies = new FaceAdjacencies();
  91807. var p0Index = indices[index];
  91808. var p1Index = indices[index + 1];
  91809. var p2Index = indices[index + 2];
  91810. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  91811. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  91812. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  91813. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  91814. faceNormal.normalize();
  91815. faceNormals.push(faceNormal);
  91816. adjacencies.push(faceAdjacencies);
  91817. }
  91818. // Scan
  91819. for (index = 0; index < adjacencies.length; index++) {
  91820. faceAdjacencies = adjacencies[index];
  91821. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  91822. var otherFaceAdjacencies = adjacencies[otherIndex];
  91823. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  91824. break;
  91825. }
  91826. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  91827. continue;
  91828. }
  91829. var otherP0 = indices[otherIndex * 3];
  91830. var otherP1 = indices[otherIndex * 3 + 1];
  91831. var otherP2 = indices[otherIndex * 3 + 2];
  91832. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  91833. var otherEdgeIndex = 0;
  91834. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  91835. continue;
  91836. }
  91837. switch (edgeIndex) {
  91838. case 0:
  91839. if (this._checkVerticesInsteadOfIndices) {
  91840. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91841. }
  91842. else {
  91843. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  91844. }
  91845. break;
  91846. case 1:
  91847. if (this._checkVerticesInsteadOfIndices) {
  91848. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91849. }
  91850. else {
  91851. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  91852. }
  91853. break;
  91854. case 2:
  91855. if (this._checkVerticesInsteadOfIndices) {
  91856. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91857. }
  91858. else {
  91859. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  91860. }
  91861. break;
  91862. }
  91863. if (otherEdgeIndex === -1) {
  91864. continue;
  91865. }
  91866. faceAdjacencies.edges[edgeIndex] = otherIndex;
  91867. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  91868. faceAdjacencies.edgesConnectedCount++;
  91869. otherFaceAdjacencies.edgesConnectedCount++;
  91870. if (faceAdjacencies.edgesConnectedCount === 3) {
  91871. break;
  91872. }
  91873. }
  91874. }
  91875. }
  91876. // Create lines
  91877. for (index = 0; index < adjacencies.length; index++) {
  91878. // We need a line when a face has no adjacency on a specific edge or if all the adjacencies has an angle greater than epsilon
  91879. var current = adjacencies[index];
  91880. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  91881. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  91882. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  91883. }
  91884. // Merge into a single mesh
  91885. var engine = this._source.getScene().getEngine();
  91886. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  91887. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  91888. this._ib = engine.createIndexBuffer(this._linesIndices);
  91889. this._indicesCount = this._linesIndices.length;
  91890. };
  91891. EdgesRenderer.prototype.render = function () {
  91892. var scene = this._source.getScene();
  91893. if (!this._lineShader.isReady() || !scene.activeCamera) {
  91894. return;
  91895. }
  91896. var engine = scene.getEngine();
  91897. this._lineShader._preBind();
  91898. // VBOs
  91899. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  91900. scene.resetCachedMaterial();
  91901. this._lineShader.setColor4("color", this._source.edgesColor);
  91902. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  91903. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  91904. }
  91905. else {
  91906. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  91907. }
  91908. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  91909. this._lineShader.bind(this._source.getWorldMatrix());
  91910. // Draw order
  91911. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  91912. this._lineShader.unbind();
  91913. engine.setDepthWrite(true);
  91914. };
  91915. return EdgesRenderer;
  91916. }());
  91917. BABYLON.EdgesRenderer = EdgesRenderer;
  91918. })(BABYLON || (BABYLON = {}));
  91919. //# sourceMappingURL=babylon.edgesRenderer.js.map
  91920. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91921. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91922. s = arguments[i];
  91923. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91924. t[p] = s[p];
  91925. }
  91926. return t;
  91927. };
  91928. var BABYLON;
  91929. (function (BABYLON) {
  91930. /**
  91931. * The effect layer Helps adding post process effect blended with the main pass.
  91932. *
  91933. * This can be for instance use to generate glow or higlight effects on the scene.
  91934. *
  91935. * The effect layer class can not be used directly and is intented to inherited from to be
  91936. * customized per effects.
  91937. */
  91938. var EffectLayer = /** @class */ (function () {
  91939. /**
  91940. * Instantiates a new effect Layer and references it in the scene.
  91941. * @param name The name of the layer
  91942. * @param scene The scene to use the layer in
  91943. */
  91944. function EffectLayer(
  91945. /** The Friendly of the effect in the scene */
  91946. name, scene) {
  91947. this._vertexBuffers = {};
  91948. this._maxSize = 0;
  91949. this._mainTextureDesiredSize = { width: 0, height: 0 };
  91950. this._shouldRender = true;
  91951. this._postProcesses = [];
  91952. this._textures = [];
  91953. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  91954. /**
  91955. * The clear color of the texture used to generate the glow map.
  91956. */
  91957. this.neutralColor = new BABYLON.Color4();
  91958. /**
  91959. * Specifies wether the highlight layer is enabled or not.
  91960. */
  91961. this.isEnabled = true;
  91962. /**
  91963. * An event triggered when the effect layer has been disposed.
  91964. */
  91965. this.onDisposeObservable = new BABYLON.Observable();
  91966. /**
  91967. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  91968. */
  91969. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  91970. /**
  91971. * An event triggered when the generated texture is being merged in the scene.
  91972. */
  91973. this.onBeforeComposeObservable = new BABYLON.Observable();
  91974. /**
  91975. * An event triggered when the generated texture has been merged in the scene.
  91976. */
  91977. this.onAfterComposeObservable = new BABYLON.Observable();
  91978. /**
  91979. * An event triggered when the efffect layer changes its size.
  91980. */
  91981. this.onSizeChangedObservable = new BABYLON.Observable();
  91982. this.name = name;
  91983. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91984. this._engine = scene.getEngine();
  91985. this._maxSize = this._engine.getCaps().maxTextureSize;
  91986. this._scene.effectLayers.push(this);
  91987. // Generate Buffers
  91988. this._generateIndexBuffer();
  91989. this._genrateVertexBuffer();
  91990. }
  91991. Object.defineProperty(EffectLayer.prototype, "camera", {
  91992. /**
  91993. * Gets the camera attached to the layer.
  91994. */
  91995. get: function () {
  91996. return this._effectLayerOptions.camera;
  91997. },
  91998. enumerable: true,
  91999. configurable: true
  92000. });
  92001. /**
  92002. * Initializes the effect layer with the required options.
  92003. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  92004. */
  92005. EffectLayer.prototype._init = function (options) {
  92006. // Adapt options
  92007. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  92008. this._setMainTextureSize();
  92009. this._createMainTexture();
  92010. this._createTextureAndPostProcesses();
  92011. this._mergeEffect = this._createMergeEffect();
  92012. };
  92013. /**
  92014. * Generates the index buffer of the full screen quad blending to the main canvas.
  92015. */
  92016. EffectLayer.prototype._generateIndexBuffer = function () {
  92017. // Indices
  92018. var indices = [];
  92019. indices.push(0);
  92020. indices.push(1);
  92021. indices.push(2);
  92022. indices.push(0);
  92023. indices.push(2);
  92024. indices.push(3);
  92025. this._indexBuffer = this._engine.createIndexBuffer(indices);
  92026. };
  92027. /**
  92028. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  92029. */
  92030. EffectLayer.prototype._genrateVertexBuffer = function () {
  92031. // VBO
  92032. var vertices = [];
  92033. vertices.push(1, 1);
  92034. vertices.push(-1, 1);
  92035. vertices.push(-1, -1);
  92036. vertices.push(1, -1);
  92037. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  92038. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  92039. };
  92040. /**
  92041. * Sets the main texture desired size which is the closest power of two
  92042. * of the engine canvas size.
  92043. */
  92044. EffectLayer.prototype._setMainTextureSize = function () {
  92045. if (this._effectLayerOptions.mainTextureFixedSize) {
  92046. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  92047. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  92048. }
  92049. else {
  92050. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  92051. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  92052. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  92053. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  92054. }
  92055. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  92056. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  92057. };
  92058. /**
  92059. * Creates the main texture for the effect layer.
  92060. */
  92061. EffectLayer.prototype._createMainTexture = function () {
  92062. var _this = this;
  92063. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  92064. width: this._mainTextureDesiredSize.width,
  92065. height: this._mainTextureDesiredSize.height
  92066. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  92067. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  92068. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92069. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92070. this._mainTexture.anisotropicFilteringLevel = 1;
  92071. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92072. this._mainTexture.renderParticles = false;
  92073. this._mainTexture.renderList = null;
  92074. this._mainTexture.ignoreCameraViewport = true;
  92075. // Custom render function
  92076. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  92077. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  92078. var index;
  92079. var engine = _this._scene.getEngine();
  92080. if (depthOnlySubMeshes.length) {
  92081. engine.setColorWrite(false);
  92082. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  92083. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  92084. }
  92085. engine.setColorWrite(true);
  92086. }
  92087. for (index = 0; index < opaqueSubMeshes.length; index++) {
  92088. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  92089. }
  92090. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  92091. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  92092. }
  92093. for (index = 0; index < transparentSubMeshes.length; index++) {
  92094. _this._renderSubMesh(transparentSubMeshes.data[index]);
  92095. }
  92096. };
  92097. this._mainTexture.onClearObservable.add(function (engine) {
  92098. engine.clear(_this.neutralColor, true, true, true);
  92099. });
  92100. };
  92101. /**
  92102. * Checks for the readiness of the element composing the layer.
  92103. * @param subMesh the mesh to check for
  92104. * @param useInstances specify wether or not to use instances to render the mesh
  92105. * @param emissiveTexture the associated emissive texture used to generate the glow
  92106. * @return true if ready otherwise, false
  92107. */
  92108. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  92109. var material = subMesh.getMaterial();
  92110. if (!material) {
  92111. return false;
  92112. }
  92113. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  92114. return false;
  92115. }
  92116. var defines = [];
  92117. var attribs = [BABYLON.VertexBuffer.PositionKind];
  92118. var mesh = subMesh.getMesh();
  92119. var uv1 = false;
  92120. var uv2 = false;
  92121. // Alpha test
  92122. if (material && material.needAlphaTesting()) {
  92123. var alphaTexture = material.getAlphaTestTexture();
  92124. if (alphaTexture) {
  92125. defines.push("#define ALPHATEST");
  92126. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  92127. alphaTexture.coordinatesIndex === 1) {
  92128. defines.push("#define DIFFUSEUV2");
  92129. uv2 = true;
  92130. }
  92131. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  92132. defines.push("#define DIFFUSEUV1");
  92133. uv1 = true;
  92134. }
  92135. }
  92136. }
  92137. // Emissive
  92138. if (emissiveTexture) {
  92139. defines.push("#define EMISSIVE");
  92140. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  92141. emissiveTexture.coordinatesIndex === 1) {
  92142. defines.push("#define EMISSIVEUV2");
  92143. uv2 = true;
  92144. }
  92145. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  92146. defines.push("#define EMISSIVEUV1");
  92147. uv1 = true;
  92148. }
  92149. }
  92150. if (uv1) {
  92151. attribs.push(BABYLON.VertexBuffer.UVKind);
  92152. defines.push("#define UV1");
  92153. }
  92154. if (uv2) {
  92155. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  92156. defines.push("#define UV2");
  92157. }
  92158. // Bones
  92159. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  92160. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  92161. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  92162. if (mesh.numBoneInfluencers > 4) {
  92163. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  92164. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  92165. }
  92166. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  92167. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  92168. }
  92169. else {
  92170. defines.push("#define NUM_BONE_INFLUENCERS 0");
  92171. }
  92172. // Morph targets
  92173. var manager = mesh.morphTargetManager;
  92174. var morphInfluencers = 0;
  92175. if (manager) {
  92176. if (manager.numInfluencers > 0) {
  92177. defines.push("#define MORPHTARGETS");
  92178. morphInfluencers = manager.numInfluencers;
  92179. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  92180. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  92181. }
  92182. }
  92183. // Instances
  92184. if (useInstances) {
  92185. defines.push("#define INSTANCES");
  92186. attribs.push("world0");
  92187. attribs.push("world1");
  92188. attribs.push("world2");
  92189. attribs.push("world3");
  92190. }
  92191. // Get correct effect
  92192. var join = defines.join("\n");
  92193. if (this._cachedDefines !== join) {
  92194. this._cachedDefines = join;
  92195. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  92196. }
  92197. return this._effectLayerMapGenerationEffect.isReady();
  92198. };
  92199. /**
  92200. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  92201. */
  92202. EffectLayer.prototype.render = function () {
  92203. var currentEffect = this._mergeEffect;
  92204. // Check
  92205. if (!currentEffect.isReady())
  92206. return;
  92207. for (var i = 0; i < this._postProcesses.length; i++) {
  92208. if (!this._postProcesses[i].isReady()) {
  92209. return;
  92210. }
  92211. }
  92212. var engine = this._scene.getEngine();
  92213. this.onBeforeComposeObservable.notifyObservers(this);
  92214. // Render
  92215. engine.enableEffect(currentEffect);
  92216. engine.setState(false);
  92217. // VBOs
  92218. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  92219. // Cache
  92220. var previousAlphaMode = engine.getAlphaMode();
  92221. // Go Blend.
  92222. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  92223. // Blends the map on the main canvas.
  92224. this._internalRender(currentEffect);
  92225. // Restore Alpha
  92226. engine.setAlphaMode(previousAlphaMode);
  92227. this.onAfterComposeObservable.notifyObservers(this);
  92228. // Handle size changes.
  92229. var size = this._mainTexture.getSize();
  92230. this._setMainTextureSize();
  92231. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  92232. // Recreate RTT and post processes on size change.
  92233. this.onSizeChangedObservable.notifyObservers(this);
  92234. this._disposeTextureAndPostProcesses();
  92235. this._createMainTexture();
  92236. this._createTextureAndPostProcesses();
  92237. }
  92238. };
  92239. /**
  92240. * Determine if a given mesh will be used in the current effect.
  92241. * @param mesh mesh to test
  92242. * @returns true if the mesh will be used
  92243. */
  92244. EffectLayer.prototype.hasMesh = function (mesh) {
  92245. return true;
  92246. };
  92247. /**
  92248. * Returns true if the layer contains information to display, otherwise false.
  92249. * @returns true if the glow layer should be rendered
  92250. */
  92251. EffectLayer.prototype.shouldRender = function () {
  92252. return this.isEnabled && this._shouldRender;
  92253. };
  92254. /**
  92255. * Returns true if the mesh should render, otherwise false.
  92256. * @param mesh The mesh to render
  92257. * @returns true if it should render otherwise false
  92258. */
  92259. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  92260. return true;
  92261. };
  92262. /**
  92263. * Returns true if the mesh should render, otherwise false.
  92264. * @param mesh The mesh to render
  92265. * @returns true if it should render otherwise false
  92266. */
  92267. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  92268. return true;
  92269. };
  92270. /**
  92271. * Renders the submesh passed in parameter to the generation map.
  92272. */
  92273. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  92274. var _this = this;
  92275. if (!this.shouldRender()) {
  92276. return;
  92277. }
  92278. var material = subMesh.getMaterial();
  92279. var mesh = subMesh.getRenderingMesh();
  92280. var scene = this._scene;
  92281. var engine = scene.getEngine();
  92282. if (!material) {
  92283. return;
  92284. }
  92285. // Do not block in blend mode.
  92286. if (material.needAlphaBlendingForMesh(mesh)) {
  92287. return;
  92288. }
  92289. // Culling
  92290. engine.setState(material.backFaceCulling);
  92291. // Managing instances
  92292. var batch = mesh._getInstancesRenderList(subMesh._id);
  92293. if (batch.mustReturn) {
  92294. return;
  92295. }
  92296. // Early Exit per mesh
  92297. if (!this._shouldRenderMesh(mesh)) {
  92298. return;
  92299. }
  92300. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  92301. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  92302. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  92303. engine.enableEffect(this._effectLayerMapGenerationEffect);
  92304. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  92305. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  92306. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  92307. // Alpha test
  92308. if (material && material.needAlphaTesting()) {
  92309. var alphaTexture = material.getAlphaTestTexture();
  92310. if (alphaTexture) {
  92311. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  92312. var textureMatrix = alphaTexture.getTextureMatrix();
  92313. if (textureMatrix) {
  92314. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  92315. }
  92316. }
  92317. }
  92318. // Glow emissive only
  92319. if (this._emissiveTextureAndColor.texture) {
  92320. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  92321. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  92322. }
  92323. // Bones
  92324. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  92325. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  92326. }
  92327. // Morph targets
  92328. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  92329. // Draw
  92330. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  92331. }
  92332. else {
  92333. // Need to reset refresh rate of the shadowMap
  92334. this._mainTexture.resetRefreshCounter();
  92335. }
  92336. };
  92337. /**
  92338. * Rebuild the required buffers.
  92339. * @hidden Internal use only.
  92340. */
  92341. EffectLayer.prototype._rebuild = function () {
  92342. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  92343. if (vb) {
  92344. vb._rebuild();
  92345. }
  92346. this._generateIndexBuffer();
  92347. };
  92348. /**
  92349. * Dispose only the render target textures and post process.
  92350. */
  92351. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  92352. this._mainTexture.dispose();
  92353. for (var i = 0; i < this._postProcesses.length; i++) {
  92354. if (this._postProcesses[i]) {
  92355. this._postProcesses[i].dispose();
  92356. }
  92357. }
  92358. this._postProcesses = [];
  92359. for (var i = 0; i < this._textures.length; i++) {
  92360. if (this._textures[i]) {
  92361. this._textures[i].dispose();
  92362. }
  92363. }
  92364. this._textures = [];
  92365. };
  92366. /**
  92367. * Dispose the highlight layer and free resources.
  92368. */
  92369. EffectLayer.prototype.dispose = function () {
  92370. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  92371. if (vertexBuffer) {
  92372. vertexBuffer.dispose();
  92373. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  92374. }
  92375. if (this._indexBuffer) {
  92376. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  92377. this._indexBuffer = null;
  92378. }
  92379. // Clean textures and post processes
  92380. this._disposeTextureAndPostProcesses();
  92381. // Remove from scene
  92382. var index = this._scene.effectLayers.indexOf(this, 0);
  92383. if (index > -1) {
  92384. this._scene.effectLayers.splice(index, 1);
  92385. }
  92386. // Callback
  92387. this.onDisposeObservable.notifyObservers(this);
  92388. this.onDisposeObservable.clear();
  92389. this.onBeforeRenderMainTextureObservable.clear();
  92390. this.onBeforeComposeObservable.clear();
  92391. this.onAfterComposeObservable.clear();
  92392. this.onSizeChangedObservable.clear();
  92393. };
  92394. /**
  92395. * Gets the class name of the effect layer
  92396. * @returns the string with the class name of the effect layer
  92397. */
  92398. EffectLayer.prototype.getClassName = function () {
  92399. return "EffectLayer";
  92400. };
  92401. /**
  92402. * Creates an effect layer from parsed effect layer data
  92403. * @param parsedEffectLayer defines effect layer data
  92404. * @param scene defines the current scene
  92405. * @param rootUrl defines the root URL containing the effect layer information
  92406. * @returns a parsed effect Layer
  92407. */
  92408. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  92409. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  92410. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  92411. };
  92412. __decorate([
  92413. BABYLON.serialize()
  92414. ], EffectLayer.prototype, "name", void 0);
  92415. __decorate([
  92416. BABYLON.serializeAsColor4()
  92417. ], EffectLayer.prototype, "neutralColor", void 0);
  92418. __decorate([
  92419. BABYLON.serialize()
  92420. ], EffectLayer.prototype, "isEnabled", void 0);
  92421. __decorate([
  92422. BABYLON.serializeAsCameraReference()
  92423. ], EffectLayer.prototype, "camera", null);
  92424. return EffectLayer;
  92425. }());
  92426. BABYLON.EffectLayer = EffectLayer;
  92427. })(BABYLON || (BABYLON = {}));
  92428. //# sourceMappingURL=babylon.effectLayer.js.map
  92429. var BABYLON;
  92430. (function (BABYLON) {
  92431. /**
  92432. * Special Glow Blur post process only blurring the alpha channel
  92433. * It enforces keeping the most luminous color in the color channel.
  92434. */
  92435. var GlowBlurPostProcess = /** @class */ (function (_super) {
  92436. __extends(GlowBlurPostProcess, _super);
  92437. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  92438. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  92439. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  92440. _this.direction = direction;
  92441. _this.kernel = kernel;
  92442. _this.onApplyObservable.add(function (effect) {
  92443. effect.setFloat2("screenSize", _this.width, _this.height);
  92444. effect.setVector2("direction", _this.direction);
  92445. effect.setFloat("blurWidth", _this.kernel);
  92446. });
  92447. return _this;
  92448. }
  92449. return GlowBlurPostProcess;
  92450. }(BABYLON.PostProcess));
  92451. /**
  92452. * The highlight layer Helps adding a glow effect around a mesh.
  92453. *
  92454. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92455. * glowy meshes to your scene.
  92456. *
  92457. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  92458. */
  92459. var HighlightLayer = /** @class */ (function (_super) {
  92460. __extends(HighlightLayer, _super);
  92461. /**
  92462. * Instantiates a new highlight Layer and references it to the scene..
  92463. * @param name The name of the layer
  92464. * @param scene The scene to use the layer in
  92465. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  92466. */
  92467. function HighlightLayer(name, scene, options) {
  92468. var _this = _super.call(this, name, scene) || this;
  92469. _this.name = name;
  92470. /**
  92471. * Specifies whether or not the inner glow is ACTIVE in the layer.
  92472. */
  92473. _this.innerGlow = true;
  92474. /**
  92475. * Specifies whether or not the outer glow is ACTIVE in the layer.
  92476. */
  92477. _this.outerGlow = true;
  92478. /**
  92479. * An event triggered when the highlight layer is being blurred.
  92480. */
  92481. _this.onBeforeBlurObservable = new BABYLON.Observable();
  92482. /**
  92483. * An event triggered when the highlight layer has been blurred.
  92484. */
  92485. _this.onAfterBlurObservable = new BABYLON.Observable();
  92486. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  92487. _this._meshes = {};
  92488. _this._excludedMeshes = {};
  92489. _this.neutralColor = HighlightLayer.NeutralColor;
  92490. // Warn on stencil
  92491. if (!_this._engine.isStencilEnable) {
  92492. BABYLON.Tools.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new BABYLON.Engine(canvas, antialias, { stencil: true }");
  92493. }
  92494. // Adapt options
  92495. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  92496. // Initialize the layer
  92497. _this._init({
  92498. alphaBlendingMode: _this._options.alphaBlendingMode,
  92499. camera: _this._options.camera,
  92500. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92501. mainTextureRatio: _this._options.mainTextureRatio
  92502. });
  92503. // Do not render as long as no meshes have been added
  92504. _this._shouldRender = false;
  92505. return _this;
  92506. }
  92507. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  92508. /**
  92509. * Gets the horizontal size of the blur.
  92510. */
  92511. get: function () {
  92512. return this._horizontalBlurPostprocess.kernel;
  92513. },
  92514. /**
  92515. * Specifies the horizontal size of the blur.
  92516. */
  92517. set: function (value) {
  92518. this._horizontalBlurPostprocess.kernel = value;
  92519. },
  92520. enumerable: true,
  92521. configurable: true
  92522. });
  92523. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  92524. /**
  92525. * Gets the vertical size of the blur.
  92526. */
  92527. get: function () {
  92528. return this._verticalBlurPostprocess.kernel;
  92529. },
  92530. /**
  92531. * Specifies the vertical size of the blur.
  92532. */
  92533. set: function (value) {
  92534. this._verticalBlurPostprocess.kernel = value;
  92535. },
  92536. enumerable: true,
  92537. configurable: true
  92538. });
  92539. /**
  92540. * Get the effect name of the layer.
  92541. * @return The effect name
  92542. */
  92543. HighlightLayer.prototype.getEffectName = function () {
  92544. return HighlightLayer.EffectName;
  92545. };
  92546. /**
  92547. * Create the merge effect. This is the shader use to blit the information back
  92548. * to the main canvas at the end of the scene rendering.
  92549. */
  92550. HighlightLayer.prototype._createMergeEffect = function () {
  92551. // Effect
  92552. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  92553. };
  92554. /**
  92555. * Creates the render target textures and post processes used in the highlight layer.
  92556. */
  92557. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  92558. var _this = this;
  92559. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  92560. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  92561. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92562. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92563. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  92564. width: blurTextureWidth,
  92565. height: blurTextureHeight
  92566. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92567. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92568. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92569. this._blurTexture.anisotropicFilteringLevel = 16;
  92570. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  92571. this._blurTexture.renderParticles = false;
  92572. this._blurTexture.ignoreCameraViewport = true;
  92573. this._textures = [this._blurTexture];
  92574. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  92575. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92576. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  92577. effect.setTexture("textureSampler", _this._mainTexture);
  92578. });
  92579. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92580. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  92581. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  92582. });
  92583. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92584. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  92585. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  92586. });
  92587. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  92588. }
  92589. else {
  92590. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  92591. width: blurTextureWidth,
  92592. height: blurTextureHeight
  92593. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92594. this._horizontalBlurPostprocess.width = blurTextureWidth;
  92595. this._horizontalBlurPostprocess.height = blurTextureHeight;
  92596. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  92597. effect.setTexture("textureSampler", _this._mainTexture);
  92598. });
  92599. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  92600. width: blurTextureWidth,
  92601. height: blurTextureHeight
  92602. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92603. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  92604. }
  92605. this._mainTexture.onAfterUnbindObservable.add(function () {
  92606. _this.onBeforeBlurObservable.notifyObservers(_this);
  92607. var internalTexture = _this._blurTexture.getInternalTexture();
  92608. if (internalTexture) {
  92609. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  92610. }
  92611. _this.onAfterBlurObservable.notifyObservers(_this);
  92612. });
  92613. // Prevent autoClear.
  92614. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92615. };
  92616. /**
  92617. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92618. */
  92619. HighlightLayer.prototype.needStencil = function () {
  92620. return true;
  92621. };
  92622. /**
  92623. * Checks for the readiness of the element composing the layer.
  92624. * @param subMesh the mesh to check for
  92625. * @param useInstances specify wether or not to use instances to render the mesh
  92626. * @param emissiveTexture the associated emissive texture used to generate the glow
  92627. * @return true if ready otherwise, false
  92628. */
  92629. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  92630. var material = subMesh.getMaterial();
  92631. var mesh = subMesh.getRenderingMesh();
  92632. if (!material || !mesh || !this._meshes) {
  92633. return false;
  92634. }
  92635. var emissiveTexture = null;
  92636. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  92637. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  92638. emissiveTexture = material.emissiveTexture;
  92639. }
  92640. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92641. };
  92642. /**
  92643. * Implementation specific of rendering the generating effect on the main canvas.
  92644. * @param effect The effect used to render through
  92645. */
  92646. HighlightLayer.prototype._internalRender = function (effect) {
  92647. // Texture
  92648. effect.setTexture("textureSampler", this._blurTexture);
  92649. // Cache
  92650. var engine = this._engine;
  92651. var previousStencilBuffer = engine.getStencilBuffer();
  92652. var previousStencilFunction = engine.getStencilFunction();
  92653. var previousStencilMask = engine.getStencilMask();
  92654. var previousStencilOperationPass = engine.getStencilOperationPass();
  92655. var previousStencilOperationFail = engine.getStencilOperationFail();
  92656. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  92657. var previousStencilReference = engine.getStencilFunctionReference();
  92658. // Stencil operations
  92659. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  92660. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  92661. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  92662. // Draw order
  92663. engine.setStencilMask(0x00);
  92664. engine.setStencilBuffer(true);
  92665. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  92666. // 2 passes inner outer
  92667. if (this.outerGlow) {
  92668. effect.setFloat("offset", 0);
  92669. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  92670. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92671. }
  92672. if (this.innerGlow) {
  92673. effect.setFloat("offset", 1);
  92674. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  92675. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92676. }
  92677. // Restore Cache
  92678. engine.setStencilFunction(previousStencilFunction);
  92679. engine.setStencilMask(previousStencilMask);
  92680. engine.setStencilBuffer(previousStencilBuffer);
  92681. engine.setStencilOperationPass(previousStencilOperationPass);
  92682. engine.setStencilOperationFail(previousStencilOperationFail);
  92683. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  92684. engine.setStencilFunctionReference(previousStencilReference);
  92685. };
  92686. /**
  92687. * Returns true if the layer contains information to display, otherwise false.
  92688. */
  92689. HighlightLayer.prototype.shouldRender = function () {
  92690. if (_super.prototype.shouldRender.call(this)) {
  92691. return this._meshes ? true : false;
  92692. }
  92693. return false;
  92694. };
  92695. /**
  92696. * Returns true if the mesh should render, otherwise false.
  92697. * @param mesh The mesh to render
  92698. * @returns true if it should render otherwise false
  92699. */
  92700. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  92701. // Excluded Mesh
  92702. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  92703. return false;
  92704. }
  92705. ;
  92706. return true;
  92707. };
  92708. /**
  92709. * Sets the required values for both the emissive texture and and the main color.
  92710. */
  92711. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92712. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  92713. if (highlightLayerMesh) {
  92714. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  92715. }
  92716. else {
  92717. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92718. }
  92719. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  92720. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92721. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  92722. }
  92723. else {
  92724. this._emissiveTextureAndColor.texture = null;
  92725. }
  92726. };
  92727. /**
  92728. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  92729. * @param mesh The mesh to exclude from the highlight layer
  92730. */
  92731. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  92732. if (!this._excludedMeshes) {
  92733. return;
  92734. }
  92735. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92736. if (!meshExcluded) {
  92737. this._excludedMeshes[mesh.uniqueId] = {
  92738. mesh: mesh,
  92739. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  92740. mesh.getEngine().setStencilBuffer(false);
  92741. }),
  92742. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  92743. mesh.getEngine().setStencilBuffer(true);
  92744. }),
  92745. };
  92746. }
  92747. };
  92748. /**
  92749. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  92750. * @param mesh The mesh to highlight
  92751. */
  92752. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  92753. if (!this._excludedMeshes) {
  92754. return;
  92755. }
  92756. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92757. if (meshExcluded) {
  92758. if (meshExcluded.beforeRender) {
  92759. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  92760. }
  92761. if (meshExcluded.afterRender) {
  92762. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  92763. }
  92764. }
  92765. this._excludedMeshes[mesh.uniqueId] = null;
  92766. };
  92767. /**
  92768. * Determine if a given mesh will be highlighted by the current HighlightLayer
  92769. * @param mesh mesh to test
  92770. * @returns true if the mesh will be highlighted by the current HighlightLayer
  92771. */
  92772. HighlightLayer.prototype.hasMesh = function (mesh) {
  92773. if (!this._meshes) {
  92774. return false;
  92775. }
  92776. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  92777. };
  92778. /**
  92779. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  92780. * @param mesh The mesh to highlight
  92781. * @param color The color of the highlight
  92782. * @param glowEmissiveOnly Extract the glow from the emissive texture
  92783. */
  92784. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  92785. var _this = this;
  92786. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  92787. if (!this._meshes) {
  92788. return;
  92789. }
  92790. var meshHighlight = this._meshes[mesh.uniqueId];
  92791. if (meshHighlight) {
  92792. meshHighlight.color = color;
  92793. }
  92794. else {
  92795. this._meshes[mesh.uniqueId] = {
  92796. mesh: mesh,
  92797. color: color,
  92798. // Lambda required for capture due to Observable this context
  92799. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  92800. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  92801. _this._defaultStencilReference(mesh);
  92802. }
  92803. else {
  92804. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  92805. }
  92806. }),
  92807. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  92808. glowEmissiveOnly: glowEmissiveOnly
  92809. };
  92810. }
  92811. this._shouldRender = true;
  92812. };
  92813. /**
  92814. * Remove a mesh from the highlight layer in order to make it stop glowing.
  92815. * @param mesh The mesh to highlight
  92816. */
  92817. HighlightLayer.prototype.removeMesh = function (mesh) {
  92818. if (!this._meshes) {
  92819. return;
  92820. }
  92821. var meshHighlight = this._meshes[mesh.uniqueId];
  92822. if (meshHighlight) {
  92823. if (meshHighlight.observerHighlight) {
  92824. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92825. }
  92826. if (meshHighlight.observerDefault) {
  92827. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92828. }
  92829. delete this._meshes[mesh.uniqueId];
  92830. }
  92831. this._shouldRender = false;
  92832. for (var meshHighlightToCheck in this._meshes) {
  92833. if (this._meshes[meshHighlightToCheck]) {
  92834. this._shouldRender = true;
  92835. break;
  92836. }
  92837. }
  92838. };
  92839. /**
  92840. * Force the stencil to the normal expected value for none glowing parts
  92841. */
  92842. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  92843. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  92844. };
  92845. /**
  92846. * Free any resources and references associated to a mesh.
  92847. * Internal use
  92848. * @param mesh The mesh to free.
  92849. */
  92850. HighlightLayer.prototype._disposeMesh = function (mesh) {
  92851. this.removeMesh(mesh);
  92852. this.removeExcludedMesh(mesh);
  92853. };
  92854. /**
  92855. * Dispose the highlight layer and free resources.
  92856. */
  92857. HighlightLayer.prototype.dispose = function () {
  92858. if (this._meshes) {
  92859. // Clean mesh references
  92860. for (var id in this._meshes) {
  92861. var meshHighlight = this._meshes[id];
  92862. if (meshHighlight && meshHighlight.mesh) {
  92863. if (meshHighlight.observerHighlight) {
  92864. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92865. }
  92866. if (meshHighlight.observerDefault) {
  92867. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92868. }
  92869. }
  92870. }
  92871. this._meshes = null;
  92872. }
  92873. if (this._excludedMeshes) {
  92874. for (var id in this._excludedMeshes) {
  92875. var meshHighlight = this._excludedMeshes[id];
  92876. if (meshHighlight) {
  92877. if (meshHighlight.beforeRender) {
  92878. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  92879. }
  92880. if (meshHighlight.afterRender) {
  92881. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  92882. }
  92883. }
  92884. }
  92885. this._excludedMeshes = null;
  92886. }
  92887. _super.prototype.dispose.call(this);
  92888. };
  92889. /**
  92890. * Gets the class name of the effect layer
  92891. * @returns the string with the class name of the effect layer
  92892. */
  92893. HighlightLayer.prototype.getClassName = function () {
  92894. return "HighlightLayer";
  92895. };
  92896. /**
  92897. * Serializes this Highlight layer
  92898. * @returns a serialized Highlight layer object
  92899. */
  92900. HighlightLayer.prototype.serialize = function () {
  92901. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92902. serializationObject.customType = "BABYLON.HighlightLayer";
  92903. // Highlighted meshes
  92904. serializationObject.meshes = [];
  92905. if (this._meshes) {
  92906. for (var m in this._meshes) {
  92907. var mesh = this._meshes[m];
  92908. if (mesh) {
  92909. serializationObject.meshes.push({
  92910. glowEmissiveOnly: mesh.glowEmissiveOnly,
  92911. color: mesh.color.asArray(),
  92912. meshId: mesh.mesh.id
  92913. });
  92914. }
  92915. }
  92916. }
  92917. // Excluded meshes
  92918. serializationObject.excludedMeshes = [];
  92919. if (this._excludedMeshes) {
  92920. for (var e in this._excludedMeshes) {
  92921. var excludedMesh = this._excludedMeshes[e];
  92922. if (excludedMesh) {
  92923. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  92924. }
  92925. }
  92926. }
  92927. return serializationObject;
  92928. };
  92929. /**
  92930. * Creates a Highlight layer from parsed Highlight layer data
  92931. * @param parsedHightlightLayer defines the Highlight layer data
  92932. * @param scene defines the current scene
  92933. * @param rootUrl defines the root URL containing the Highlight layer information
  92934. * @returns a parsed Highlight layer
  92935. */
  92936. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  92937. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  92938. var index;
  92939. // Excluded meshes
  92940. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  92941. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  92942. if (mesh) {
  92943. hl.addExcludedMesh(mesh);
  92944. }
  92945. }
  92946. // Included meshes
  92947. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  92948. var highlightedMesh = parsedHightlightLayer.meshes[index];
  92949. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  92950. if (mesh) {
  92951. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  92952. }
  92953. }
  92954. return hl;
  92955. };
  92956. /**
  92957. * Effect Name of the highlight layer.
  92958. */
  92959. HighlightLayer.EffectName = "HighlightLayer";
  92960. /**
  92961. * The neutral color used during the preparation of the glow effect.
  92962. * This is black by default as the blend operation is a blend operation.
  92963. */
  92964. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  92965. /**
  92966. * Stencil value used for glowing meshes.
  92967. */
  92968. HighlightLayer.GlowingMeshStencilReference = 0x02;
  92969. /**
  92970. * Stencil value used for the other meshes in the scene.
  92971. */
  92972. HighlightLayer.NormalMeshStencilReference = 0x01;
  92973. __decorate([
  92974. BABYLON.serialize()
  92975. ], HighlightLayer.prototype, "innerGlow", void 0);
  92976. __decorate([
  92977. BABYLON.serialize()
  92978. ], HighlightLayer.prototype, "outerGlow", void 0);
  92979. __decorate([
  92980. BABYLON.serialize()
  92981. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  92982. __decorate([
  92983. BABYLON.serialize()
  92984. ], HighlightLayer.prototype, "blurVerticalSize", null);
  92985. __decorate([
  92986. BABYLON.serialize("options")
  92987. ], HighlightLayer.prototype, "_options", void 0);
  92988. return HighlightLayer;
  92989. }(BABYLON.EffectLayer));
  92990. BABYLON.HighlightLayer = HighlightLayer;
  92991. })(BABYLON || (BABYLON = {}));
  92992. //# sourceMappingURL=babylon.highlightLayer.js.map
  92993. var BABYLON;
  92994. (function (BABYLON) {
  92995. /**
  92996. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  92997. *
  92998. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92999. * glowy meshes to your scene.
  93000. *
  93001. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  93002. */
  93003. var GlowLayer = /** @class */ (function (_super) {
  93004. __extends(GlowLayer, _super);
  93005. /**
  93006. * Instantiates a new glow Layer and references it to the scene.
  93007. * @param name The name of the layer
  93008. * @param scene The scene to use the layer in
  93009. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  93010. */
  93011. function GlowLayer(name, scene, options) {
  93012. var _this = _super.call(this, name, scene) || this;
  93013. _this._intensity = 1.0;
  93014. _this._includedOnlyMeshes = [];
  93015. _this._excludedMeshes = [];
  93016. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  93017. // Adapt options
  93018. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  93019. // Initialize the layer
  93020. _this._init({
  93021. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  93022. camera: _this._options.camera,
  93023. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  93024. mainTextureRatio: _this._options.mainTextureRatio
  93025. });
  93026. return _this;
  93027. }
  93028. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  93029. /**
  93030. * Gets the kernel size of the blur.
  93031. */
  93032. get: function () {
  93033. return this._horizontalBlurPostprocess1.kernel;
  93034. },
  93035. /**
  93036. * Sets the kernel size of the blur.
  93037. */
  93038. set: function (value) {
  93039. this._horizontalBlurPostprocess1.kernel = value;
  93040. this._verticalBlurPostprocess1.kernel = value;
  93041. this._horizontalBlurPostprocess2.kernel = value;
  93042. this._verticalBlurPostprocess2.kernel = value;
  93043. },
  93044. enumerable: true,
  93045. configurable: true
  93046. });
  93047. Object.defineProperty(GlowLayer.prototype, "intensity", {
  93048. /**
  93049. * Gets the glow intensity.
  93050. */
  93051. get: function () {
  93052. return this._intensity;
  93053. },
  93054. /**
  93055. * Sets the glow intensity.
  93056. */
  93057. set: function (value) {
  93058. this._intensity = value;
  93059. },
  93060. enumerable: true,
  93061. configurable: true
  93062. });
  93063. /**
  93064. * Get the effect name of the layer.
  93065. * @return The effect name
  93066. */
  93067. GlowLayer.prototype.getEffectName = function () {
  93068. return GlowLayer.EffectName;
  93069. };
  93070. /**
  93071. * Create the merge effect. This is the shader use to blit the information back
  93072. * to the main canvas at the end of the scene rendering.
  93073. */
  93074. GlowLayer.prototype._createMergeEffect = function () {
  93075. // Effect
  93076. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  93077. };
  93078. /**
  93079. * Creates the render target textures and post processes used in the glow layer.
  93080. */
  93081. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  93082. var _this = this;
  93083. var blurTextureWidth = this._mainTextureDesiredSize.width;
  93084. var blurTextureHeight = this._mainTextureDesiredSize.height;
  93085. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  93086. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  93087. var textureType = 0;
  93088. if (this._engine.getCaps().textureHalfFloatRender) {
  93089. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  93090. }
  93091. else {
  93092. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93093. }
  93094. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  93095. width: blurTextureWidth,
  93096. height: blurTextureHeight
  93097. }, this._scene, false, true, textureType);
  93098. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93099. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93100. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93101. this._blurTexture1.renderParticles = false;
  93102. this._blurTexture1.ignoreCameraViewport = true;
  93103. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  93104. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  93105. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  93106. width: blurTextureWidth2,
  93107. height: blurTextureHeight2
  93108. }, this._scene, false, true, textureType);
  93109. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93110. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93111. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93112. this._blurTexture2.renderParticles = false;
  93113. this._blurTexture2.ignoreCameraViewport = true;
  93114. this._textures = [this._blurTexture1, this._blurTexture2];
  93115. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  93116. width: blurTextureWidth,
  93117. height: blurTextureHeight
  93118. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93119. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  93120. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  93121. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  93122. effect.setTexture("textureSampler", _this._mainTexture);
  93123. });
  93124. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  93125. width: blurTextureWidth,
  93126. height: blurTextureHeight
  93127. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93128. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  93129. width: blurTextureWidth2,
  93130. height: blurTextureHeight2
  93131. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93132. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  93133. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  93134. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  93135. effect.setTexture("textureSampler", _this._blurTexture1);
  93136. });
  93137. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  93138. width: blurTextureWidth2,
  93139. height: blurTextureHeight2
  93140. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93141. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  93142. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  93143. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  93144. this._mainTexture.samples = this._options.mainTextureSamples;
  93145. this._mainTexture.onAfterUnbindObservable.add(function () {
  93146. var internalTexture = _this._blurTexture1.getInternalTexture();
  93147. if (internalTexture) {
  93148. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  93149. internalTexture = _this._blurTexture2.getInternalTexture();
  93150. if (internalTexture) {
  93151. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  93152. }
  93153. }
  93154. });
  93155. // Prevent autoClear.
  93156. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  93157. };
  93158. /**
  93159. * Checks for the readiness of the element composing the layer.
  93160. * @param subMesh the mesh to check for
  93161. * @param useInstances specify wether or not to use instances to render the mesh
  93162. * @param emissiveTexture the associated emissive texture used to generate the glow
  93163. * @return true if ready otherwise, false
  93164. */
  93165. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  93166. var material = subMesh.getMaterial();
  93167. var mesh = subMesh.getRenderingMesh();
  93168. if (!material || !mesh) {
  93169. return false;
  93170. }
  93171. var emissiveTexture = material.emissiveTexture;
  93172. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  93173. };
  93174. /**
  93175. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  93176. */
  93177. GlowLayer.prototype.needStencil = function () {
  93178. return false;
  93179. };
  93180. /**
  93181. * Implementation specific of rendering the generating effect on the main canvas.
  93182. * @param effect The effect used to render through
  93183. */
  93184. GlowLayer.prototype._internalRender = function (effect) {
  93185. // Texture
  93186. effect.setTexture("textureSampler", this._blurTexture1);
  93187. effect.setTexture("textureSampler2", this._blurTexture2);
  93188. effect.setFloat("offset", this._intensity);
  93189. // Cache
  93190. var engine = this._engine;
  93191. var previousStencilBuffer = engine.getStencilBuffer();
  93192. // Draw order
  93193. engine.setStencilBuffer(false);
  93194. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93195. // Draw order
  93196. engine.setStencilBuffer(previousStencilBuffer);
  93197. };
  93198. /**
  93199. * Sets the required values for both the emissive texture and and the main color.
  93200. */
  93201. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  93202. var textureLevel = 1.0;
  93203. if (this.customEmissiveTextureSelector) {
  93204. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  93205. }
  93206. else {
  93207. if (material) {
  93208. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  93209. if (this._emissiveTextureAndColor.texture) {
  93210. textureLevel = this._emissiveTextureAndColor.texture.level;
  93211. }
  93212. }
  93213. else {
  93214. this._emissiveTextureAndColor.texture = null;
  93215. }
  93216. }
  93217. if (this.customEmissiveColorSelector) {
  93218. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  93219. }
  93220. else {
  93221. if (material.emissiveColor) {
  93222. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  93223. }
  93224. else {
  93225. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  93226. }
  93227. }
  93228. };
  93229. /**
  93230. * Returns true if the mesh should render, otherwise false.
  93231. * @param mesh The mesh to render
  93232. * @returns true if it should render otherwise false
  93233. */
  93234. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  93235. return this.hasMesh(mesh);
  93236. };
  93237. /**
  93238. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  93239. * @param mesh The mesh to exclude from the glow layer
  93240. */
  93241. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  93242. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  93243. this._excludedMeshes.push(mesh.uniqueId);
  93244. }
  93245. };
  93246. /**
  93247. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  93248. * @param mesh The mesh to remove
  93249. */
  93250. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  93251. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  93252. if (index !== -1) {
  93253. this._excludedMeshes.splice(index, 1);
  93254. }
  93255. };
  93256. /**
  93257. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  93258. * @param mesh The mesh to include in the glow layer
  93259. */
  93260. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  93261. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  93262. this._includedOnlyMeshes.push(mesh.uniqueId);
  93263. }
  93264. };
  93265. /**
  93266. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  93267. * @param mesh The mesh to remove
  93268. */
  93269. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  93270. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  93271. if (index !== -1) {
  93272. this._includedOnlyMeshes.splice(index, 1);
  93273. }
  93274. };
  93275. /**
  93276. * Determine if a given mesh will be used in the glow layer
  93277. * @param mesh The mesh to test
  93278. * @returns true if the mesh will be highlighted by the current glow layer
  93279. */
  93280. GlowLayer.prototype.hasMesh = function (mesh) {
  93281. // Included Mesh
  93282. if (this._includedOnlyMeshes.length) {
  93283. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  93284. }
  93285. ;
  93286. // Excluded Mesh
  93287. if (this._excludedMeshes.length) {
  93288. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  93289. }
  93290. ;
  93291. return true;
  93292. };
  93293. /**
  93294. * Free any resources and references associated to a mesh.
  93295. * Internal use
  93296. * @param mesh The mesh to free.
  93297. */
  93298. GlowLayer.prototype._disposeMesh = function (mesh) {
  93299. this.removeIncludedOnlyMesh(mesh);
  93300. this.removeExcludedMesh(mesh);
  93301. };
  93302. /**
  93303. * Gets the class name of the effect layer
  93304. * @returns the string with the class name of the effect layer
  93305. */
  93306. GlowLayer.prototype.getClassName = function () {
  93307. return "GlowLayer";
  93308. };
  93309. /**
  93310. * Serializes this glow layer
  93311. * @returns a serialized glow layer object
  93312. */
  93313. GlowLayer.prototype.serialize = function () {
  93314. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  93315. serializationObject.customType = "BABYLON.GlowLayer";
  93316. var index;
  93317. // Included meshes
  93318. serializationObject.includedMeshes = [];
  93319. if (this._includedOnlyMeshes.length) {
  93320. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  93321. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  93322. if (mesh) {
  93323. serializationObject.includedMeshes.push(mesh.id);
  93324. }
  93325. }
  93326. }
  93327. // Excluded meshes
  93328. serializationObject.excludedMeshes = [];
  93329. if (this._excludedMeshes.length) {
  93330. for (index = 0; index < this._excludedMeshes.length; index++) {
  93331. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  93332. if (mesh) {
  93333. serializationObject.excludedMeshes.push(mesh.id);
  93334. }
  93335. }
  93336. }
  93337. return serializationObject;
  93338. };
  93339. /**
  93340. * Creates a Glow Layer from parsed glow layer data
  93341. * @param parsedGlowLayer defines glow layer data
  93342. * @param scene defines the current scene
  93343. * @param rootUrl defines the root URL containing the glow layer information
  93344. * @returns a parsed Glow Layer
  93345. */
  93346. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  93347. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  93348. var index;
  93349. // Excluded meshes
  93350. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  93351. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  93352. if (mesh) {
  93353. gl.addExcludedMesh(mesh);
  93354. }
  93355. }
  93356. // Included meshes
  93357. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  93358. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  93359. if (mesh) {
  93360. gl.addIncludedOnlyMesh(mesh);
  93361. }
  93362. }
  93363. return gl;
  93364. };
  93365. /**
  93366. * Effect Name of the layer.
  93367. */
  93368. GlowLayer.EffectName = "GlowLayer";
  93369. /**
  93370. * The default blur kernel size used for the glow.
  93371. */
  93372. GlowLayer.DefaultBlurKernelSize = 32;
  93373. /**
  93374. * The default texture size ratio used for the glow.
  93375. */
  93376. GlowLayer.DefaultTextureRatio = 0.5;
  93377. __decorate([
  93378. BABYLON.serialize()
  93379. ], GlowLayer.prototype, "blurKernelSize", null);
  93380. __decorate([
  93381. BABYLON.serialize()
  93382. ], GlowLayer.prototype, "intensity", null);
  93383. __decorate([
  93384. BABYLON.serialize("options")
  93385. ], GlowLayer.prototype, "_options", void 0);
  93386. return GlowLayer;
  93387. }(BABYLON.EffectLayer));
  93388. BABYLON.GlowLayer = GlowLayer;
  93389. })(BABYLON || (BABYLON = {}));
  93390. //# sourceMappingURL=babylon.glowLayer.js.map
  93391. var BABYLON;
  93392. (function (BABYLON) {
  93393. /**
  93394. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  93395. */
  93396. var AssetTaskState;
  93397. (function (AssetTaskState) {
  93398. /**
  93399. * Initialization
  93400. */
  93401. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  93402. /**
  93403. * Running
  93404. */
  93405. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  93406. /**
  93407. * Done
  93408. */
  93409. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  93410. /**
  93411. * Error
  93412. */
  93413. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  93414. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  93415. /**
  93416. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  93417. */
  93418. var AbstractAssetTask = /** @class */ (function () {
  93419. /**
  93420. * Creates a new {BABYLON.AssetsManager}
  93421. * @param name defines the name of the task
  93422. */
  93423. function AbstractAssetTask(
  93424. /**
  93425. * Task name
  93426. */ name) {
  93427. this.name = name;
  93428. this._isCompleted = false;
  93429. this._taskState = AssetTaskState.INIT;
  93430. }
  93431. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  93432. /**
  93433. * Get if the task is completed
  93434. */
  93435. get: function () {
  93436. return this._isCompleted;
  93437. },
  93438. enumerable: true,
  93439. configurable: true
  93440. });
  93441. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  93442. /**
  93443. * Gets the current state of the task
  93444. */
  93445. get: function () {
  93446. return this._taskState;
  93447. },
  93448. enumerable: true,
  93449. configurable: true
  93450. });
  93451. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  93452. /**
  93453. * Gets the current error object (if task is in error)
  93454. */
  93455. get: function () {
  93456. return this._errorObject;
  93457. },
  93458. enumerable: true,
  93459. configurable: true
  93460. });
  93461. /**
  93462. * Internal only
  93463. * @hidden
  93464. */
  93465. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  93466. if (this._errorObject) {
  93467. return;
  93468. }
  93469. this._errorObject = {
  93470. message: message,
  93471. exception: exception
  93472. };
  93473. };
  93474. /**
  93475. * Execute the current task
  93476. * @param scene defines the scene where you want your assets to be loaded
  93477. * @param onSuccess is a callback called when the task is successfully executed
  93478. * @param onError is a callback called if an error occurs
  93479. */
  93480. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93481. var _this = this;
  93482. this._taskState = AssetTaskState.RUNNING;
  93483. this.runTask(scene, function () {
  93484. _this.onDoneCallback(onSuccess, onError);
  93485. }, function (msg, exception) {
  93486. _this.onErrorCallback(onError, msg, exception);
  93487. });
  93488. };
  93489. /**
  93490. * Execute the current task
  93491. * @param scene defines the scene where you want your assets to be loaded
  93492. * @param onSuccess is a callback called when the task is successfully executed
  93493. * @param onError is a callback called if an error occurs
  93494. */
  93495. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93496. throw new Error("runTask is not implemented");
  93497. };
  93498. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  93499. this._taskState = AssetTaskState.ERROR;
  93500. this._errorObject = {
  93501. message: message,
  93502. exception: exception
  93503. };
  93504. if (this.onError) {
  93505. this.onError(this, message, exception);
  93506. }
  93507. onError();
  93508. };
  93509. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  93510. try {
  93511. this._taskState = AssetTaskState.DONE;
  93512. this._isCompleted = true;
  93513. if (this.onSuccess) {
  93514. this.onSuccess(this);
  93515. }
  93516. onSuccess();
  93517. }
  93518. catch (e) {
  93519. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  93520. }
  93521. };
  93522. return AbstractAssetTask;
  93523. }());
  93524. BABYLON.AbstractAssetTask = AbstractAssetTask;
  93525. /**
  93526. * Class used to share progress information about assets loading
  93527. */
  93528. var AssetsProgressEvent = /** @class */ (function () {
  93529. /**
  93530. * Creates a {BABYLON.AssetsProgressEvent}
  93531. * @param remainingCount defines the number of remaining tasks to process
  93532. * @param totalCount defines the total number of tasks
  93533. * @param task defines the task that was just processed
  93534. */
  93535. function AssetsProgressEvent(remainingCount, totalCount, task) {
  93536. this.remainingCount = remainingCount;
  93537. this.totalCount = totalCount;
  93538. this.task = task;
  93539. }
  93540. return AssetsProgressEvent;
  93541. }());
  93542. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  93543. /**
  93544. * Define a task used by {BABYLON.AssetsManager} to load meshes
  93545. */
  93546. var MeshAssetTask = /** @class */ (function (_super) {
  93547. __extends(MeshAssetTask, _super);
  93548. /**
  93549. * Creates a new {BABYLON.MeshAssetTask}
  93550. * @param name defines the name of the task
  93551. * @param meshesNames defines the list of mesh's names you want to load
  93552. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  93553. * @param sceneFilename defines the filename of the scene to load from
  93554. */
  93555. function MeshAssetTask(
  93556. /**
  93557. * Defines the name of the task
  93558. */
  93559. name,
  93560. /**
  93561. * Defines the list of mesh's names you want to load
  93562. */
  93563. meshesNames,
  93564. /**
  93565. * Defines the root url to use as a base to load your meshes and associated resources
  93566. */
  93567. rootUrl,
  93568. /**
  93569. * Defines the filename of the scene to load from
  93570. */
  93571. sceneFilename) {
  93572. var _this = _super.call(this, name) || this;
  93573. _this.name = name;
  93574. _this.meshesNames = meshesNames;
  93575. _this.rootUrl = rootUrl;
  93576. _this.sceneFilename = sceneFilename;
  93577. return _this;
  93578. }
  93579. /**
  93580. * Execute the current task
  93581. * @param scene defines the scene where you want your assets to be loaded
  93582. * @param onSuccess is a callback called when the task is successfully executed
  93583. * @param onError is a callback called if an error occurs
  93584. */
  93585. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93586. var _this = this;
  93587. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  93588. _this.loadedMeshes = meshes;
  93589. _this.loadedParticleSystems = particleSystems;
  93590. _this.loadedSkeletons = skeletons;
  93591. onSuccess();
  93592. }, null, function (scene, message, exception) {
  93593. onError(message, exception);
  93594. });
  93595. };
  93596. return MeshAssetTask;
  93597. }(AbstractAssetTask));
  93598. BABYLON.MeshAssetTask = MeshAssetTask;
  93599. /**
  93600. * Define a task used by {BABYLON.AssetsManager} to load text content
  93601. */
  93602. var TextFileAssetTask = /** @class */ (function (_super) {
  93603. __extends(TextFileAssetTask, _super);
  93604. /**
  93605. * Creates a new TextFileAssetTask object
  93606. * @param name defines the name of the task
  93607. * @param url defines the location of the file to load
  93608. */
  93609. function TextFileAssetTask(
  93610. /**
  93611. * Defines the name of the task
  93612. */
  93613. name,
  93614. /**
  93615. * Defines the location of the file to load
  93616. */
  93617. url) {
  93618. var _this = _super.call(this, name) || this;
  93619. _this.name = name;
  93620. _this.url = url;
  93621. return _this;
  93622. }
  93623. /**
  93624. * Execute the current task
  93625. * @param scene defines the scene where you want your assets to be loaded
  93626. * @param onSuccess is a callback called when the task is successfully executed
  93627. * @param onError is a callback called if an error occurs
  93628. */
  93629. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93630. var _this = this;
  93631. scene._loadFile(this.url, function (data) {
  93632. _this.text = data;
  93633. onSuccess();
  93634. }, undefined, false, false, function (request, exception) {
  93635. if (request) {
  93636. onError(request.status + " " + request.statusText, exception);
  93637. }
  93638. });
  93639. };
  93640. return TextFileAssetTask;
  93641. }(AbstractAssetTask));
  93642. BABYLON.TextFileAssetTask = TextFileAssetTask;
  93643. /**
  93644. * Define a task used by {BABYLON.AssetsManager} to load binary data
  93645. */
  93646. var BinaryFileAssetTask = /** @class */ (function (_super) {
  93647. __extends(BinaryFileAssetTask, _super);
  93648. /**
  93649. * Creates a new BinaryFileAssetTask object
  93650. * @param name defines the name of the new task
  93651. * @param url defines the location of the file to load
  93652. */
  93653. function BinaryFileAssetTask(
  93654. /**
  93655. * Defines the name of the task
  93656. */
  93657. name,
  93658. /**
  93659. * Defines the location of the file to load
  93660. */
  93661. url) {
  93662. var _this = _super.call(this, name) || this;
  93663. _this.name = name;
  93664. _this.url = url;
  93665. return _this;
  93666. }
  93667. /**
  93668. * Execute the current task
  93669. * @param scene defines the scene where you want your assets to be loaded
  93670. * @param onSuccess is a callback called when the task is successfully executed
  93671. * @param onError is a callback called if an error occurs
  93672. */
  93673. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93674. var _this = this;
  93675. scene._loadFile(this.url, function (data) {
  93676. _this.data = data;
  93677. onSuccess();
  93678. }, undefined, true, true, function (request, exception) {
  93679. if (request) {
  93680. onError(request.status + " " + request.statusText, exception);
  93681. }
  93682. });
  93683. };
  93684. return BinaryFileAssetTask;
  93685. }(AbstractAssetTask));
  93686. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  93687. /**
  93688. * Define a task used by {BABYLON.AssetsManager} to load images
  93689. */
  93690. var ImageAssetTask = /** @class */ (function (_super) {
  93691. __extends(ImageAssetTask, _super);
  93692. /**
  93693. * Creates a new ImageAssetTask
  93694. * @param name defines the name of the task
  93695. * @param url defines the location of the image to load
  93696. */
  93697. function ImageAssetTask(
  93698. /**
  93699. * Defines the name of the task
  93700. */
  93701. name,
  93702. /**
  93703. * Defines the location of the image to load
  93704. */
  93705. url) {
  93706. var _this = _super.call(this, name) || this;
  93707. _this.name = name;
  93708. _this.url = url;
  93709. return _this;
  93710. }
  93711. /**
  93712. * Execute the current task
  93713. * @param scene defines the scene where you want your assets to be loaded
  93714. * @param onSuccess is a callback called when the task is successfully executed
  93715. * @param onError is a callback called if an error occurs
  93716. */
  93717. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93718. var _this = this;
  93719. var img = new Image();
  93720. BABYLON.Tools.SetCorsBehavior(this.url, img);
  93721. img.onload = function () {
  93722. _this.image = img;
  93723. onSuccess();
  93724. };
  93725. img.onerror = function (err) {
  93726. onError("Error loading image", err);
  93727. };
  93728. img.src = this.url;
  93729. };
  93730. return ImageAssetTask;
  93731. }(AbstractAssetTask));
  93732. BABYLON.ImageAssetTask = ImageAssetTask;
  93733. /**
  93734. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  93735. */
  93736. var TextureAssetTask = /** @class */ (function (_super) {
  93737. __extends(TextureAssetTask, _super);
  93738. /**
  93739. * Creates a new TextureAssetTask object
  93740. * @param name defines the name of the task
  93741. * @param url defines the location of the file to load
  93742. * @param noMipmap defines if mipmap should not be generated (default is false)
  93743. * @param invertY defines if texture must be inverted on Y axis (default is false)
  93744. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93745. */
  93746. function TextureAssetTask(
  93747. /**
  93748. * Defines the name of the task
  93749. */
  93750. name,
  93751. /**
  93752. * Defines the location of the file to load
  93753. */
  93754. url,
  93755. /**
  93756. * Defines if mipmap should not be generated (default is false)
  93757. */
  93758. noMipmap,
  93759. /**
  93760. * Defines if texture must be inverted on Y axis (default is false)
  93761. */
  93762. invertY,
  93763. /**
  93764. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93765. */
  93766. samplingMode) {
  93767. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93768. var _this = _super.call(this, name) || this;
  93769. _this.name = name;
  93770. _this.url = url;
  93771. _this.noMipmap = noMipmap;
  93772. _this.invertY = invertY;
  93773. _this.samplingMode = samplingMode;
  93774. return _this;
  93775. }
  93776. /**
  93777. * Execute the current task
  93778. * @param scene defines the scene where you want your assets to be loaded
  93779. * @param onSuccess is a callback called when the task is successfully executed
  93780. * @param onError is a callback called if an error occurs
  93781. */
  93782. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93783. var onload = function () {
  93784. onSuccess();
  93785. };
  93786. var onerror = function (message, exception) {
  93787. onError(message, exception);
  93788. };
  93789. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  93790. };
  93791. return TextureAssetTask;
  93792. }(AbstractAssetTask));
  93793. BABYLON.TextureAssetTask = TextureAssetTask;
  93794. /**
  93795. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  93796. */
  93797. var CubeTextureAssetTask = /** @class */ (function (_super) {
  93798. __extends(CubeTextureAssetTask, _super);
  93799. /**
  93800. * Creates a new CubeTextureAssetTask
  93801. * @param name defines the name of the task
  93802. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93803. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93804. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93805. * @param files defines the explicit list of files (undefined by default)
  93806. */
  93807. function CubeTextureAssetTask(
  93808. /**
  93809. * Defines the name of the task
  93810. */
  93811. name,
  93812. /**
  93813. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93814. */
  93815. url,
  93816. /**
  93817. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93818. */
  93819. extensions,
  93820. /**
  93821. * Defines if mipmaps should not be generated (default is false)
  93822. */
  93823. noMipmap,
  93824. /**
  93825. * Defines the explicit list of files (undefined by default)
  93826. */
  93827. files) {
  93828. var _this = _super.call(this, name) || this;
  93829. _this.name = name;
  93830. _this.url = url;
  93831. _this.extensions = extensions;
  93832. _this.noMipmap = noMipmap;
  93833. _this.files = files;
  93834. return _this;
  93835. }
  93836. /**
  93837. * Execute the current task
  93838. * @param scene defines the scene where you want your assets to be loaded
  93839. * @param onSuccess is a callback called when the task is successfully executed
  93840. * @param onError is a callback called if an error occurs
  93841. */
  93842. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93843. var onload = function () {
  93844. onSuccess();
  93845. };
  93846. var onerror = function (message, exception) {
  93847. onError(message, exception);
  93848. };
  93849. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  93850. };
  93851. return CubeTextureAssetTask;
  93852. }(AbstractAssetTask));
  93853. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  93854. /**
  93855. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  93856. */
  93857. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  93858. __extends(HDRCubeTextureAssetTask, _super);
  93859. /**
  93860. * Creates a new HDRCubeTextureAssetTask object
  93861. * @param name defines the name of the task
  93862. * @param url defines the location of the file to load
  93863. * @param size defines the desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  93864. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93865. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93866. * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  93867. * @param reserved Internal use only
  93868. */
  93869. function HDRCubeTextureAssetTask(
  93870. /**
  93871. * Defines the name of the task
  93872. */
  93873. name,
  93874. /**
  93875. * Defines the location of the file to load
  93876. */
  93877. url,
  93878. /**
  93879. * Defines the desired size (the more it increases the longer the generation will be)
  93880. */
  93881. size,
  93882. /**
  93883. * Defines if mipmaps should not be generated (default is false)
  93884. */
  93885. noMipmap,
  93886. /**
  93887. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93888. */
  93889. generateHarmonics,
  93890. /**
  93891. * Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  93892. */
  93893. gammaSpace,
  93894. /**
  93895. * Internal Use Only
  93896. */
  93897. reserved) {
  93898. if (noMipmap === void 0) { noMipmap = false; }
  93899. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93900. if (gammaSpace === void 0) { gammaSpace = false; }
  93901. if (reserved === void 0) { reserved = false; }
  93902. var _this = _super.call(this, name) || this;
  93903. _this.name = name;
  93904. _this.url = url;
  93905. _this.size = size;
  93906. _this.noMipmap = noMipmap;
  93907. _this.generateHarmonics = generateHarmonics;
  93908. _this.gammaSpace = gammaSpace;
  93909. _this.reserved = reserved;
  93910. return _this;
  93911. }
  93912. /**
  93913. * Execute the current task
  93914. * @param scene defines the scene where you want your assets to be loaded
  93915. * @param onSuccess is a callback called when the task is successfully executed
  93916. * @param onError is a callback called if an error occurs
  93917. */
  93918. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93919. var onload = function () {
  93920. onSuccess();
  93921. };
  93922. var onerror = function (message, exception) {
  93923. onError(message, exception);
  93924. };
  93925. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  93926. };
  93927. return HDRCubeTextureAssetTask;
  93928. }(AbstractAssetTask));
  93929. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  93930. /**
  93931. * This class can be used to easily import assets into a scene
  93932. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  93933. */
  93934. var AssetsManager = /** @class */ (function () {
  93935. /**
  93936. * Creates a new AssetsManager
  93937. * @param scene defines the scene to work on
  93938. */
  93939. function AssetsManager(scene) {
  93940. this._isLoading = false;
  93941. this._tasks = new Array();
  93942. this._waitingTasksCount = 0;
  93943. this._totalTasksCount = 0;
  93944. /**
  93945. * Observable called when all tasks are processed
  93946. */
  93947. this.onTaskSuccessObservable = new BABYLON.Observable();
  93948. /**
  93949. * Observable called when a task had an error
  93950. */
  93951. this.onTaskErrorObservable = new BABYLON.Observable();
  93952. /**
  93953. * Observable called when a task is successful
  93954. */
  93955. this.onTasksDoneObservable = new BABYLON.Observable();
  93956. /**
  93957. * Observable called when a task is done (whatever the result is)
  93958. */
  93959. this.onProgressObservable = new BABYLON.Observable();
  93960. /**
  93961. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  93962. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  93963. */
  93964. this.useDefaultLoadingScreen = true;
  93965. this._scene = scene;
  93966. }
  93967. /**
  93968. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  93969. * @param taskName defines the name of the new task
  93970. * @param meshesNames defines the name of meshes to load
  93971. * @param rootUrl defines the root url to use to locate files
  93972. * @param sceneFilename defines the filename of the scene file
  93973. * @returns a new {BABYLON.MeshAssetTask} object
  93974. */
  93975. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  93976. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  93977. this._tasks.push(task);
  93978. return task;
  93979. };
  93980. /**
  93981. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  93982. * @param taskName defines the name of the new task
  93983. * @param url defines the url of the file to load
  93984. * @returns a new {BABYLON.TextFileAssetTask} object
  93985. */
  93986. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  93987. var task = new TextFileAssetTask(taskName, url);
  93988. this._tasks.push(task);
  93989. return task;
  93990. };
  93991. /**
  93992. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  93993. * @param taskName defines the name of the new task
  93994. * @param url defines the url of the file to load
  93995. * @returns a new {BABYLON.BinaryFileAssetTask} object
  93996. */
  93997. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  93998. var task = new BinaryFileAssetTask(taskName, url);
  93999. this._tasks.push(task);
  94000. return task;
  94001. };
  94002. /**
  94003. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  94004. * @param taskName defines the name of the new task
  94005. * @param url defines the url of the file to load
  94006. * @returns a new {BABYLON.ImageAssetTask} object
  94007. */
  94008. AssetsManager.prototype.addImageTask = function (taskName, url) {
  94009. var task = new ImageAssetTask(taskName, url);
  94010. this._tasks.push(task);
  94011. return task;
  94012. };
  94013. /**
  94014. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  94015. * @param taskName defines the name of the new task
  94016. * @param url defines the url of the file to load
  94017. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  94018. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  94019. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  94020. * @returns a new {BABYLON.TextureAssetTask} object
  94021. */
  94022. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  94023. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  94024. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  94025. this._tasks.push(task);
  94026. return task;
  94027. };
  94028. /**
  94029. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  94030. * @param taskName defines the name of the new task
  94031. * @param url defines the url of the file to load
  94032. * @param extensions defines the extension to use to load the cube map (can be null)
  94033. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  94034. * @param files defines the list of files to load (can be null)
  94035. * @returns a new {BABYLON.CubeTextureAssetTask} object
  94036. */
  94037. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  94038. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  94039. this._tasks.push(task);
  94040. return task;
  94041. };
  94042. /**
  94043. *
  94044. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  94045. * @param taskName defines the name of the new task
  94046. * @param url defines the url of the file to load
  94047. * @param size defines the size you want for the cubemap (can be null)
  94048. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  94049. * @param generateHarmonics defines if you want to automatically generate (true by default)
  94050. * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  94051. * @param reserved Internal use only
  94052. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  94053. */
  94054. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  94055. if (noMipmap === void 0) { noMipmap = false; }
  94056. if (generateHarmonics === void 0) { generateHarmonics = true; }
  94057. if (gammaSpace === void 0) { gammaSpace = false; }
  94058. if (reserved === void 0) { reserved = false; }
  94059. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  94060. this._tasks.push(task);
  94061. return task;
  94062. };
  94063. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  94064. this._waitingTasksCount--;
  94065. try {
  94066. if (this.onProgress) {
  94067. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  94068. }
  94069. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  94070. }
  94071. catch (e) {
  94072. BABYLON.Tools.Error("Error running progress callbacks.");
  94073. console.log(e);
  94074. }
  94075. if (this._waitingTasksCount === 0) {
  94076. try {
  94077. if (this.onFinish) {
  94078. this.onFinish(this._tasks);
  94079. }
  94080. // Let's remove successfull tasks
  94081. var currentTasks = this._tasks.slice();
  94082. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  94083. var task = currentTasks_1[_i];
  94084. if (task.taskState === AssetTaskState.DONE) {
  94085. var index = this._tasks.indexOf(task);
  94086. if (index > -1) {
  94087. this._tasks.splice(index, 1);
  94088. }
  94089. }
  94090. }
  94091. this.onTasksDoneObservable.notifyObservers(this._tasks);
  94092. }
  94093. catch (e) {
  94094. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  94095. console.log(e);
  94096. }
  94097. this._isLoading = false;
  94098. this._scene.getEngine().hideLoadingUI();
  94099. }
  94100. };
  94101. AssetsManager.prototype._runTask = function (task) {
  94102. var _this = this;
  94103. var done = function () {
  94104. try {
  94105. if (_this.onTaskSuccess) {
  94106. _this.onTaskSuccess(task);
  94107. }
  94108. _this.onTaskSuccessObservable.notifyObservers(task);
  94109. _this._decreaseWaitingTasksCount(task);
  94110. }
  94111. catch (e) {
  94112. error("Error executing task success callbacks", e);
  94113. }
  94114. };
  94115. var error = function (message, exception) {
  94116. task._setErrorObject(message, exception);
  94117. if (_this.onTaskError) {
  94118. _this.onTaskError(task);
  94119. }
  94120. _this.onTaskErrorObservable.notifyObservers(task);
  94121. _this._decreaseWaitingTasksCount(task);
  94122. };
  94123. task.run(this._scene, done, error);
  94124. };
  94125. /**
  94126. * Reset the {BABYLON.AssetsManager} and remove all tasks
  94127. * @return the current instance of the {BABYLON.AssetsManager}
  94128. */
  94129. AssetsManager.prototype.reset = function () {
  94130. this._isLoading = false;
  94131. this._tasks = new Array();
  94132. return this;
  94133. };
  94134. /**
  94135. * Start the loading process
  94136. * @return the current instance of the {BABYLON.AssetsManager}
  94137. */
  94138. AssetsManager.prototype.load = function () {
  94139. if (this._isLoading) {
  94140. return this;
  94141. }
  94142. this._isLoading = true;
  94143. this._waitingTasksCount = this._tasks.length;
  94144. this._totalTasksCount = this._tasks.length;
  94145. if (this._waitingTasksCount === 0) {
  94146. this._isLoading = false;
  94147. if (this.onFinish) {
  94148. this.onFinish(this._tasks);
  94149. }
  94150. this.onTasksDoneObservable.notifyObservers(this._tasks);
  94151. return this;
  94152. }
  94153. if (this.useDefaultLoadingScreen) {
  94154. this._scene.getEngine().displayLoadingUI();
  94155. }
  94156. for (var index = 0; index < this._tasks.length; index++) {
  94157. var task = this._tasks[index];
  94158. this._runTask(task);
  94159. }
  94160. return this;
  94161. };
  94162. return AssetsManager;
  94163. }());
  94164. BABYLON.AssetsManager = AssetsManager;
  94165. })(BABYLON || (BABYLON = {}));
  94166. //# sourceMappingURL=babylon.assetsManager.js.map
  94167. var BABYLON;
  94168. (function (BABYLON) {
  94169. var serializedGeometries = [];
  94170. var serializeGeometry = function (geometry, serializationGeometries) {
  94171. if (serializedGeometries[geometry.id]) {
  94172. return;
  94173. }
  94174. if (geometry.doNotSerialize) {
  94175. return;
  94176. }
  94177. if (geometry instanceof BABYLON.BoxGeometry) {
  94178. serializationGeometries.boxes.push(geometry.serialize());
  94179. }
  94180. else if (geometry instanceof BABYLON.SphereGeometry) {
  94181. serializationGeometries.spheres.push(geometry.serialize());
  94182. }
  94183. else if (geometry instanceof BABYLON.CylinderGeometry) {
  94184. serializationGeometries.cylinders.push(geometry.serialize());
  94185. }
  94186. else if (geometry instanceof BABYLON.TorusGeometry) {
  94187. serializationGeometries.toruses.push(geometry.serialize());
  94188. }
  94189. else if (geometry instanceof BABYLON.GroundGeometry) {
  94190. serializationGeometries.grounds.push(geometry.serialize());
  94191. }
  94192. else if (geometry instanceof BABYLON.Plane) {
  94193. serializationGeometries.planes.push(geometry.serialize());
  94194. }
  94195. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  94196. serializationGeometries.torusKnots.push(geometry.serialize());
  94197. }
  94198. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  94199. throw new Error("Unknown primitive type");
  94200. }
  94201. else {
  94202. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  94203. }
  94204. serializedGeometries[geometry.id] = true;
  94205. };
  94206. var serializeMesh = function (mesh, serializationScene) {
  94207. var serializationObject = {};
  94208. // Geometry
  94209. var geometry = mesh._geometry;
  94210. if (geometry) {
  94211. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  94212. // 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
  94213. serializeGeometry(geometry, serializationScene.geometries);
  94214. }
  94215. }
  94216. // Custom
  94217. if (mesh.serialize) {
  94218. mesh.serialize(serializationObject);
  94219. }
  94220. return serializationObject;
  94221. };
  94222. var finalizeSingleMesh = function (mesh, serializationObject) {
  94223. //only works if the mesh is already loaded
  94224. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  94225. //serialize material
  94226. if (mesh.material) {
  94227. if (mesh.material instanceof BABYLON.StandardMaterial) {
  94228. serializationObject.materials = serializationObject.materials || [];
  94229. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  94230. serializationObject.materials.push(mesh.material.serialize());
  94231. }
  94232. }
  94233. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  94234. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  94235. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  94236. serializationObject.multiMaterials.push(mesh.material.serialize());
  94237. }
  94238. }
  94239. }
  94240. //serialize geometry
  94241. var geometry = mesh._geometry;
  94242. if (geometry) {
  94243. if (!serializationObject.geometries) {
  94244. serializationObject.geometries = {};
  94245. serializationObject.geometries.boxes = [];
  94246. serializationObject.geometries.spheres = [];
  94247. serializationObject.geometries.cylinders = [];
  94248. serializationObject.geometries.toruses = [];
  94249. serializationObject.geometries.grounds = [];
  94250. serializationObject.geometries.planes = [];
  94251. serializationObject.geometries.torusKnots = [];
  94252. serializationObject.geometries.vertexData = [];
  94253. }
  94254. serializeGeometry(geometry, serializationObject.geometries);
  94255. }
  94256. // Skeletons
  94257. if (mesh.skeleton) {
  94258. serializationObject.skeletons = serializationObject.skeletons || [];
  94259. serializationObject.skeletons.push(mesh.skeleton.serialize());
  94260. }
  94261. //serialize the actual mesh
  94262. serializationObject.meshes = serializationObject.meshes || [];
  94263. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  94264. }
  94265. };
  94266. var SceneSerializer = /** @class */ (function () {
  94267. function SceneSerializer() {
  94268. }
  94269. SceneSerializer.ClearCache = function () {
  94270. serializedGeometries = [];
  94271. };
  94272. SceneSerializer.Serialize = function (scene) {
  94273. var serializationObject = {};
  94274. SceneSerializer.ClearCache();
  94275. // Scene
  94276. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  94277. serializationObject.autoClear = scene.autoClear;
  94278. serializationObject.clearColor = scene.clearColor.asArray();
  94279. serializationObject.ambientColor = scene.ambientColor.asArray();
  94280. serializationObject.gravity = scene.gravity.asArray();
  94281. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  94282. serializationObject.workerCollisions = scene.workerCollisions;
  94283. // Fog
  94284. if (scene.fogMode && scene.fogMode !== 0) {
  94285. serializationObject.fogMode = scene.fogMode;
  94286. serializationObject.fogColor = scene.fogColor.asArray();
  94287. serializationObject.fogStart = scene.fogStart;
  94288. serializationObject.fogEnd = scene.fogEnd;
  94289. serializationObject.fogDensity = scene.fogDensity;
  94290. }
  94291. //Physics
  94292. if (scene.isPhysicsEnabled()) {
  94293. var physicEngine = scene.getPhysicsEngine();
  94294. if (physicEngine) {
  94295. serializationObject.physicsEnabled = true;
  94296. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  94297. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  94298. }
  94299. }
  94300. // Metadata
  94301. if (scene.metadata) {
  94302. serializationObject.metadata = scene.metadata;
  94303. }
  94304. // Morph targets
  94305. serializationObject.morphTargetManagers = [];
  94306. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  94307. var abstractMesh = _a[_i];
  94308. var manager = abstractMesh.morphTargetManager;
  94309. if (manager) {
  94310. serializationObject.morphTargetManagers.push(manager.serialize());
  94311. }
  94312. }
  94313. // Lights
  94314. serializationObject.lights = [];
  94315. var index;
  94316. var light;
  94317. for (index = 0; index < scene.lights.length; index++) {
  94318. light = scene.lights[index];
  94319. if (!light.doNotSerialize) {
  94320. serializationObject.lights.push(light.serialize());
  94321. }
  94322. }
  94323. // Cameras
  94324. serializationObject.cameras = [];
  94325. for (index = 0; index < scene.cameras.length; index++) {
  94326. var camera = scene.cameras[index];
  94327. if (!camera.doNotSerialize) {
  94328. serializationObject.cameras.push(camera.serialize());
  94329. }
  94330. }
  94331. if (scene.activeCamera) {
  94332. serializationObject.activeCameraID = scene.activeCamera.id;
  94333. }
  94334. // Animations
  94335. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  94336. // Materials
  94337. serializationObject.materials = [];
  94338. serializationObject.multiMaterials = [];
  94339. var material;
  94340. for (index = 0; index < scene.materials.length; index++) {
  94341. material = scene.materials[index];
  94342. if (!material.doNotSerialize) {
  94343. serializationObject.materials.push(material.serialize());
  94344. }
  94345. }
  94346. // MultiMaterials
  94347. serializationObject.multiMaterials = [];
  94348. for (index = 0; index < scene.multiMaterials.length; index++) {
  94349. var multiMaterial = scene.multiMaterials[index];
  94350. serializationObject.multiMaterials.push(multiMaterial.serialize());
  94351. }
  94352. // Environment texture
  94353. if (scene.environmentTexture) {
  94354. serializationObject.environmentTexture = scene.environmentTexture.name;
  94355. }
  94356. // Skeletons
  94357. serializationObject.skeletons = [];
  94358. for (index = 0; index < scene.skeletons.length; index++) {
  94359. var skeleton = scene.skeletons[index];
  94360. if (!skeleton.doNotSerialize) {
  94361. serializationObject.skeletons.push(skeleton.serialize());
  94362. }
  94363. }
  94364. // Transform nodes
  94365. serializationObject.transformNodes = [];
  94366. for (index = 0; index < scene.transformNodes.length; index++) {
  94367. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  94368. }
  94369. // Geometries
  94370. serializationObject.geometries = {};
  94371. serializationObject.geometries.boxes = [];
  94372. serializationObject.geometries.spheres = [];
  94373. serializationObject.geometries.cylinders = [];
  94374. serializationObject.geometries.toruses = [];
  94375. serializationObject.geometries.grounds = [];
  94376. serializationObject.geometries.planes = [];
  94377. serializationObject.geometries.torusKnots = [];
  94378. serializationObject.geometries.vertexData = [];
  94379. serializedGeometries = [];
  94380. var geometries = scene.getGeometries();
  94381. for (index = 0; index < geometries.length; index++) {
  94382. var geometry = geometries[index];
  94383. if (geometry.isReady()) {
  94384. serializeGeometry(geometry, serializationObject.geometries);
  94385. }
  94386. }
  94387. // Meshes
  94388. serializationObject.meshes = [];
  94389. for (index = 0; index < scene.meshes.length; index++) {
  94390. var abstractMesh = scene.meshes[index];
  94391. if (abstractMesh instanceof BABYLON.Mesh) {
  94392. var mesh = abstractMesh;
  94393. if (!mesh.doNotSerialize) {
  94394. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  94395. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  94396. }
  94397. }
  94398. }
  94399. }
  94400. // Particles Systems
  94401. serializationObject.particleSystems = [];
  94402. for (index = 0; index < scene.particleSystems.length; index++) {
  94403. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  94404. }
  94405. // Lens flares
  94406. serializationObject.lensFlareSystems = [];
  94407. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  94408. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  94409. }
  94410. // Shadows
  94411. serializationObject.shadowGenerators = [];
  94412. for (index = 0; index < scene.lights.length; index++) {
  94413. light = scene.lights[index];
  94414. var shadowGenerator = light.getShadowGenerator();
  94415. if (shadowGenerator) {
  94416. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  94417. }
  94418. }
  94419. // Action Manager
  94420. if (scene.actionManager) {
  94421. serializationObject.actions = scene.actionManager.serialize("scene");
  94422. }
  94423. // Audio
  94424. serializationObject.sounds = [];
  94425. for (index = 0; index < scene.soundTracks.length; index++) {
  94426. var soundtrack = scene.soundTracks[index];
  94427. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  94428. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  94429. }
  94430. }
  94431. // Effect layers
  94432. serializationObject.effectLayers = [];
  94433. for (index = 0; index < scene.effectLayers.length; index++) {
  94434. var layer = scene.effectLayers[index];
  94435. if (layer.serialize) {
  94436. serializationObject.effectLayers.push(layer.serialize());
  94437. }
  94438. }
  94439. return serializationObject;
  94440. };
  94441. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  94442. if (withParents === void 0) { withParents = false; }
  94443. if (withChildren === void 0) { withChildren = false; }
  94444. var serializationObject = {};
  94445. SceneSerializer.ClearCache();
  94446. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  94447. if (withParents || withChildren) {
  94448. //deliberate for loop! not for each, appended should be processed as well.
  94449. for (var i = 0; i < toSerialize.length; ++i) {
  94450. if (withChildren) {
  94451. toSerialize[i].getDescendants().forEach(function (node) {
  94452. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  94453. toSerialize.push(node);
  94454. }
  94455. });
  94456. }
  94457. //make sure the array doesn't contain the object already
  94458. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  94459. toSerialize.push(toSerialize[i].parent);
  94460. }
  94461. }
  94462. }
  94463. toSerialize.forEach(function (mesh) {
  94464. finalizeSingleMesh(mesh, serializationObject);
  94465. });
  94466. return serializationObject;
  94467. };
  94468. return SceneSerializer;
  94469. }());
  94470. BABYLON.SceneSerializer = SceneSerializer;
  94471. })(BABYLON || (BABYLON = {}));
  94472. //# sourceMappingURL=babylon.sceneSerializer.js.map
  94473. var BABYLON;
  94474. (function (BABYLON) {
  94475. var ReflectionProbe = /** @class */ (function () {
  94476. function ReflectionProbe(name, size, scene, generateMipMaps) {
  94477. if (generateMipMaps === void 0) { generateMipMaps = true; }
  94478. var _this = this;
  94479. this.name = name;
  94480. this._viewMatrix = BABYLON.Matrix.Identity();
  94481. this._target = BABYLON.Vector3.Zero();
  94482. this._add = BABYLON.Vector3.Zero();
  94483. this._invertYAxis = false;
  94484. this.position = BABYLON.Vector3.Zero();
  94485. this._scene = scene;
  94486. this._scene.reflectionProbes.push(this);
  94487. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  94488. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  94489. switch (faceIndex) {
  94490. case 0:
  94491. _this._add.copyFromFloats(1, 0, 0);
  94492. break;
  94493. case 1:
  94494. _this._add.copyFromFloats(-1, 0, 0);
  94495. break;
  94496. case 2:
  94497. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  94498. break;
  94499. case 3:
  94500. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  94501. break;
  94502. case 4:
  94503. _this._add.copyFromFloats(0, 0, 1);
  94504. break;
  94505. case 5:
  94506. _this._add.copyFromFloats(0, 0, -1);
  94507. break;
  94508. }
  94509. if (_this._attachedMesh) {
  94510. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  94511. }
  94512. _this.position.addToRef(_this._add, _this._target);
  94513. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  94514. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  94515. scene._forcedViewPosition = _this.position;
  94516. });
  94517. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  94518. scene._forcedViewPosition = null;
  94519. scene.updateTransformMatrix(true);
  94520. });
  94521. if (scene.activeCamera) {
  94522. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  94523. }
  94524. }
  94525. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  94526. get: function () {
  94527. return this._renderTargetTexture.samples;
  94528. },
  94529. set: function (value) {
  94530. this._renderTargetTexture.samples = value;
  94531. },
  94532. enumerable: true,
  94533. configurable: true
  94534. });
  94535. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  94536. get: function () {
  94537. return this._renderTargetTexture.refreshRate;
  94538. },
  94539. set: function (value) {
  94540. this._renderTargetTexture.refreshRate = value;
  94541. },
  94542. enumerable: true,
  94543. configurable: true
  94544. });
  94545. ReflectionProbe.prototype.getScene = function () {
  94546. return this._scene;
  94547. };
  94548. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  94549. get: function () {
  94550. return this._renderTargetTexture;
  94551. },
  94552. enumerable: true,
  94553. configurable: true
  94554. });
  94555. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  94556. get: function () {
  94557. return this._renderTargetTexture.renderList;
  94558. },
  94559. enumerable: true,
  94560. configurable: true
  94561. });
  94562. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  94563. this._attachedMesh = mesh;
  94564. };
  94565. /**
  94566. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  94567. *
  94568. * @param renderingGroupId The rendering group id corresponding to its index
  94569. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  94570. */
  94571. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  94572. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  94573. };
  94574. ReflectionProbe.prototype.dispose = function () {
  94575. var index = this._scene.reflectionProbes.indexOf(this);
  94576. if (index !== -1) {
  94577. // Remove from the scene if found
  94578. this._scene.reflectionProbes.splice(index, 1);
  94579. }
  94580. if (this._renderTargetTexture) {
  94581. this._renderTargetTexture.dispose();
  94582. this._renderTargetTexture = null;
  94583. }
  94584. };
  94585. return ReflectionProbe;
  94586. }());
  94587. BABYLON.ReflectionProbe = ReflectionProbe;
  94588. })(BABYLON || (BABYLON = {}));
  94589. //# sourceMappingURL=babylon.reflectionProbe.js.map
  94590. var BABYLON;
  94591. (function (BABYLON) {
  94592. var Layer = /** @class */ (function () {
  94593. function Layer(name, imgUrl, scene, isBackground, color) {
  94594. this.name = name;
  94595. this.scale = new BABYLON.Vector2(1, 1);
  94596. this.offset = new BABYLON.Vector2(0, 0);
  94597. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  94598. this.layerMask = 0x0FFFFFFF;
  94599. this._vertexBuffers = {};
  94600. // Events
  94601. /**
  94602. * An event triggered when the layer is disposed.
  94603. */
  94604. this.onDisposeObservable = new BABYLON.Observable();
  94605. /**
  94606. * An event triggered before rendering the scene
  94607. */
  94608. this.onBeforeRenderObservable = new BABYLON.Observable();
  94609. /**
  94610. * An event triggered after rendering the scene
  94611. */
  94612. this.onAfterRenderObservable = new BABYLON.Observable();
  94613. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  94614. this.isBackground = isBackground === undefined ? true : isBackground;
  94615. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  94616. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  94617. this._scene.layers.push(this);
  94618. var engine = this._scene.getEngine();
  94619. // VBO
  94620. var vertices = [];
  94621. vertices.push(1, 1);
  94622. vertices.push(-1, 1);
  94623. vertices.push(-1, -1);
  94624. vertices.push(1, -1);
  94625. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  94626. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  94627. this._createIndexBuffer();
  94628. // Effects
  94629. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  94630. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  94631. }
  94632. Object.defineProperty(Layer.prototype, "onDispose", {
  94633. set: function (callback) {
  94634. if (this._onDisposeObserver) {
  94635. this.onDisposeObservable.remove(this._onDisposeObserver);
  94636. }
  94637. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  94638. },
  94639. enumerable: true,
  94640. configurable: true
  94641. });
  94642. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  94643. set: function (callback) {
  94644. if (this._onBeforeRenderObserver) {
  94645. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  94646. }
  94647. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  94648. },
  94649. enumerable: true,
  94650. configurable: true
  94651. });
  94652. Object.defineProperty(Layer.prototype, "onAfterRender", {
  94653. set: function (callback) {
  94654. if (this._onAfterRenderObserver) {
  94655. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  94656. }
  94657. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  94658. },
  94659. enumerable: true,
  94660. configurable: true
  94661. });
  94662. Layer.prototype._createIndexBuffer = function () {
  94663. var engine = this._scene.getEngine();
  94664. // Indices
  94665. var indices = [];
  94666. indices.push(0);
  94667. indices.push(1);
  94668. indices.push(2);
  94669. indices.push(0);
  94670. indices.push(2);
  94671. indices.push(3);
  94672. this._indexBuffer = engine.createIndexBuffer(indices);
  94673. };
  94674. Layer.prototype._rebuild = function () {
  94675. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94676. if (vb) {
  94677. vb._rebuild();
  94678. }
  94679. this._createIndexBuffer();
  94680. };
  94681. Layer.prototype.render = function () {
  94682. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  94683. // Check
  94684. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  94685. return;
  94686. var engine = this._scene.getEngine();
  94687. this.onBeforeRenderObservable.notifyObservers(this);
  94688. // Render
  94689. engine.enableEffect(currentEffect);
  94690. engine.setState(false);
  94691. // Texture
  94692. currentEffect.setTexture("textureSampler", this.texture);
  94693. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  94694. // Color
  94695. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  94696. // Scale / offset
  94697. currentEffect.setVector2("offset", this.offset);
  94698. currentEffect.setVector2("scale", this.scale);
  94699. // VBOs
  94700. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  94701. // Draw order
  94702. if (!this.alphaTest) {
  94703. engine.setAlphaMode(this.alphaBlendingMode);
  94704. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94705. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  94706. }
  94707. else {
  94708. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94709. }
  94710. this.onAfterRenderObservable.notifyObservers(this);
  94711. };
  94712. Layer.prototype.dispose = function () {
  94713. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94714. if (vertexBuffer) {
  94715. vertexBuffer.dispose();
  94716. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  94717. }
  94718. if (this._indexBuffer) {
  94719. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  94720. this._indexBuffer = null;
  94721. }
  94722. if (this.texture) {
  94723. this.texture.dispose();
  94724. this.texture = null;
  94725. }
  94726. // Remove from scene
  94727. var index = this._scene.layers.indexOf(this);
  94728. this._scene.layers.splice(index, 1);
  94729. // Callback
  94730. this.onDisposeObservable.notifyObservers(this);
  94731. this.onDisposeObservable.clear();
  94732. this.onAfterRenderObservable.clear();
  94733. this.onBeforeRenderObservable.clear();
  94734. };
  94735. return Layer;
  94736. }());
  94737. BABYLON.Layer = Layer;
  94738. })(BABYLON || (BABYLON = {}));
  94739. //# sourceMappingURL=babylon.layer.js.map
  94740. var BABYLON;
  94741. (function (BABYLON) {
  94742. var TextureTools = /** @class */ (function () {
  94743. function TextureTools() {
  94744. }
  94745. /**
  94746. * Uses the GPU to create a copy texture rescaled at a given size
  94747. * @param texture Texture to copy from
  94748. * @param width Desired width
  94749. * @param height Desired height
  94750. * @return Generated texture
  94751. */
  94752. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  94753. if (useBilinearMode === void 0) { useBilinearMode = true; }
  94754. var scene = texture.getScene();
  94755. var engine = scene.getEngine();
  94756. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  94757. rtt.wrapU = texture.wrapU;
  94758. rtt.wrapV = texture.wrapV;
  94759. rtt.uOffset = texture.uOffset;
  94760. rtt.vOffset = texture.vOffset;
  94761. rtt.uScale = texture.uScale;
  94762. rtt.vScale = texture.vScale;
  94763. rtt.uAng = texture.uAng;
  94764. rtt.vAng = texture.vAng;
  94765. rtt.wAng = texture.wAng;
  94766. rtt.coordinatesIndex = texture.coordinatesIndex;
  94767. rtt.level = texture.level;
  94768. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  94769. rtt._texture.isReady = false;
  94770. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94771. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94772. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  94773. passPostProcess.getEffect().executeWhenCompiled(function () {
  94774. passPostProcess.onApply = function (effect) {
  94775. effect.setTexture("textureSampler", texture);
  94776. };
  94777. var internalTexture = rtt.getInternalTexture();
  94778. if (internalTexture) {
  94779. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  94780. engine.unBindFramebuffer(internalTexture);
  94781. rtt.disposeFramebufferObjects();
  94782. passPostProcess.dispose();
  94783. internalTexture.isReady = true;
  94784. }
  94785. });
  94786. return rtt;
  94787. };
  94788. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  94789. if (!scene._environmentBRDFTexture) {
  94790. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94791. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94792. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94793. scene._environmentBRDFTexture = texture;
  94794. }
  94795. return scene._environmentBRDFTexture;
  94796. };
  94797. TextureTools._environmentBRDFBase64Texture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR4Xu19Z7PtTHbW1g3jMMbGmGDAZAMm5xxMLDAU0WSKWOQcCoqccw6eGdtgk4yNbZxnvvAL+Af8Af6AsQl+06ako9X36dXPSi3pnPu+cz/cOntL3S1pq5+w1mrpLs/eud9fvn27rf9evPPwFz+v22S7fGZ/n7/70G79J5/Xv/qzbLP+Pnvvoc/6Tz7jX/15/c62LfeH7fofbpfP3l/ct36Wf+u4+D37+XYb++G26LPsr/zFttnPuh37bm1bt0f7MvtlnOx4uv0H4fty8UUsz77rfn/57u32cgXvDv72eQf0tl0+G38b0Nf9K4Dl704MEfA16KsE8Gw9JgD+DQE8EA0DT2b7GwK4GHnF4a8iguXZt9/vL5/dbisJbEq/uwD5vIK/fbbAv4N9U/8nJIDNCazKvBLBGwdwu62OhajxmQSAx6gqNp5HCg9wPan2nwSNjhLD8ux/3u8vP3y7vbwDAYjtR8AzFyDqLu1Q+YEINnew23rPCYiKb+q/K7o4AVT4tg0t/h4ydJZfkQASQ/d5b9fZ/Z1ENmuPn/cwYCYEELBguKC3nRkCnE0AFOwOKCOAR/sH/L4hgFMpbSWP5dn/uN9ffs7t9mJ5cAHoBLTyszBAFJ/F/xIKdASw5wgaEWDMLySxAk4svf6L+4QAGPiJCziNAPb4f3UZ2dh/m+z7BK4SAPYrxf5FB6ABPgCUAfANAZwKyscc7IEA/vv9/uLzbreXzx9cQCMACAl00m8jAlF7ov6SCMQ8gJsMFFBnCECSg5H6TxJAU3vPAbwhgFfz9AABeOEDBcIbB3AqPzwQwH+731/8sNvt5Ydut5e3B2C/fG9P+jESgGz/RgxG9r9VAwTUUh0goQDafUz+DYnAnSha5l99Z1l/yQVswAZSGIAugNd/9xBgCw9E8aECkHUB22QPHIAVDlQdQAMWAibhBgZAasAVHUAI8Cqg96Tm0bj3VBS9jwd7IIBvuN9ffMHt9vLTbreXy+32QlwAhgMIeuNzKwOqCoB2Aa00KHE+EsIeDuj4H2N+Hf/TfAC6A4nhgQCQDDwiaKDXiq9KgBEJNPArAtCk0AEd2mpAizW3/lYIoANpBPg3BPA+hjs/9eXZV+0E8Bm32wsJA9aEoBCAuAABPiEAC/yDC4gSgRgKRHkAlgsI6v7iEFqJEMgBwb4BGkEfEEDnDlReoAP/SQRgOYIB+IYDMEE/SQBbXoLNr0jhq4qOZc0PHBSf5oKW519xvz//kbfby8+83V68ABfwniIBgwgQ/HoRUMv8w5qAoQqgk4DWQiCw+63eD8k/XAPQgK5s/5a5xzAAqgR6wY9k+ZEMtCOoJABb230hEHMFWQdgAl0Ap/+uc6tKBrrP/n0AuwfiNwTwNKguHHV5/qX3+/M1B/Ddb7cXax7g2e324vaQB3hhkMAW92tHoFb96cVAbimwkgQ0Vv7R+D8iACfuxzKfLvnNlAAjAsBwwP2MwLQAD9sbYJME0AFcg5uBPSAA0x0AobhtcDKDA0j3KYDhk7Hp8uKj9/vzH3C7vfget9uLT9nDgDUZuOYCLBJA8MNKPyGGIftPrL+4gy3eh5p/lwRUYYAs9Fn7tM/E9lvJwCH2DxJ/mPTr4nyyLiDtBgTAGCrgNuPzNuETgN+suEEAFhng9lkCoICMLH7V0isCeEMCxylrefkl9/uzz90J4NNUGLDmAnYXINUBrf5dCCAuQCcCvYVAYPk3G++VAveVfkIAFRLolgbr2F9ifP33pAqAV/fHRF4HcAS7AKlAAEIYFNwITOszs/wMsB6II4BXFZ0QwBsSOEYCDwTw2TsBfPrt9uLlqzCgcwFABI0EVCiANl8Uvq0JWNsi2JPZ/0YKsOiHxftsW4v51ZqAaBWgZf91PsBL/jFHwEqBR1cCiuJ3gAfCmCEA3cf8rmz8AMZHIoA3JDBPAsuHVgL4jNvt+UoCH34ggK0asIYBGArsAB7AD+reQgCl+GwZ8LaNlP3MEEDaSg4ACMGr/+ulwV4JsAEfLH42/vdKgWElAJ4QpBl+LAlKErHwt+oGMgTA2ngE4IUIOH3dGr/hAKT/m/UBdSJYPuVL7vflU26352sScCWAD+0EsCcDVxewKjfmAzAsENVn4EfgdySgnYB81yEAgL4RA8T8mTUASAAYBgylQAkL8K/+zL6rsl8qF6ArAeS7WRGoAB8Sf7isN/VZqTs6jQ5wXlweWfyqpQ8I4I0TmCCAT/3I/b48u92ef9bt9nwNAdZE4FoOFALYXcAGegkDMByAzzQEgJh+cAIs/legH0IA5QTCPADE+7ISkD0TgA/8sBIgLQfOgF/F9kPcr+J8fIYguyCILQRKgV4DNviOzoKqeJS0u4AA3pBAjQSWT//I/b5OmC0MWB3ASgBrGLA+IryvDNxCgRXo+wKhjgwk8bcTwUACsJ09ANRVAALwCxmEoFcrAUsuAJ4M1E8BDuHABAHomJ8RgACrZfQLyT9dBWi2OOEG9NJd/TDQ8HAQuBE97ZhjGKy6o+imnU+4gDckkCeB5cMfud/v6zr9Dz84gOdCAM/3JwQhF9CAD25gBWWz/8wNgMpj3K9Lfy0foMMBVffXyT4r+cceC9bvCcDFP0311QrATPkvWgosYQFLAuoqQEcQuw3v2si25F+M1RkZXLUU+CgBmCBOEsCbvECOBJbP+Oj9fv+u2+3Zp91uz9cy4Kfebs/3ROD6iPD2b10YJCXB+0PyrgsHdtBuRACfBeTN+uM+suJPSEDbfh3/oxPoHgwiC3/06j8Eutj69sAQqj++I0CUfvIpwCEvYCT90O4Pn1XsT5Ve1/+dcp9FBh3woqXBSEJkvjHHEOUPqJPAjUUCeOMGfCJYPvOj9/t7//d2e7YmAlcS2B3A8xcPYcBm/7ULEDIQew+5gS0EIEA31R8Uf6gAoBsgKwBd9ddvBBJAs6XARgLQXQ2o7T8+IETe+9eRACg7rhCMVgCiE8D4O9wOCb2ubOht1/vYd2ubzLlgKbBHEDSnAMfL6durVm8qBPwXWz7rY/f7/X/fbsvL2+3Zqv4QAjzfw4COAMAJbEC3wC8koBJ9lAhgxZ+4hi3Oh/f8dU8EqtV/JhHgWn9cC4CJQZXZp6GAk/1nawMkrrcqAiwPIIA2FwOB2oaAF5UkcX+GADBs0I5gsNbBQqCorJcFJjqWKvhNMjky0Aek7/LZH7vf3/vO2215vruAD91uz/dSYCOAPQzYkoD7vw34sFIQw4LNymNSUKk8Wv0hCYhkoJ74Q6BboO9eDKoWAHXvBiCvAdPZf4nt3QqA924AbfXV8t8uN4Bt2We029WkoErWpSoCSm11TM8AOYA5uRS4RAITIQDDavaYHxCcm5exfM7H7vd3v2N9McDt9uxDD//WKsAG/ue32/M1DEACuO3g1jkBsf57fqCL/7UbIISAio85AAG0VQEYiIC9DJTYfy/+Dx8HlpeDRK8G90IBHQbgWgD2WT8LoOJ7NyeA5JEkAwwxmuqzur5X6y+sBEwDMggrqoBNH7c68Puk/fI9Vwfwvx4e6H724oEA1iSg5AAaAewlweeyLmAnAHQCTfU1CTAH4GyTMt+QDMRFQFEYQB71lXUAOjHYlvTqh4N2xe5yASoh2PpaJUGDBDrLr9cGIDlY1l+vDlQOAQHckYMiA68KMFsGtOy65RCGsMIDT+QqJoD3yUwCy/f+6P3+7koAt50AXrwigM0FrIuEoBrwHMMAUhmQUKAlAwHo7VmAPURo9h/r//ozLv1V7/5v6wGMV4B3rwYPXEBqIZAQwp4TYDE+LQlqtQfw6my/LgsyZaeLg7wVgmDnWQ5AA5ZWCDRx7ECzyn3udgFptFCIgTlyFRMEUCKgA+O/jl2Xz/3o/f7Otz88QvpszQOsLmAPARoBSDVgud02AthdwPZ5BSxUBVr8L3kAVHrvs076KSLQi3/M9QCJ7H/G/rf4n8X41XIgcwHecuBMDgAe+BHA6uQgqnvbF5DB5hwUQM3vQgIWkKOVftH+gAC6cz0RXZ9MjmD5fh/ZCWCd1CsB7CSwhgArAUgIIC5AQoDOCewJwab+CH79WR4C0mQAZT4hEQS9DgfEztNkoEECDfi6FAhZflb6Q1XXqwHDEECpvZX4a0qP1l7bfAS98cQfzQUo9a4mASMC0CsIm6JGK/2i/QkCuFK9PxmIYPm8nQDu795uy3K7LTvwVyJAB7ARwJoAVLkA7QIkJ9A5AQS95Ad2YmgvAJWwQFcBpB38pUuB9wVKbAWgCXwV86Mz2ICKTwUWFgOxMEBicr0eoBwCGBUADfxsDsAiA+zflNay31ZcfnAdAAXgDGkcdAcfZCJYfuCX3O9vf/vtthHAmgcQF7ATwOoAtn9IACsRSDkQ/wqIIUGoXYEQQ/sL5IDJP539776DwodVAGlr5QBgP8sDdApP3gSUXQa8/rZsRaBeHmy+HwDyCI1MUNlZzX9iJSBO9igJGJYCo4RdIqMfJQ4Ztq8C7FXjHuSnQ92XH/yvdwJ4Z68ErOXAlQRW0O9/JRG42v9GBHsuAImAqv+uzDo30C3yAfVHoHeg9xyAp/7wlp+WFCSWv1sOTBb+0EoAZP5DImBrApAUMFHolQG19c+EAkbpjyUEdQ6gm/QEsCzZFxKDlWNwprJVWfBm/1WAvWrcQ0ie7Lz80H91v7/9v263+9sPI2zrAZAEdvXvXMBKBJIIFDcgyUAEvHICg/o7wA/Bvyt35wCc2F9Cg03RvRyAA34N8hD0xsIfXP7bQgDMFSgyYO8GsF4N/hQ5ALak1yUGRQDZZJ5VWXgKEsie8yQuH63b8vn/8oEA3lsJYJ2EQgD73xX4z9bs/74gaHMBQgA7+DsXAJWBBniHCLTtNx2AUnkG/LYNiUCpvX7wp6sIOHF/lwgkNf8UGagwYMgLMBdgLQCyVgOyciCGCs5nz/Jr8EXOQOcQZEbrfjjTU8qaCBseMyx4vxPB8iP+RU8A24Kg9R8Qgaj/av8lDBgcwApQ+QdVgW0bKr3+jsk//AztzBKgtv4K+Kj08rl7JFgt9BnCAIsQcD2AsQAolQj0CAGAqhOFCK5u3cA+84dyIJLCPm6buAgoBa5qDoDF6wzUkZ13iSDKKwTamSKZSf29cuzJUwq7LV/wz18RwH2Nl9dKABLArv6bC5B/+9OBGxmsIIR1AQ3w2gk4RECTfwBulgC0rP96/FYJUOv9SzkAB/xuKTBY/qsTgZ0LILF/s/RW9v81ywEwhbeAwUIH6hRwGp+wEOhqoF49fojqQoPlR/+z+/3t77jd3n3rdru999CzEYAQAYJfXACEAqL8W5lQgA5uoJUK9zxBB3ii9ALiYT2AjvuN72wFILP+XdlP8gLKFeg6f5QM3AC+VlMMZ9ABGuN+VePHWL6tHVD23or3tQPo2iWfBRgShDp0ELcBjmIAbwTWqEzIJvLM6kEDEFcD9erxCzg3my4/9p/e7299x+323lu32+oAtjwAhgE7Cazqv7mAvRLQcgG7A9B5AAwHus87CWBYsIKFfe+eCSBgt2J+7QBQ+VsogOU/9fIPBvLhASEF8AHwlhPQ2wVYFhmo/Wby74QyYLcmQAEbbbue2FcnAb28QTmHQKBwNVCvHv8IESw//h/f7299pyIA7QIE/LsTeIbqL59hPUADvHIBG8jBIWgn0L4rsKMj2Noomz8QgZELsCoAAnh0Caj8lup7ib9tX+ZBoKgUmFkWTGJ8S/UHZa/kAHT+QGaeoeQmMUC/CoAzVYAjYDvSNwPCq8fPnINus/zEfwQE8O7tdt8dwGZjIQQQ9Y9cwAB+RQIC4I4MdvvdLL+O//E7LgLykn6q3Efjf6X8bOUfkoNYcQZ8z/KzBUBYCqT/YQgjBuOBHxPs7JHh7JoAy/IzWz+xEtBKBEYg8fIGw+SeQQQ+CzHZP+oWXWPU/8z9y0/+h/f729/5kAN4791X/6/cpl4SCsDfLRQwHEBLCmJFYH92vssNgBPo7D8qv4CekIHpAjKgx1iffGbKb5UAQwdguIAtz2KsEWj7vIQggNON91lYoIFN2mznYKj9UBmwQgXLLcDstRTdBchEFWAWcLP9MgC9cuzM8aXN8lP//v3+9v/uCUDyAM0FIBFADqAjAsgFiAvYwK3/MfAL8InSd/Yfy37Qpyv3OSTgxf8C5vZXPfF3aB2AA3hJGg5LghMOgCUBo8SgEAyC3Irvh5xAwhW0cT1iQBKYWds/QQLdeVUQcrEjeGoiWH7633sggHfWJOAaAkglYL/wLQyQf3tYsCp9CwmgFIgOgIJ/JwMdBuB3cQTDX4z9wR2whN+WE9idh67761p/F/8bpb8O/OotQCsJDhZfji0qT9p0LsCI83X9H8E9KH8iCSiTrQO29bwAAbvlCipPAw4T/oRKQAVElbaMJ472t7jnqnEjrlt+1t+539/6P4oAxLquawIkF7Bb/40M9hAAHcD2GVzABmBYKSgxfyMGAbROCipl1w6gs/8ZF0Cy/UIOOr7vHAIu9iHP/2v77yX9ROUt29+AHVUCnDJgtvSn8wXsnQGzIUAW3F27qFS4z2CrD07wCogqbR8LtGecUwR4vX/5OX/7FQFsOYC9FCiToBGAEAH83ZwA5AM06BspiPKrNQIt/kcg69iffBegNqVXb/wdQgIMC0DltUuQ+L+Bmz0OrNTdK/91+4JVf15SEPMCYRkwEfc3stBxurMS0AoTMKRocaV8cKw6jpcFsdUn2/8qRT8buGeP55HC8vP+5v3+1v99cADvvfNQBZB4dO24Kv5GAntSUOz/+n1wAis4wAnoMAC/N9svSUKsBABgmwPAbQTwWzsW/2vAI6j14h+1CEjnBYZFQWSxj+sEVFyPjgBBrhf+aOtPY39vRaBVJlQ2vyOGIATQsb6etBguDMSQyAF4IMhUAmZANNNnUNSqBDvtzzif6HSWL/wbuwN4eycA4gDEBQgRYPzfSGC3/BYBdOCHxKBHBAJoAbdWfIz1I9XXsf5g9y0yAJB7iUDPCaC6e2EA2ngMGyIHwAgBldncf4ID0EDXVp1NYmbnrclOtyfDhiPOoCO4CEXB/rOBfOZ4yy/8a7sDAALY1gKAfWMEgOovoNdk0IArKr+7gwH02gWQ2L4t/sEEoLL2IQnoFX96HYC4CIz/jcSgAJSVAtu2RPZ/SPRBHkC7AkYEqceC2fqBfdKaCcHAAeAkpKVBCANcElBVgBQRTC4HngHOTJ+rQo2jhEbP6xf/VU4AmBza7L+EAZgLgGSgxP8dGQDwmQOQbS2xp6oEWAnQn1seIEMCJO4fsv8Q2w/JQU0IJMvPiCCT/NPuQP/noJ0rAFBa23VSr1N/vQhIgxzzB9odMMIAkGvFZPF6JkyIlJeFFl6IcRYYX0ciOOOcll/6l+/3t/7fngPYy4BSCmyT0SGAlgvY4/+BAET10fZjUhAWCg2AV8nBEPQ6D6DJgSUAoQ/G+Dr+T9l/pfg0HxAs/e3WBUhbsihIgHKkHGiGCQHYO/UHomDgdd0BcRkZlYtyAFlgZNtlzqkSJcwc1xr/6FjLL/tLPQG8t+YA3tuXBKPiqISgAB//bjZdkoNE/Rs5EAIYXIAKCwYHYJADlvhalp8RgS4PogNwFN8jgo1A2LoALxRw1gA09TbCAjckQHBZlQEFwEoS0Iv1S3mAYFGPlwOIJn+0v+ocPohEsHzRX9gJYM0BvPvwTyoB2gGsP6iEAowANsBJWAAVgRYeAPCb/WdkAKEAttNJwRbzM+UPQI8K36k9Kf3RagBTe2vhj3o8uAFXLxUGxTdXBrK1AIltTZ2JzUe7Lp/Ralvxvrb5kcWP9nv2fwBzIRF4FRFkx/XcwRljHCGm5Vf++fv9re+63d4xCABVRhOAJoOtRCguQKoCmghwv7L/mBPQwB/KfMQhCEF0ym8RAUkIToUAxrP/gxOwSoDGmn9WCjTzASw3kHQA5poA7Q4g3n+MEMAChiadiopXwHZV26usvB43e/7Lr/pznADakmBdDcB8AFj+5ggcF4AhgAlwwyUM6m+pPgF8U3BS6jOdAAkJ3HUAO5C7ZKBT99/IVDsGhwyY3e8qNfhCERXDa5BrlW/ftaoqe265Ar0U+PIQQCUzqwqYBYfnSK4AcuW8sjmHaMzl1/zZnQDeud3eXRcCrfH/ngNYbyxzAKL8nQNAMiC5gI0gBNz42XIBAnAkBACwqDyWByPlp2BPWP7WD0Crs/5ewq+1JaBnWX8rEajbDiVAlbNpwHRyAJ4D6EqECQcQWfxo/0wI4E3wcPJnUbSLXqH5A26qHaD9kb7ssKaj+nV/ZiSALRG4rwhsJLBfUKt/k3yAJMGwEtCFBGD/PTIY4n6d8ANyaEk/Q/nPUv8h+WeRgXYCVgIwSwbK3osKi4PonEGUC2C2Pngc2LL73Xanlj9bBTg7BIgAFe2vuoxZS14B7wy/DCT8xX/qfn/rrYccwLtrElA7AJkgkrDSJUHJfO/Z/wZ4Kx8g4IXyYKfm0i9QfkoSJK5HghALr51Ce2Jwv0ad9BvAj1WCidKfZf1x3UDnvPQ90HYf7o1WfSQMGbOpU1D3H6oCynpjPE7VfSccpoalMEHNdAxFKkDLgDzTRo5ZaXukz1E34f1Gy2/8kzEB6MUlsjCoCwWMEAAdgOcGTECrnECn+JYTgPyABn0U82vwt7hfJft0rK9DAlHooTSolH94GxBUAnTSL/reAbz6UBADt344SDkIJBIT5E62HgnEAwgFmjq3ChFkAJUFd7Zd9fwsdZ89nnX85Tf/8Z0A1hwAOgDJAxBbuU1usboYCoiCKvWX+L/lAUDlNUG0bD8Bt7dviP9Vf0v9LbV3XQCz/3qbZf2d0h8D+JAPYDb/RAfArL1l92W7Z/OjEICpOZvkw7bES0EisET7M0RxRNkzx78qJGj37rf+MUUA+zoAnQjs1gTAhJNyFy4X7kBtkYHKB0ifDMgrLiADfJMESGa/Cwe0/a+CHsmA5QQ8N6ByAzJZh1IhEobOAegsvwaVDhEKDkCre0cielYbau4SQfIZggyIM0DMtMkc6ywnMHMsduzlt/+R+/2tt2+3d8QBiAtQSUBaEVDxPyYB22cEuiYDQgJtLUFk7539ke1vgAeAR05gC3ekbAclwuaEjEVA3XoAAnLpT6sBCuStrUrIpqsBHhkwcBOVTecFJAteCAFSyk/GzapwBOJofwV0mbEQkNX2p/X9HX9IEcB7eyLw3q8IlPgSbV/LBThEIMreQJkhAeYOIsDrsELV8VmIgHX9ITGo1L+BnxGB5wQY6IvKLzZZCKD7nsj8m+sADjoAVHk9ga19tF1CzSk5GO8T9MCUAdpZbSqEUW17lpNYfucfvN/fBgfwLlQBcEnwdkA9cdGiCjCgGrCpZhACDMSA6wL28dewgKl6GzuI963EXwtf1Nr/wQ0YMb+bCJwAPgKc5gPIPeiImeUC4B5J2zbZnGXBQjI4Mdk2HFNPYqv9MNlJCJByAzPPEezIiUAe7a8ANjPWGYpePc52Db/799/vb7/zKgQQAnhvDwH0cwFWLqBluwkRYJ7AqgoMTiHjApTqR9ZfbLxbCbCUX1wOKQGiO8ASn7XdKgMimL2SoG4nkxGVnqk+OoeBDHR4AN87EmCWnlULBGiBuiNJMFC5RJB8HsACRgYwZ7WpEEY2pNEuYOoYv/f37Q7g3dvtnT3+39YC6BBAv3IK1wVA9p8SAYC5gRDBqz53QDasvag/dQboGMCy0zBA7e/CgoTyszX/VeA35QeH1YGc2Hwr2YchGn5mJNGVd8FdoEOIHEBo9VkeQc3cqFJgEkPhxSBHwoIMCVTAlx1vlggq4y+/7/fe72+tDuDdV2XARgD7isDtd95BpZWjKRUov4Acwa6BT5OEsEjICg1aBUAl8DpwA2kgQeCYbHsjL0zygfKbll9XC5xk3zYGgM1yA0IKERGgI2PJQJ20M13CAQfgWv1kEjBj+Yc2zlqAGdWPgBPtrwI2O16FXMrn8Ad+z04AaxVgTwDiasAtBNgnrK4E6HBgSApichCBBHkBCnQNbmb1iTPoSEXlDXCfTv6x0EAA2OUDtCPA70bMT6sAXjVAlf4sIhieC8BYXy0CYk5gIPKCA8CJGzoAI5QYJqoRzx8NAZ6KCLLgzra7igSWP/i79hzA6gCAAMQFrBMNSUCrFypUm+x78k/cQRffY45AqatOGDJy0CDHkh5dDERielFhWvrTIYHO+icy/jK+qe6sCkCAH70erLsXylXMWv5GFowQrLyACISU6HZ0W+RALX0Qz2ug4NgYUWScRNQ+q6IZ8GbaVMCdHS99jX/4dwIBCAmsoNd5AHAB1sRDArByAV1YgLkBnfRDF6AtPbP4LNY32lkOgMX/tPynSKFzC466Y2JP+mT+mk8BOiVAVP2MA9COgH4nQGcgHxyCAe5uMicqARTcJ+QBIlB5+6O+V4E7c9wMCSx/9HfkCEDyAMPDJiQZ2AABqtZUVwG7s+ZWMlCDO/F9iPFZso9l/IkDaMRgxPqe4g8JQa30yg14pdaM7TddgWHxXcUPVgLqvnqyWw6AqrlT0jPV33AekYJb4IlAdfX+6LwR0BVi8Yhg+WO//X5/e68AyLMAawlwCAEwF2BkpTfgqwlu5QU6G45KrdYNsNi9qwAQMgjBnyEDI77XYGcxfjXut1wAhlfSptsGoNHJPab6XkLwTAeAk1MIidp+mJlRJYCqPxCABwizr0aUDl3I/ogEMsDMjJEZp0oYjECWP/HbSA4ACEDWAbA8gJ6MjADWbYP6i5LqvyRROBBABHgjXEAV14k963s7d0koOkm/s+J+FiaERADqbjkAHKNNrsRCoE7lmYsQ0HjlPm+dgMzKRLmQkkgyBJhR/SPWPwPyTJuriWD5U78FHMB7eyJQ5QDaYiBhXL0mgGWumRNQAO/KbieTASMOL8bvVgUSq2/lAvAaOvDiwiEjs6/BThdZ6bUBJNvfuQN0Z+pzVzI09nXqrT3UMRMAACAASURBVJcKg+J6xKAnLao7Tvruc6ZcyBS6EDpUXUIEvgyAz2oTnQuqe+aYzT386d98v69rALZ1AEIAazVgz/4zBzC8aorlAdS2rkIgC4e8v2TxkOsGMLeA45I6vgZ7ygFg4g8JQhOdl+FPZv+ZnRey0CQhE4PtH1TfCBmkXQd+S+1ZXkCTiQZq0gG4sb6qMHSAKFYQHpsIMoDMtKla/syYy5/9Tb0DWGP/7R8QgOUA2NtnzEw3LhRS6hjlA9CK6/gfS4XU5rOk427p9bg02cfATtS9CwGcSsB6/taTf9Zvx0ItvQ2JgH7WgEYyMMA+5AwmHMBMDsAjAhrPTz5M9H4mggy4M65g+XO/YSeAXf1lLYAsBca/24D7MwKdakBIYOUBxKYyJ0BDAeIOTOW2QI75AgVkXNVH7b+VBFTgDisAQda/gd5LrCrlZpa/WXJrEVBk+cGxNWAkqwDMQWiFNq2/zNKgDOi6A2NFICULRAV8rrSN7HgEzmh/NH4G2MZlDi8qXf78Fz8QgNj/thjIcADtvw9HNcgQwGxIwPIGLHTQVj8BfszWmzkAlZsQwFrlPbcCYOUCjBwKKwl6pUBRWyFhukxY7LmO7414X8f61BVY4YLY9iDBhy6BTX6LPJCoPHtcAXelbQRUD+gZEojGZyCvjrv8hV/fOwArBGBLgnFpcGdJYUJ0gNknxLDNCwm8xKEV6xtqPwt4DWpm92kIQICN7bSNF2Xv/pLfUgNd5wxoCEAA34GbqL0VAmhSuMIBuIqv8wGJRUQWmCzAfNIQwV/8tff7O+9BEhBKgEMiUIUAXjLQinMbAAAcCIruFWMVgBPFX28iLhW2Yvzu+JCo06A21wAQm69XRVJwk+RpaiEQCxeQKEDlaWhgtEWQWEqvt7vhwoQDKAFfjR+5hytdgjf20X1HLH/kIpa//GtUCLATgE4CogOQz628IwzslKx0gosuG1bWnuUGotJhyzUYYUIjBSsnoJKVXZnPCAeYo3EBH1UDDIA38CniiBR/CA1I1r5VEQBUg/1XVt8jjG7iWZUD5WEz5UIK8sRagIhYquQQgfqI/a/aeBYKZMOD5a/86r0MCGsApAqQcQDbgTQBMNuqJ70GE/nuOgMSGjDFj7ZZhNABnxBTIxon459Vfa9yYpUEEfRU5RXounEUkJEgGJlEYNb9O2IQ16hsO07y9nk2ETjzJKG4JIKUSlgQKqyDzgzQM22ic/AcxPLXflXSAew30no8eDsJvBGWyhmJsKojQOAOi3R0yRFtPcvuqxo/tf7qeryYv2T/mZqT0IARgfzmG9Eg6erP8Jvr+4Tk4Sk6IwnWfgA/IxsCPhmfKWuk3ugcqENIgLwC+hl1j4Ac7c+CPDNOd4/++q/ccwCRA1iFHkqAtBrA3ICh/J46Yp7AjM+DHIK27t1aA0YIbKGPIisrw59NAOqSH/0NEKyMCBS4qwnAtNpnk4JGnN8pfKYKoIgiA2R2DEYglW1XE8FZQI6AHu1vv8nf+BUPBNDKgFYOgDkAsHdmQhAnkhP74kNDg72OwgMP0CRuN90GW+CTdCwWoVluQKv3EAYQ1cZjuOpv9JXJNyT49KIgliMwlByVu7kJUFwvPBjcQuaxYSuUOBAGZMjGIxEP1BEQn3z/3/oi4gA0CQD4uxAACMBLCKLNjFSPJd3Q7rtJOWu1oZNcHMgmE+8H5T3P3Xj7OlCzCgEeN+sEVDs8Rpu4Ol9ggd1ScuYWkAQIsDv1lrYqB+BZ/2FfsBqQAe3sbZG6Xwn2aGzr3Ja//cuJA8CnAXfr314SajgBkwBwAs6EAwmwWWFChThY0s8iI297B3DDPYRtCLi3Psb2AdRAHrKvqb9BCEyNtaKXS4OkoqAnomXjKUEo9e/GSjqAs0HvAS8C5WzfaNwKES1/95cZDmAlAbIacPudIRcgi4H0oqBuUirgU6WDSVtJsHnJw8gtZNyGWeJLEJNn61vZzYjzo/3dQ0Ea1DgmUXMWAqTAbil9UOaLynttQj+iAzibCCLQRfstUM+ShJiqqP/y937p7gDuex5gBz5bByD23woDMA9ACeCAG8jkCLTis+8ZUhjCAisZOKvwySw/OoWONFWMrmv4ZsWAqX+wrXMGbLkwnMvgIowEIWuHTsV1CTKz978WeViA88IKDzRnA/Ts8TyCcUng7/+SngC2twFZJLBPljIB4IQ1wgA9waPM+rCfJApN9Tae1beOGZ1LO06CEKj7UbF9A7CVB7AShIa9R3Uf1gOwhF9V6S1iEEQFDqFN3my14IJEYNYRTANNERd+PZMMIsXXp7H8g198v68VgHf2uP9dBX5xAtvbgaUUqEqCg/1HKweAlx9vsLeGIlqxchWojCyqY1RCgXK5jxGHofIsD9B+V92nSAgIxCEkgLEGBU8mAaO4PgoVmEJbOQQG1CzIs+08Msg6kAwRzJBOlgiWf/SLRgewksCq8l0YAKBveQAgBGb/t4vDhJQmAwf4a9dQeZPWnJbiHMfgOYeNlAKlx3BFOxs3L6B+LySS8EUg6rzwuEgQ3luBGugDqx/lCzyCGPbtCBBi05M9Io2OFB4hEXgmGLMgzZDEjIvYruUf/0I7BGgkAJWAbY46SUArGThMyAIZVADH2ppEkiCBir2n5xmpu5ME1I5pUH+LYEnFICKEDpiFEADPSSu0JhQX/MphTBFBIYnI3MRjgLviLs48H9OR/JNf4IcAK9bxPwoV9TerAXgj4T0BOJk9MhAQDZOfACUCNgIy0zbTJpPZpyGAQwTiKug7AYkr0L+N991Vf00gpGyHINbK3yZVMQQwVT2xEMh1BEZ/Nvk1EKsKmgXyGeOeTQQdEf/TL3wggNX2b/H//jqwLRGo1gC0HMCeD9AlQPw+WDqZJEZIoCdaNY6OgOmFAVq5u7ae3Y9AHam7sd8kApUsZHaekclAvrv86eoBcwkZkFvrA1hf1wU4Cu4Btu1T/c8G/hWgrxDEmSFDc0D//OdDCEAqADoPIMnA7a8wrv6LpSEFfJlkoQtAdfKShEmAWlUDN7xgOYYE6DPuBY+Lv0W0HRXdK/cN2X6l0jqcsICubbx2AVeFAK7Sy+zV1YDiasAjgH6MvqZth+vXH6sksfyLn/eKAFaw6yoA5gEE9FYScDsZZfsR8CwhSJNb2Tq5UVLsQO0lE5Pk4bqRiBDU/oEcHFVn9X1T4dFZ6TKhYfWZcltqbm6HsZm6D07QKuGRcqQGgEUKSF5N2QySYPutbZkw4SmJwCIIJIXIYSz/8uf2BEDXAWAosN/w7gUhAHwhge7GY2wGBKFtf5oMGKgcl1Cx/wKwKKQY2hWB3oHbqver7ab6J8t/2L9VbaR6sM8auk4gArlRNbBchQnSaBw5RyV7lRCAgSYCerS/otRZwqiMmSECc7x/9XNUDkCvAyB5AAwDtrlBQgG8KegCOsvolQgrgPKcQKTQSReBhOCquBP3a8LTToXF/vpY8ls2J6AdBFH/rNJfov4YDoL6UzVP5gDc8MBJBFbBnwHrWW08EEcqrvhw+5oNBZZ//bMLBCDqb7kAcAJtUQeyOuQDcGIPnzFeJQClSbJqngBULW3xIzKpkBYe3wGxkISn/u5zASwccLbh5NHhht43ELsFcGeFXwfmA1UAdBsZ9YxU/ej+zDkwJ+RtO5Mkmhh9yc+637cKwJ79lxyAlP/kKcC1IqBzAJgL0K4AQwC0m7hgyAsBrAVEaL0HJU6SQKeiyT6dWictOwsTsqW+9ttosAax/pA3AKJBEqEhQLX+T+J2PG9GEIxEPPC6ag/SNzhOtm/fZo3JABYpfLT/KBFU+leUvxHNR37mSAAC/lYBUDkA76EgIYWOAHASKnXHm4/hwaB8pIxIV8oFFpxlziNws/0diSgF91bwuQQmE7QQ+2fUvwO+pf7KkXRA9db6W6QB1+KCHu1qMgTQE70DoTOG24/Y5qMuIEMOFYBXQ4FM++WjP2MnAFUClGTg5gCEAMhy4M4F7JNou/eZ0qBWELD7qO6D0uNkZXmEwKqb4HXI4wzAa8ejLTYSjb5mfXz8jgCvlP86YrhC/ZH4lfpSFU4SgAfMo88TZFxAlRgyY1aI4Iy2zQF87KfbBLCVAAP199YCaBJAV9AlnAxX0NqwnIBSrHSSziAPa/VeJt/ACMp0AY6l1+CNvofqb6h6NikoJMMUHN2apayZNt3YxRwAPa6Tb2iTXj4cVP2MwkdkUQFz5njsGt1tX/rTHghArwHY7P++DBhdwDanYCWgzgPIfh2TtfUB+6QcJhcBedfGUXoGwAaOyXhdKy4rC1rxPAtlymqfjP0x5h6ArVSdARJdiQa6BWC8t3h8RhQ616AnY+cEigRQdREWUZ1NDBnFz4I5Y+OroMf2y5f9VE4ACH50AS4B7OD28gDtxyEVgW6yOIQwWGlg/Uz8bQLXcBoa/AM56Dq8FcMbCTyx/o3ISF3fsvaMWPRv7JLEPht08nC4TyTDb5UNI1VnwO3coaHQFPBKxa0QwAO/G1LAucwA+2oHkDkny2Vs27/8pygCANUXF9D+h2CdC1CA334rcQf7Z7yxsp8qiFpBOKhPQAiW6jIlN9UdzllAKQBjdtxT9eF8HJLQ5xNae6Lska1nSu+pfyMjb3GOlxwEYrHANwA6sO/abdBxyRiPAf4ZoGf6WOA9y0Es/+YnAwHs4JfsP4v/JSEoTgD/is1veYFZEsB+xAp7gDEX0yRU2asQaHX2wD8QjEEsCDKt0pZqM2LpSqaiiNpteCW7mQSgukc4UTWxsH0Z8EaKT/erRGIW/E/pAo6AOdt35+Pxvwf/t0gA8BKQFfzZMiDmAYakoJ4oUB2gE4UtHDLiYQSa9bnsDEhJj4HfdBYHF/V4Vn8gvh3sh9Rfk60ot7c9Uf+Xc80AkDnCNGng+RrnzCa/RS6Z8zXBJDv0ORnf9bHY96Pbov7LV/ykMQfQrQMgVQABvP67//60BKgXA7UTU9Z/mDgk+TeAndjrBtpCBcEF9Wz23on7j1p9TW74mzaH4jgC/Vtri20uDdakzvIDbTL0y1I9Gx+V8CJHgNeTBfIMEXhjz5LDU5HB8pU/ccwByBOAXQ6AxP9sQVBL5EJGF8uByPYDCehJE1UGAuB7JKD3MadA22iFx9DCiPPpeZAFOZWyH46Jk2cDPiZFRX1IvI7XrMdg2fsOvCRsYGMM25QadgC8KAeQIg5BblAajOL26v5Z4DPrb6m95wKWf/cTxhwAPgJskQAu/aUhAIB5+22J9aelQa0uOuFFQoRBCY2Soc4PNBDBMQVAGJ50amqVI8kYOH4F3FTZsyU9EvuLMs4q/NBP3SNT1Y2FPQyQcs0RYYT7JxYTZQgiAmoE/Ki/8E80DgO+RQYe8Nvx/v2P3wng9updALgAyEoEYrY/ejS4katyBegG2OfOEqpSX7s4K0QohgVUpSft+5VgR7BFsb/nEkxScByD/s31pB2IIOMSIETRE9YLF0wiOGMtwcUu4EoyyIAe79uyEsDwIhAsBSrrT6sAuyJ0i4KU6p9CAkpl9boBNuHT7iCw9vThJBJfe8erKrt2IZZjoWSIcTkLCTwVt6oC6nojwLKYvuoWIsUf1DsZRljn7m3PAPcMBY/GqIK8YU/IHTYs/+HHKQLYAd+tBCQkMIQA7L0AQAxo8bbjI1MXPiOIqMJNOgIEly4HmvsUIaUA7oQ0tD/LuBsAzTqC7XosUnAy/MwBZADtKTl1fjhB2aT19j9RCHAGOWTGyII/Gyos//HHAgEo5c8kAbv4X6m+lRDEmy73EtViSEA5pcFOIVTSMHIEAgTLVuvVceXVeFWwO3F+ByIW5zuxv1ZRRqL6d2TK64E1Y/9dIiDWfVB3veqPEcEThAARcDNgPKtNdC6Dw/lPP+Z+fxcWAOHbgM2FQKDsQ/wP+7TSo+qzsiAqk1apLmGoVUor4kTpcCCDALzZen1EQpbNp+QEjgNdiZWxN8t4pCKQUXeLOChZOFacEoFxTmzsYRIjEZwQAnjjRwCL7Hu0PxofLnVc1IM7gzxGE96vWgkAHwUWF8AWAuGDQOyhIAQ/KwPu+9t5KmVvJwXtMHSgE9BQfU0g7oMy2g4byb9ZMFtkwUCMhNDtJ2VDDVoNLBoSEBLpQBYB18kPpElkv9HM1XRzwFB85gzw2BaArX4uoRRAFYG7up+RQYYgKm5i+aof/RACiPK39wAAEbB3ArSq3v4Bl//qpcAa8Nt3QhAM7N0FE7DTSWc4goEUAAwm8Ky1CNYCG69syWr/BJBWLkArvWflL1H/iDwE2I6dH0hKJkeyYtCRFYCThSdZYLuEwo6hCGwGlE9FBsNx//OP2gkAwwBJBBoVgK4SsE8KyQWwuJ8RAoIdCQJvpMXqVnlQA3z4TpRdjsHA1IEo6hss7JFzQQDQYwaE0AHAUmMrSWgAmJKomuRH7D8DmOVWGMAjgHb7T8oBeORR2XcFOcyMyfps2776C/ocwPr7df8rkEMC23xS/0uQLgVm3IBOAHYni1ldneHVcSMJKdbJEYYOQU7BDR+M8VMZeQZUY1tHVNYxlQJnQgJNKNbk9tzGAFovx0CWDXurDkPF1+MVcgBZhzDbbgaoVWdQsftNaIHcNwLQIYCQgCh9SwaC2jfgQ/lPg92qAnQnokIB6gCUcrlVAqNsZqqco+xMtTM2/FTwVxyBofAsvGGgNe25UxqskgxV+ETIkCaCAgFEzkLmqdXuqZ1ARBam6gMAl6/5kSoEUPYfwa/fBNSeBQBi2MZW7wRox8skBgnYTUfgKLeA11O4KDk3gJ0pWzI00BOYxuhOeU9fhwXWqdg/Io7MfuJKKNhBfRrAJisAFJgH1wF4oPYAF4HxyP6oLwN6xhls/f7Lj7jf5dHf9hdeBNoRgJH5L4UB+2TSpBDmBADsCG5U9izYq+Sg25uKqqsJhnJ64JdrcC13Mfan14tAdDL76MhM0qmOFdh2fRxGJBZQoycKI7BkQZ5tFx0v2h+BPw30BrhXH7bweCOA/eWf+kUgFvjxKcChGqAAbuYADCLQ4N5O14j9I/DjftcGe1UDpn7Ogh2LhCrHfyzw098Hwews/aVkkMzkD8qd7JciggNJQItUjoC0CuAjxMLOMzz3r/3h4ADgLcDM+ktOwKwC4HJg9ZmV/RoXWaGBUv1TiYABO8ofWLHwRDLPBd8JCn8quLMWPeMkiPozK5/dNpBCkAPIgnwWiLP9QqAqBc8of6rN1/3wh4VA8gRg9AxARwI7iFgJUCcAKwlBFg50lQIdDoCbMC1rpYKQrBygW+kUMcjkR+CsxvHus/sReCPQRvsR0A74rPCBnXtK6ZVTsdzgYwK+ovaVthE5zCi/8MnydZ+vQgC1AIiFARveINHnJQMbNlHlAbDbiTj7NBmUiYCoNqsiDBNUT+YjoHaSh3Lz3BDBcivedkaSjvqa8X2ypBe+QEQBVl9vBHrmCCi4H7EKcJban00GFcJYvv6H9UlA+i4AXAuAZT/1WWf/LdXv8G6VAQkxlMHPMsJFJ3CJylugstTaU2FPdT3wZpQ9UZ4LiYvU/TswJ1xDRsWZ88v0a0oIFjtDNt7YEQCPEEc0dnX/AwGQ2P9oDkDCAvld9XdP9dEV4I3tbpaenMZ3V2lIn0yCSlv0wyTh1Nkz9p6ppxVGoFU2VV/UOqn+6NKiMbtzdQgmcgRv1P/hJlXdw/C7/dcfajsAifeFDESU27MB+wa5jzoUaOB3LD4SA4v9NVF4LgAnd3ehgeozAHugHianEx6wCR+FG2YeA294whVQYtjvWQRUMw9BlDIkG7b6j4VmVrusOp9s/y0ncJX6R+POAD4kiI0A4L8BQ+Uf3gfg2H/2MBBTfdP+C7vAzdaPAFfIwLSERHVoIoqUBjNKm3EDGVIwx8kAOFLuaL86hkkkxcU/jDgrSh8CUhG9B6iMzc+0iUB7xO6H4EWszLqBb/ghJARgTwKytwI7OYAhBHBcQDYckOtlTmFYABIA3XILbCEJ3QaE1ampsRItHTbsF+mqqpUryCzZzYA/QzJJN+ICPLFqLwPCI/F/aXy5N4YjiRT6akB7BGmd2/INP/ghBGjJPwL+1QnIfGf2X8CuQ4GGEZXoO9UFEOdwhAxYDiCtXE79ngKh2t7LFWTAHwAbSTEKEby2kaqznEHUJ6XmCUJJjaPUdFbFK4CvtI2IprJ/+caVAHQSkD0ObL0MxCgJbnNNqb7+XlX+KATYLlwdky4NZVaRxY/ZcMGLZwNHkCaXCPwZ1bbOBZXNyS0wkJruSKmll1w9CsrHdACzZOBdYwWwYj7CcAhcijf+8o0/KHYAkgzs/u4Trqm+/g7gKYUDRNG7F4jKhTlAbz+SbgNjdz+g0S5yA0wFO5AQAnHVzwOoZ/vPAn8yMeclKSMlPwOspm1nhO2oeRZEM+0qgH8q9d/O8ZtWAig4AMGQuRDIWQ48JAUBkO3eRcDWuQSi+pETQOBSdpxQ/kjJI7IYljkrVXaBlajpZxbqeGrOQEDzGqA8OoywfvdqHP5+IICznEKFSDJOYhjvm35g0QEkFwIh2Bm4w3AgcAJ6MrV5R+y9BpcmCFQl+oOz8MByE0qNu/EK4UDkJBihWHF7Bvz4m5jAJct+I8Wn+6+I1a8YE0k4+OwBtaLwlbYZwIfjrQQwrP4jK/82+6+2y8q/IQmolR2SiNvvqFUc3x/A9jOwESfAgB6BnxGJFR6E9tWbhJ499ey9FUbIhDT6ejadAjwKMbSVtkgxY7kvAOuZjwFn1fvq0CACeAhucGPycejzzT9gdABYERheCLqDUQhh+0qeC2iYNcBvWf4wMWgQhE7+CdHoC04TAlFy0zkY6+41udAJkyANar8JKVIHEBFEspYfOZLIxofkmSEOr82B+H9WvWcIoALaStuILNj+bdtKAF4JUKu+uQpQx/5AFKj6NBwQeiLOYCCxKEegCELb++GHcCoCA2taYHXU0IrtXTJhjsd5kKcDpziDBEEgQZkkg+MBWVigiYjA/T3gZofjGI4kC+azwTszXgTaqwlgHX/5ls97tRRYVL2tADRCgUH1yYKgDofE4nc4VqDG/EGbE0ZiziMIF/yGYlCHYJEKKzviJLaOEWTbQ5CQpN9AAhcoP5JWGaBA8lmyKYHZI+FgldwMeLNhgncNlX0RWczufyAAWQqcjP2tCgACV+Z+t0RYAUmIpAOxEdtHTmDbTybBsHaAnIMmiuHmatcBk9m8iexcEgrqVgP2c6cxvFL+LMii2HkYJ5Er8H6TaeL4ANj/CKSPofiIowcH8P23COBGnwHQhOBVALxHg1l4kCED0mbIEVjqTIhk+4GT26dJIXAF0yGBQR4U6MR5ZNsNTkIRS0mVsa8ir+o4LnF4ZKvPYXKV3xWK/1o4gG/9/ioJKC8E9dyAAXaM75sDANDp+N8LA7p3CyjF1Y5B3xxKEsZ6AVo5SIDYZHMvGRUlqqLseLCSbzunpBVGMsy6hTA0icAWXf9sIjC45irZyPzKuJUjIH4KxR8cwLd+v50A1PMAmOzTnwXTYvkld7Bth5uM+9uBo3yAodKR8uP4HUEQ5dFtGYEM25QCDwQQqVAEzAgcQdx/JvipC4jICX50Cpxk/wzoorCkAsrM8WbHM0WCEGXU9qr9y0oAWwiglH8LCYz1/w3wqvznqr5BDhqsUwuEqg5BkUwHdgOI2yGsx02tHIHcaGd/pMQIbArMRF7hCGAwFMqAxWwTEdys+sO9zJzfjBuoKPVVba8lgGISsFsApElivyE45wdXADdNhwUdlkm8nnYCCeWXY+l439tecgvG5OxuZqSMjnPoJnwWYJETYUoenWOkaBP9M2C2yDML8my72fg/Am2FLKKxZvZvfb7t+77KAWxOwEj8NXUHp7DNb3QBCvwSAnSCq0MAQhiitugOcCzcbsX71qrAri9OXEY21nMGHUu9GnG4oQVncMg2Z8FPSDEFNMcVHemf6ssIidw3a6wsyM9oVwXhUQLwznkQMVIKbQRAV/45RKDJoAHcIQMhiwjUQwjQscer3hYh0BWBxhhCNCzej/ZZx9FuIsolHLbMFUWfAXIUviAY2ecKOUVjMTIoXH8EmAwhRSA/Cuoj/c255pHot33uQw6A5QFku5cLQGAjMSDmLCcw4BImixUaCDCZkntuwGtPCcABCx6nHBJkVDg7qSuvwEoAcQDIBPi9MTIAKyt59rcKyGWWHCr9IvJ4kv2NAII8gIC1Wwqs1wUAoi0yEABrx82UP+sGziCFDsgkHLDyBN1N80gjqCLg+CkQJOPqdn4BUOhEniENVJtE/2x8TduRa/IAmT1WBMSzxomO8yj7P/65r1YCotIPn0m8j28BFpVvwGdkoCRf2/gOd1k3MNgImIEEyBZZYEKJugVrHYEoi3EsTSzu5HEIZCCFyuQPnMIl4If7kgVMtt0hUkOCMj5XgVex7VM2XU3IlEAQxyPDdP0//n3GlYAh+FWs370OXBbbqWSfblNxAlbbsuUPyMLLBeA9YLafTZruB8+AO2vps+32650Flqem4b4T1d881oyreWICqJLL1e2XjQDkjUDkmX+d5WffEVeWE0CBNJU/qfq6f0eQBdVv/Qw1tdyCBWzGsDJGqBIZgiCAzjqK0kQ6A1hnjOGBNUEwIUmd5AAqxyndB0PFw7nkOAY9R5ePf+9XSUBGBAJudAVt234Ttn37xi4ESGyTE0rnAIBtBqwfAD/+Zl68r8nGdA3RykEsy2TtfJYkKsfWk+wM4GavJwnA2fj/CDCPgqzSPwoLov1HSOUVAeBKwGgtgJH80+AfbL8OC9A66Od0gFy0UiuCa+Sjt0cKboYQRGmHsR0w4vmGE0GRltk+AapuIlTbG9dcDh8mxpkCauL6wt/eUcojfY8AUiv0Wd+tc3ogAA/8xsKfDuykTVP2/YO1GlCLNnUCiii0Cpu7LUfgjUf2WTG/JgXLORwFtbkE2VLQRNKPTgiHjNKASBw7PZZ2J0Vnc+Q4ugsk6gAAG0BJREFUVVKKQH/muZxKCp/4Xv3DQGLn0fI3sEerAPVTghAaaFyllgcDi1Asq43t6yzwI2IIKgHiOFKWjZyjZ3XZBMuAOJqYbTJVwwuDfIb/l8FR2cy5VX6Ts0HmZdunz90i7eClJZnjZdoMv1EjAMcFbLiYAT+x8TpX0DCeAHPXxAA5XTug7YiW7on9NPYPwgLtEEKiSNjcTg2y4YSehCeBv+xUZid98ne5khCmwHaQDGeOGfVZVgKwqgAiiBH4U2XAfTCco1qxNcAZxiOAm+J/kSvwEoYU4Anl325ath0hr5BYNPDYq9Sr4LzY+reJfBZZVa/vhPYRGGf2Z/p4bZZPfM++CmCFAF4YIETR/upnApw3AqUJAQ4ShQPD/ovA3wjdANDwwxvKZbVjN45uSwI427eqnIywpsbIKOT7iAAy4Ix+p5kxMn2kzSsCCKoA+AiwJoOOAJTtF8vPSAK3NSFLhAJdPwLuTKiwHc8jhsx+1YaGBSRxJdeadQgWETBVTJNG0mVEE3TbXww9yg6lmPzL/gapawNSitpXgIdcF40783tlzmUd94EAEiVAuc8m+HWOoCH61fxAy19R/mplAElHicqrryeD3wM1fVkpm1gBkOgxHEV0gZA4VnpiFlQ5MzHNNoXjpM+9APBozKuI59BvpgAwJgE/B0KA6CWgrP7vZP4bWcBJZJYEI1FYQuzlAtw8gTFg2jXs12I+diz7gQA9tu/2GaRkOQvrfYapiZgNR6znyMn1zQCkpG7GOZfG0PenQAAZIM6cS2bcq9osnxAC0C6AgH14+Ie9EIQQwoY5FRo0HAbbKY5In3Yf2QtHEGVWiGEAVhHow1cHPHgeJnAZqAIll3GrSUdKBkdyBmQF41WTsxv3LMK6mAAe5bdwSKt6/AcCMEIAmevrbz88A7Dv1CofVQQ66w9ftAJrMdSuAHD46ucIiEGDeRDcKCwgB43KgZYa47l4biIav0QyybjfOufhWGcRiQHK7nivKQFUATcQ+Ylgnhl7+cT3sEOARgDO038dATjZ/w74AKTM9q05AScjBY8YEHRVy4/Kr4mEKZXbRnaSa/IAvR3HISk3CZkkr3AMOPeM3c2SiTtWAfyzgDyz3+xYZ/6e6XPoCMBZ9tuAboB8cALKIbT5x54H2CeVBrkGOHUFHjFQNlBJ6wnVZ+AWgogA3Fg6cVymuJ1zME/kYQdT0CwgXTUpEFdmUodtCgQQjrVf2NXtMuNn2lTu18x4rxyACgO8sp+n+ts+A+Rs+a+0Z1jFfXS/ASLLGQxjJEAYlgpn1FwdN0UazloDD6wR4aQVH4GTPP+ZCUkn/MmhxtWgsu7H7O9x5fkun/hsFQKw5B+AGsGfjfc9UrDIYjukmmjatlv4taoAFduvyccFWYJIvOSdFvIo7s8Avps0ScBaE606VoVUdFvL9byO4Inc2PvhnEcC2CfL+mf7p+P//ar1dgTsEA7AmJ1gFrZ36k36tXEjV8CshFwT3tEsqBPt2rDQNqX68GNl2kfEUQGmpcQR+VSOkQJIQf2vUMorxkxdd1R+hbl6aLzmAMhCnuEZAKPmrxW+EYAFcGtpsLM9dATgUrSiMvLQbSruYArQCaKIAJxyCjgxnGN6hGLuyy55npicFuEcJZSjAD7aPwvOK46TGfPBAej4nz3959T8B8VXYMR5aK4HIACOLD8DLZvzlp2nZiAB1G1+J9pVbD8jrdR6Awts5PymQL+Pf6j6EBCCNVHN/7iV/lgq6XkWCcn1k2NmwX2UxLLHyQBeLkPGXD7x3cccQGbdP1P9UPmt5CAAqiMLOVvD8re2XkjggHXASALUWfAzl4BzKLT0wblk+kdt0vuNc6lMbBPkhtU9tMpRgfUogGaApfmi8lsdPd9S/44ASLyPQEelZwlATQqIPU/56ctB1MtEGI61slP1NybvU4LfELBXmxMZfzZGxnGkQY8HgB9rxkVM9XkK0imqfYUYqgRYAnHBEelxXzkAJwcg4EOFz9p+5hSasBPlZuGCMgIPIkwmiN50RjWg+22zDsFxHRnwR21cEKtzjADvTUx0OzMgjsY2VbEI/iq4ps+L3JiKslfPszJ2pS2exwMBZHMA+8Re709HAGxxELTtnACgWZNIa5ew/APY9c0xngno+qlBXHxfDP7tBlaOwSZjsn+GFLZJciAMOUQYRQI4dKxHBvWVJDAz9vKJz4rXAYjidiHA/sPRtQDWE4LGOwIt1e+2KxvgEsD7DPyotNPqXwQNO84ApIkxI3IJwXryMcPjnUAAVeCd1f6MaxsJgNX9WXjgKbzlCIwyX7vn3jJhpZCUAGBjRBCKTzjukoraOlfbp04iooTk04mFic4I6QiwvQkvp+XlL44cewYkZwF0uDZ1D2Ztu76VR8ZZPv5ZDxpOwwDr+X9P4ZV9b66B2HodRmgXnHEGrc8Tgz98B4GF4wJp0Bud7B+BqDu9fcxMn6hNaT+5llL/IsnNkMNMn9eZUDYC0M/5I2jXzxqowzaw9l1bZzsCl1p9I1zQJCHkhffeVH+HJBgA9HwysZYE4TA/Z/sZziECi+clPAXOKg62y5xLFHJMjZFU2ciVnA30GRJ4jD7Lxz/zVQ5AwFVa/rt3osAv5gIQ3A+25OFuenbefV6AlBLZeBb4U/hMNSLQC8gonPyzx7Xq7gapyObwfKJx4SfIOJmzjveYQM78VlW7PktU2eseCSCI9wegW5Y/SQwakDpksPYLM1juofVTQHFxE71NKGkJQmyGDTyt9qsFGeCYo8N5ZcfJtnMnsvo9smNm2mWBUHU50bFnjvvYY67H6wiAvvLLyQPgk3xWqKCFRZSdAbdti5KBilws8YrcAd70cgxfJYtAYQPI97uPEog62DbxCmNGE7UKJjx2duwz2kVjXLl/hiAihzEz5isCCFYByhzRCj0A37H92xjE1neuwtmP/V1nQBYKWfMbQ40MCKvtD5EMO6ErgBqMGQGBnWa6z37sdPujoUYUipy4f9a+R0A/c9zl277bXgXYRQABjsDUIK0Anym7DiW0m2CCaS0ZHsggafuzYO6GSwCQNkn0CwnojDESYUwFjDjcTL9osVHZTTwigCMgvu77txCAEkCy7s9IAcHI3IIGNoJwIAV0ppmwYD+4xgn9HoCpAuIQl0aDsF9nH0J6KDWo2v5DKk86zxy/QjCZtq9Tm+hcrtq/EUCn9M4LQIYwYL+x5mpABUgK8H0jgmH47IC/U38Sl1fBnwV+GryzuYILwd+GTl5ENPmyzNONkzx2xg7PklP2ujLtHqtNdJxov3YljQBEibW1t7Y34CVW/Wngt3vv9MXxB4sPd5w5CBY+6PESTvihCUzU7JzF68uCwzrnSnKudCx1MZmJUxo/itWTP+bMeWX7PEW7s46ZGSdq00IA+uYfou4DkEG9vX2W7Weqz8gBccjcAQNPRfnNuUjcCQPB6a7BZIMqBI32SfBVjhZNtm6sxPFL48HglX5XtM2OeWa7zFhWm+VbP6NPAgrYXOX3VH8fwFT9qEqg+rvq76izRxQZfEVlQXcOJ4nDBdgZY6TZKoZ6ZpLFo4iq8JZHj1Htf1X7K8bNjDnTZiCAyPLPxvs4LnUEiaW/HaifCPyReEXEkSGfM22/nO82OaKTTyP4QMOLQo/M5NdnfXWf6viZ9pk263Vm2m0hwOoAUK3NxUCBsrvEkFH9YI1AN3+zFYHki0M6UBog8bCDYcth0SUHOgW3pwxyAPiJ9wvMjp6Z7Gzsx+pXPU62/RntGgFYyt/IQVnS9au3DwHL6vc6RIjWASDIBntvOMvsSkAPwBZuuu0HQBuNUwUFPd+LwZ+diFc4kPSxyQ/52H2rx6u0z7bV7ZZvkRyAEddr694BP3IFmXyAE/NHlt8iAv2fjXju1wJ/Cvhq4AzOzDZO58y4mXxClUxObX/4IvqzyU547xqOjnGkf7VvpX2p7bd8eCIJKIpLXAFTfq322jl0feCOee00qC2HYIHfUt408GFgb26n5v0JawVmiOVUgHuDpX6E+GwqEzseLRcnXz3OzDVV+3jtl5UAEKAIOhO40WO+mZifOA5KBEG7DuCJhUADIcDkZPPUJIQDil21/dP4KXYsNs9g46HNgYGrkz1/UucRwHrMo+c527/abwwBdgLoSIAou1bjSNU98jD/81Ct/t7/IyAuRPocAH9F9be2pEM0x+l+tTEag03u11H55Zy2yTZzURUUH2xbBVDmcEfGfOy+yzfrEMBaCrzfTAbsiBwyYcGg/oSEAOu9sKi2oe2fUP3WJQnacN4XbH84lp6VB9xJZoKn25RPPD3yaQ2PAC5zEkfHP9I/03cjAAbgAegHFv9YBMEsPyqsPgcNbNaWgb+bh4QsNLHgjWV9Q4IxZoZFIubxghmWcRWZSVrgj/xwb8Df/VYZMEY/7hVjPBAAgIIqvKHGkfJ3Y0UEsl99+L4AaQcoxLmm593Z4Gfz2pvrw76kg5giBXIiV+EwHDdsEE336/efAaiZszzzuEfHWr7508k7ARXIEMjMGZhKnnkpKGnDxhu2ESWfAX8K0Jn/ZwBmgjn3E7Y/i5uIWDITM3uszFgdYV01cPVEgvZHwXP0dK46fmXc5Zs+nZcBN8BFqn10v7H8V5NMZ7kTVYHBoicBTMkgqaqhC3AaRHiJ9m8TccJZeBM4dUw2wIHrjABVmdjkJ2nDV8eJzuus/VeelzX2RgCDwnuLghxV74CbedQ3Uy5MvBQkUn53P7odreIJUFnzvdueGKdq+b3xLwF2NqE/zRxnweiDNc6VpLD+Uo0AGnjBWg92f6dVur2yNFhA59h4nEfb5+T6fw2MCPxU9ZV8mG3UXKNzn1yjnqIRZtz9RXIpinaIplkiCgd+08D9Bc4ihuUbMQRQkzXrDBAv4UNBcllR+IDK/Ejgb5MZZnVEIJ7V9J4M9EAdEUI7ZqZhVrkzZJawFslTegPvR/gFMiSxEYBW2PX7oPIROWTe+JsIHzoygS/6fDTwjiq/Bv8s8BmJAOfR2x6BxnMW1dDBIyxrTkbnt/VzGqX6PwIgjhxCX0MGXEeO9xh912t4IIAo5nfAj2o0kAaqeDLb341hHNcDf/QEoAvsI8lCA4nW5D/iAE5558ABxR/O/SDCD3a/DCuZ83q/E8HyDZ/mVAF2pCEoKcizdj5DJEIaVfAnlgJXwT/lApxS3wzoM2DLTNSK8mfHE+UvtS/A9apxM6fwlMeW81vJ5WrnsREAA/W2LQHsVMyfGKez/gr8Q1ignEXm8V8PzFXXYIHJUmY2mWbIwPq/EvWEzkzeTJuQNMgg2XEzIJwJb6rjHgp7zjrYI43D3MryX8EBWHZ+VvUtEmGAbseAGUSPWwT/2apvglntOAv0bRwDWRnAXdYmM/BkEvKpgZm8tEeC7nWH6QhgRvVdkColt9rKcT1ioC4gsP0V8LttjUnMwFkBvjXJhu2EFGcBEk3saL8cN5uHmD3PaMpnzzMax9v/GMc4cn5n9N0IANXXBWnmPQCi0Enwb8AO2mbAXwFw1fJXiKQBxLg7FYJAR8aGiyboZfvVwNFxMhN1ZoyZPplzie5hZYzXve3y9RICEBAOZJAEdQnQxpiuG3DWBWA//RnJhu5TdyskFTIDKwBPtU2qfwQGb3/Ut/utEo0TTUxczPSd6ZMF5pVjZ88hanfkHDcCiAC7HSAqFQJthi4icAlU8YMyImPtAcAOmLBtCHzCHikwR6GEvtMnVxQY6ZFD2vMt8TDTjFN5yj5Xgisa29t/BNSV4y5f/6nj04ADABNZfI8kqJor5XcVPwF+D7RybimSgF/PHDNQ5YhAPCC2vkl3EYF6VvlpP7VxZpJW+lTasntbAYLVduYcKse9evzoXJav+9RX6wBkMnUKfgH4U+VFDcTkcmANCAR/SBIF8M+CPOUUCDnijZwB9UyfDlSJmZpo0s3HTPtMm7McRMkNRcgK9s9e18HDDt03AugArx7qMfftQ0XKP+MmvD4U4HguhDi8PpV9mfUGTJFToJdrMGaGNWHO2u46iYCQjgAwC4RsuyxRZoA0c8xo3CvGjI7p3dvla4kD2Dqom06JIOsOEs8A4A9jOZCzwV9yBKpxBtSZNt01JY5h3cwzicA7p84VZGZech1AFhjZdjPneYTIop+iet7ReGed60YAFuBc9T8R/IPiF2N+Rh6RWtM+xEmIw/EmlEckacA6KnsGuL0JaO5LJv2ykztqF+2fBXV23LNApcc5cnyPCM4Yd/kv6ACyoM62q7wSTD+BaDiQlAuYLBNSIBeAGRGBSQbkTlZAf0bb4dySbqQ62TOTNtPGDVkIarJjnkkCR45Z/V1nHMPa5xUBwEQ/TfnhF3DHJC8TYa7gKPhLqg8Hi4Bd3W9ZbDZhzgB3ZYx2bs7szUzsqM3R/Y/pBqJzPZM0HgP4eD0bAaTi/WxeoBDvD6SQIAzG/K1bslJgEUF3o48+XUhi32EiFev8WYKYAjzOPBCDSFkicHj7o75Zlc+MQy4vurS2vzp+9ryvtveZ81i+5lPGMiBT3zRJ7J3Tig9UHvVxHYC6SxmQm22csVwC2q8lcgTbGGRWHQF4tq83KbYxjNkegWAW6NG4mUk84wYyx50Zt3K+FgFUzu2o+9gIIALeVeBHuxmdQxb8VeAP48IAEZCn9zvHsCZQFuDZdvQ4CeWPJudTE0F0fjNOoDLmEQKoHmfmWjRhLF8dOQA1KVygFpKDrwP4B7IwgDkNdOYIDJBlgXt2O7wPenJEE3IG7DN9qhM9Ou8rx5slgMo5zzoT5hY2AjBBfTL48cfZhs6+OhzOvANtArBpR5AA5mEiIHc5GjPrCLLEcIXyW5O3uj07sTNgybTJgjU7Vna8KtEebe/1X/6z5QAmwT+AnL1g9CD4hTzcsMAiDba9mPCLQEv3G2RlTfoMoDNtvEnZ+quBZlR6Buwzx7lCvTMAz7SZIYDsuFlyZCrvnddGAIMDCMDfgbxCFIkKgUcg2q6m1X3/VWj7yTUD7Ec1iSHhLrJEcAT0dLIVKxHRRKwSQQSAq/dH15PdX2030z76LRj4oz7LV2kHQJRqIAgB1GOD31DRChF0bR3lM8GcKO91fYvuwmJr73y8yeQSRlL5zwL1rOJHk/jo/oxyR8e4GtDZ41fPoyeAQhKvVBk4Q/kD8FdIYLvhCTLxQozIAWzDBwCLQB3tj87BnQwTyl8hgkrbzKSNAHD1/gxJZNtkrhfVPLo2rfyV9hsBlMH8RMpfBjn8MpbyZ8asEEEbT/1GFZWOgB/tD13EBcpfBfwVbiCa+FfvrwA7OpfKWLNksZ7D8p8+lFwI9AS2H1U0A1Rp47YlwLTaTwF/7xSB9Oj+I+pfeX15SCYGyWYm5etGAhlQPmabqxwFjrsRgAaO+f0k5ccTcI+dBGuaHJLjReByCSNQ16PAj/qHgIUBKqrN2h7tH6ncFQQRgSoCeLQ/Gj+65gxxasufPSZrt/zHrAN4jcCfBjyG4RPPCZQdgAOuCLgeqUSEFIIeZt0VQD46pjeBryCBCMRX788CNjqPCplYx9wIIHQAB8GfVvwT3gNAgTQBflflme0l7qJCIDMgzwCvtQmcSZpECi82rTiECBTVsWbHi/pl9kdtzgT20bGW/xA5gNcc/K4bOAh8D8DdD3/kPygplhVLoL9Q+TPnESlUFdTV9rPOIgLw0f1HQRv9rjpE8I63EYDpAF5D8LuAP2j5o7GpSkMn/UNXvlfaZtxCa3Oh8lcAWWk7C9yzjpEFmAes2X3ZY2dIKNNm+feWA3hC8FeASNuS9QxZNbeOTfur38i6edkxI2BnVFc7kyPWPnO8yvhntI0m9WOSwBGQRy7g6P4skWwEMDiASfDjzTFdxX5m3f4CYCNyyCzwicZIkQUBv6fiFYWvtDVB9cjKnyWLqrqfBehZsM4CcbZfFrjR+BFRynGWf6cdwCT4GahSJBCAPwJrtx++6GOnQK3icVO5T3p+oAL0qG13fYScvImVAW/p+CoIzYxfPb8qkUSAuIIgZseMzjWzP9NmPb+NABpYXgPwlwAPE02vZjwT8BHJsMn7ZG6AzLoMAM9qU7H5Z6j7GWNkVLd6nCwAFVe2r5HCn7V/+crVAVSeAUALbyjhrPJ7LsIC9NaHKN4lDsBQVtMpOI7CIyg2ebxjzKr/DOgzfSok8NhtI2CeCfQjID3SN7pG3L985cvEOgAE/ZFXfSceCio7AMO1uIShriflFhySqQL2DMKgx0yofwbAnnupALYCpsx5PUaY8H4ILSoAjxzG8hUvi88C7Ee3VB5PjrZJuA02BgVp4EBSwM7E/cn1BBVV90A2tQ86RQCOCCuz/ygRZAF/lETOBLSnypXz9Igssy8igIp7WP7tTgAhcCfVuyOBE8DfLq4A/shVuERhAGsKpBeFBNH/gmRNqogoov2PRQJHj/MYJDBDDkeAPHs8fcxGAJaiVwHMwLZtS4Df7Kst+8HKgQX44fj7hizYz24XKbH8rmjzItAe3R+dU9WmZ53AB5UEZoE8228ggH+TdQAFADMgpQhGAZ0SAlHkSOGj/VZ4MRNCZPvMtuv6JQgqA9gqKWTBmAV3tl32uGcpvgWy6vZZpT8L5CgQlAA85a2qtwZ6RflDB5AEfwT4aL+21Fb7LIhn+kfAzfzHIhVgR22j8zmq/BVQZc61SgKV41fH9n6bWXI4q9/y5SoJiAMfBb9Xm7ccwXB8cQVE7QayIW8groI0s5KwOmYEHm9Cm/suUP+MEp/V5oiaV8B6VdsZEphR9Jk+FXLYCMAE0oTtb2OpCZoBq+kAjLFMsgDP4x33TOsfugohMnJuEUEM56lmRaSIV+/PnP8RwGfHrxzjyrZnksPlBPBlRhlwxrpnwW8CnWXJC0RymBCS5b4zwV5Wf+hwBNhH+lqW9rHdwVF1P9r/dQZ6ljiWlQC0SjIbPLRRilYFv0cC7Yc9WOrLAFWf94y9n+ljnZurdie8YnzquMS9PAUJHAVshqCs63oMsFeuzzvPaB8eZ/lS7QCU4jJVNckgUGurH1XuiVJfilSYFTdUtUIgR0nA67/tU7OjouBll2GEKVnQZ4EWXUPFps8es3KM15EEskoPt3T7KP02AojUO0UCk+CnoCWAzII7Au2w3yG8o6COzoUBioKCnKPrFBjJqRlQcQLVY2WJIjNuBaCvIwlUVX0G0NVjdATwMXEAAYBdEnhC8Ecgc/efGPNH5xFNdhOQRdt/ptpHCh3tj675CFE8JTFUjv2UriFz7GUlgOp/DNKRwUHwdxPfUeMjDoCCq5BfOOoEZvpr2x+BLavolXEyAM6obnTMzHEqoMuc09HxKv2rbTPAVYZO/ydUbXfkKP4/BnecprBuissAAAAASUVORK5CYII=";
  94798. return TextureTools;
  94799. }());
  94800. BABYLON.TextureTools = TextureTools;
  94801. })(BABYLON || (BABYLON = {}));
  94802. //# sourceMappingURL=babylon.textureTools.js.map
  94803. var BABYLON;
  94804. (function (BABYLON) {
  94805. var FramingBehavior = /** @class */ (function () {
  94806. function FramingBehavior() {
  94807. this._mode = FramingBehavior.FitFrustumSidesMode;
  94808. this._radiusScale = 1.0;
  94809. this._positionScale = 0.5;
  94810. this._defaultElevation = 0.3;
  94811. this._elevationReturnTime = 1500;
  94812. this._elevationReturnWaitTime = 1000;
  94813. this._zoomStopsAnimation = false;
  94814. this._framingTime = 1500;
  94815. this._isPointerDown = false;
  94816. this._lastInteractionTime = -Infinity;
  94817. // Framing control
  94818. this._animatables = new Array();
  94819. this._betaIsAnimating = false;
  94820. }
  94821. Object.defineProperty(FramingBehavior.prototype, "name", {
  94822. get: function () {
  94823. return "Framing";
  94824. },
  94825. enumerable: true,
  94826. configurable: true
  94827. });
  94828. Object.defineProperty(FramingBehavior.prototype, "mode", {
  94829. /**
  94830. * Gets current mode used by the behavior.
  94831. */
  94832. get: function () {
  94833. return this._mode;
  94834. },
  94835. /**
  94836. * Sets the current mode used by the behavior
  94837. */
  94838. set: function (mode) {
  94839. this._mode = mode;
  94840. },
  94841. enumerable: true,
  94842. configurable: true
  94843. });
  94844. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  94845. /**
  94846. * Gets the scale applied to the radius
  94847. */
  94848. get: function () {
  94849. return this._radiusScale;
  94850. },
  94851. /**
  94852. * Sets the scale applied to the radius (1 by default)
  94853. */
  94854. set: function (radius) {
  94855. this._radiusScale = radius;
  94856. },
  94857. enumerable: true,
  94858. configurable: true
  94859. });
  94860. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  94861. /**
  94862. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94863. */
  94864. get: function () {
  94865. return this._positionScale;
  94866. },
  94867. /**
  94868. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94869. */
  94870. set: function (scale) {
  94871. this._positionScale = scale;
  94872. },
  94873. enumerable: true,
  94874. configurable: true
  94875. });
  94876. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  94877. /**
  94878. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94879. * behaviour is triggered, in radians.
  94880. */
  94881. get: function () {
  94882. return this._defaultElevation;
  94883. },
  94884. /**
  94885. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94886. * behaviour is triggered, in radians.
  94887. */
  94888. set: function (elevation) {
  94889. this._defaultElevation = elevation;
  94890. },
  94891. enumerable: true,
  94892. configurable: true
  94893. });
  94894. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  94895. /**
  94896. * Gets the time (in milliseconds) taken to return to the default beta position.
  94897. * Negative value indicates camera should not return to default.
  94898. */
  94899. get: function () {
  94900. return this._elevationReturnTime;
  94901. },
  94902. /**
  94903. * Sets the time (in milliseconds) taken to return to the default beta position.
  94904. * Negative value indicates camera should not return to default.
  94905. */
  94906. set: function (speed) {
  94907. this._elevationReturnTime = speed;
  94908. },
  94909. enumerable: true,
  94910. configurable: true
  94911. });
  94912. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  94913. /**
  94914. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94915. */
  94916. get: function () {
  94917. return this._elevationReturnWaitTime;
  94918. },
  94919. /**
  94920. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94921. */
  94922. set: function (time) {
  94923. this._elevationReturnWaitTime = time;
  94924. },
  94925. enumerable: true,
  94926. configurable: true
  94927. });
  94928. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  94929. /**
  94930. * Gets the flag that indicates if user zooming should stop animation.
  94931. */
  94932. get: function () {
  94933. return this._zoomStopsAnimation;
  94934. },
  94935. /**
  94936. * Sets the flag that indicates if user zooming should stop animation.
  94937. */
  94938. set: function (flag) {
  94939. this._zoomStopsAnimation = flag;
  94940. },
  94941. enumerable: true,
  94942. configurable: true
  94943. });
  94944. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  94945. /**
  94946. * Gets the transition time when framing the mesh, in milliseconds
  94947. */
  94948. get: function () {
  94949. return this._framingTime;
  94950. },
  94951. /**
  94952. * Sets the transition time when framing the mesh, in milliseconds
  94953. */
  94954. set: function (time) {
  94955. this._framingTime = time;
  94956. },
  94957. enumerable: true,
  94958. configurable: true
  94959. });
  94960. FramingBehavior.prototype.init = function () {
  94961. // Do notihng
  94962. };
  94963. FramingBehavior.prototype.attach = function (camera) {
  94964. var _this = this;
  94965. this._attachedCamera = camera;
  94966. var scene = this._attachedCamera.getScene();
  94967. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  94968. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94969. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94970. _this._isPointerDown = true;
  94971. return;
  94972. }
  94973. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94974. _this._isPointerDown = false;
  94975. }
  94976. });
  94977. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94978. if (mesh) {
  94979. _this.zoomOnMesh(mesh);
  94980. }
  94981. });
  94982. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94983. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94984. _this._applyUserInteraction();
  94985. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  94986. // back to the default position after a given timeout
  94987. _this._maintainCameraAboveGround();
  94988. });
  94989. };
  94990. FramingBehavior.prototype.detach = function () {
  94991. if (!this._attachedCamera) {
  94992. return;
  94993. }
  94994. var scene = this._attachedCamera.getScene();
  94995. if (this._onPrePointerObservableObserver) {
  94996. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94997. }
  94998. if (this._onAfterCheckInputsObserver) {
  94999. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  95000. }
  95001. if (this._onMeshTargetChangedObserver) {
  95002. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  95003. }
  95004. this._attachedCamera = null;
  95005. };
  95006. /**
  95007. * Targets the given mesh and updates zoom level accordingly.
  95008. * @param mesh The mesh to target.
  95009. * @param radius Optional. If a cached radius position already exists, overrides default.
  95010. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  95011. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  95012. * @param onAnimationEnd Callback triggered at the end of the framing animation
  95013. */
  95014. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  95015. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  95016. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  95017. mesh.computeWorldMatrix(true);
  95018. var boundingBox = mesh.getBoundingInfo().boundingBox;
  95019. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  95020. };
  95021. /**
  95022. * Targets the given mesh with its children and updates zoom level accordingly.
  95023. * @param mesh The mesh to target.
  95024. * @param radius Optional. If a cached radius position already exists, overrides default.
  95025. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  95026. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  95027. * @param onAnimationEnd Callback triggered at the end of the framing animation
  95028. */
  95029. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  95030. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  95031. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  95032. mesh.computeWorldMatrix(true);
  95033. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  95034. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  95035. };
  95036. /**
  95037. * Targets the given meshes with their children and updates zoom level accordingly.
  95038. * @param meshes The mesh to target.
  95039. * @param radius Optional. If a cached radius position already exists, overrides default.
  95040. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  95041. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  95042. * @param onAnimationEnd Callback triggered at the end of the framing animation
  95043. */
  95044. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  95045. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  95046. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  95047. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  95048. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  95049. for (var i = 0; i < meshes.length; i++) {
  95050. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  95051. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  95052. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  95053. }
  95054. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  95055. };
  95056. /**
  95057. * Targets the given mesh and updates zoom level accordingly.
  95058. * @param mesh The mesh to target.
  95059. * @param radius Optional. If a cached radius position already exists, overrides default.
  95060. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  95061. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  95062. * @param onAnimationEnd Callback triggered at the end of the framing animation
  95063. */
  95064. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  95065. var _this = this;
  95066. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  95067. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  95068. var zoomTarget;
  95069. if (!this._attachedCamera) {
  95070. return;
  95071. }
  95072. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  95073. var bottom = minimumWorld.y;
  95074. var top = maximumWorld.y;
  95075. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  95076. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  95077. if (focusOnOriginXZ) {
  95078. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  95079. }
  95080. else {
  95081. var centerWorld = minimumWorld.add(radiusWorld);
  95082. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  95083. }
  95084. if (!this._vectorTransition) {
  95085. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  95086. }
  95087. this._betaIsAnimating = true;
  95088. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  95089. if (animatable) {
  95090. this._animatables.push(animatable);
  95091. }
  95092. // sets the radius and lower radius bounds
  95093. // Small delta ensures camera is not always at lower zoom limit.
  95094. var radius = 0;
  95095. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  95096. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  95097. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  95098. radius = position;
  95099. }
  95100. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  95101. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  95102. if (this._attachedCamera.lowerRadiusLimit === null) {
  95103. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  95104. }
  95105. }
  95106. // Set sensibilities
  95107. var extend = maximumWorld.subtract(minimumWorld).length();
  95108. this._attachedCamera.panningSensibility = 5000 / extend;
  95109. this._attachedCamera.wheelPrecision = 100 / radius;
  95110. // transition to new radius
  95111. if (!this._radiusTransition) {
  95112. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  95113. }
  95114. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  95115. _this.stopAllAnimations();
  95116. if (onAnimationEnd) {
  95117. onAnimationEnd();
  95118. }
  95119. if (_this._attachedCamera) {
  95120. _this._attachedCamera.storeState();
  95121. }
  95122. });
  95123. if (animatable) {
  95124. this._animatables.push(animatable);
  95125. }
  95126. };
  95127. /**
  95128. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  95129. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  95130. * frustum width.
  95131. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  95132. * to fully enclose the mesh in the viewing frustum.
  95133. */
  95134. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  95135. var size = maximumWorld.subtract(minimumWorld);
  95136. var boxVectorGlobalDiagonal = size.length();
  95137. var frustumSlope = this._getFrustumSlope();
  95138. // Formula for setting distance
  95139. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  95140. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  95141. // Horizon distance
  95142. var radius = radiusWithoutFraming * this._radiusScale;
  95143. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  95144. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  95145. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  95146. var camera = this._attachedCamera;
  95147. if (!camera) {
  95148. return 0;
  95149. }
  95150. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  95151. // Don't exceed the requested limit
  95152. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  95153. }
  95154. // Don't exceed the upper radius limit
  95155. if (camera.upperRadiusLimit) {
  95156. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  95157. }
  95158. return distance;
  95159. };
  95160. /**
  95161. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  95162. * is automatically returned to its default position (expected to be above ground plane).
  95163. */
  95164. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  95165. var _this = this;
  95166. if (this._elevationReturnTime < 0) {
  95167. return;
  95168. }
  95169. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  95170. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  95171. var limitBeta = Math.PI * 0.5;
  95172. // Bring the camera back up if below the ground plane
  95173. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  95174. this._betaIsAnimating = true;
  95175. //Transition to new position
  95176. this.stopAllAnimations();
  95177. if (!this._betaTransition) {
  95178. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  95179. }
  95180. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  95181. _this._clearAnimationLocks();
  95182. _this.stopAllAnimations();
  95183. });
  95184. if (animatabe) {
  95185. this._animatables.push(animatabe);
  95186. }
  95187. }
  95188. };
  95189. /**
  95190. * Returns the frustum slope based on the canvas ratio and camera FOV
  95191. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  95192. */
  95193. FramingBehavior.prototype._getFrustumSlope = function () {
  95194. // Calculate the viewport ratio
  95195. // Aspect Ratio is Height/Width.
  95196. var camera = this._attachedCamera;
  95197. if (!camera) {
  95198. return BABYLON.Vector2.Zero();
  95199. }
  95200. var engine = camera.getScene().getEngine();
  95201. var aspectRatio = engine.getAspectRatio(camera);
  95202. // Camera FOV is the vertical field of view (top-bottom) in radians.
  95203. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  95204. var frustumSlopeY = Math.tan(camera.fov / 2);
  95205. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  95206. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  95207. // along the forward vector.
  95208. var frustumSlopeX = frustumSlopeY * aspectRatio;
  95209. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  95210. };
  95211. /**
  95212. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  95213. */
  95214. FramingBehavior.prototype._clearAnimationLocks = function () {
  95215. this._betaIsAnimating = false;
  95216. };
  95217. /**
  95218. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  95219. */
  95220. FramingBehavior.prototype._applyUserInteraction = function () {
  95221. if (this.isUserIsMoving) {
  95222. this._lastInteractionTime = BABYLON.Tools.Now;
  95223. this.stopAllAnimations();
  95224. this._clearAnimationLocks();
  95225. }
  95226. };
  95227. /**
  95228. * Stops and removes all animations that have been applied to the camera
  95229. */
  95230. FramingBehavior.prototype.stopAllAnimations = function () {
  95231. if (this._attachedCamera) {
  95232. this._attachedCamera.animations = [];
  95233. }
  95234. while (this._animatables.length) {
  95235. if (this._animatables[0]) {
  95236. this._animatables[0].onAnimationEnd = null;
  95237. this._animatables[0].stop();
  95238. }
  95239. this._animatables.shift();
  95240. }
  95241. };
  95242. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  95243. /**
  95244. * Gets a value indicating if the user is moving the camera
  95245. */
  95246. get: function () {
  95247. if (!this._attachedCamera) {
  95248. return false;
  95249. }
  95250. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  95251. this._attachedCamera.inertialBetaOffset !== 0 ||
  95252. this._attachedCamera.inertialRadiusOffset !== 0 ||
  95253. this._attachedCamera.inertialPanningX !== 0 ||
  95254. this._attachedCamera.inertialPanningY !== 0 ||
  95255. this._isPointerDown;
  95256. },
  95257. enumerable: true,
  95258. configurable: true
  95259. });
  95260. /**
  95261. * The easing function used by animations
  95262. */
  95263. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  95264. /**
  95265. * The easing mode used by animations
  95266. */
  95267. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  95268. // Statics
  95269. /**
  95270. * The camera can move all the way towards the mesh.
  95271. */
  95272. FramingBehavior.IgnoreBoundsSizeMode = 0;
  95273. /**
  95274. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  95275. */
  95276. FramingBehavior.FitFrustumSidesMode = 1;
  95277. return FramingBehavior;
  95278. }());
  95279. BABYLON.FramingBehavior = FramingBehavior;
  95280. })(BABYLON || (BABYLON = {}));
  95281. //# sourceMappingURL=babylon.framingBehavior.js.map
  95282. var BABYLON;
  95283. (function (BABYLON) {
  95284. /**
  95285. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  95286. */
  95287. var BouncingBehavior = /** @class */ (function () {
  95288. function BouncingBehavior() {
  95289. /**
  95290. * The duration of the animation, in milliseconds
  95291. */
  95292. this.transitionDuration = 450;
  95293. /**
  95294. * Length of the distance animated by the transition when lower radius is reached
  95295. */
  95296. this.lowerRadiusTransitionRange = 2;
  95297. /**
  95298. * Length of the distance animated by the transition when upper radius is reached
  95299. */
  95300. this.upperRadiusTransitionRange = -2;
  95301. this._autoTransitionRange = false;
  95302. // Animations
  95303. this._radiusIsAnimating = false;
  95304. this._radiusBounceTransition = null;
  95305. this._animatables = new Array();
  95306. }
  95307. Object.defineProperty(BouncingBehavior.prototype, "name", {
  95308. get: function () {
  95309. return "Bouncing";
  95310. },
  95311. enumerable: true,
  95312. configurable: true
  95313. });
  95314. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  95315. /**
  95316. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  95317. */
  95318. get: function () {
  95319. return this._autoTransitionRange;
  95320. },
  95321. /**
  95322. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  95323. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  95324. */
  95325. set: function (value) {
  95326. var _this = this;
  95327. if (this._autoTransitionRange === value) {
  95328. return;
  95329. }
  95330. this._autoTransitionRange = value;
  95331. var camera = this._attachedCamera;
  95332. if (!camera) {
  95333. return;
  95334. }
  95335. if (value) {
  95336. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  95337. if (!mesh) {
  95338. return;
  95339. }
  95340. mesh.computeWorldMatrix(true);
  95341. var diagonal = mesh.getBoundingInfo().diagonalLength;
  95342. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  95343. _this.upperRadiusTransitionRange = diagonal * 0.05;
  95344. });
  95345. }
  95346. else if (this._onMeshTargetChangedObserver) {
  95347. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  95348. }
  95349. },
  95350. enumerable: true,
  95351. configurable: true
  95352. });
  95353. BouncingBehavior.prototype.init = function () {
  95354. // Do notihng
  95355. };
  95356. BouncingBehavior.prototype.attach = function (camera) {
  95357. var _this = this;
  95358. this._attachedCamera = camera;
  95359. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  95360. if (!_this._attachedCamera) {
  95361. return;
  95362. }
  95363. // Add the bounce animation to the lower radius limit
  95364. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  95365. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  95366. }
  95367. // Add the bounce animation to the upper radius limit
  95368. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  95369. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  95370. }
  95371. });
  95372. };
  95373. BouncingBehavior.prototype.detach = function () {
  95374. if (!this._attachedCamera) {
  95375. return;
  95376. }
  95377. if (this._onAfterCheckInputsObserver) {
  95378. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  95379. }
  95380. if (this._onMeshTargetChangedObserver) {
  95381. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  95382. }
  95383. this._attachedCamera = null;
  95384. };
  95385. /**
  95386. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  95387. * @param radiusLimit The limit to check against.
  95388. * @return Bool to indicate if at limit.
  95389. */
  95390. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  95391. if (!this._attachedCamera) {
  95392. return false;
  95393. }
  95394. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  95395. return true;
  95396. }
  95397. return false;
  95398. };
  95399. /**
  95400. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  95401. * @param radiusDelta The delta by which to animate to. Can be negative.
  95402. */
  95403. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  95404. var _this = this;
  95405. if (!this._attachedCamera) {
  95406. return;
  95407. }
  95408. if (!this._radiusBounceTransition) {
  95409. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  95410. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  95411. }
  95412. // Prevent zoom until bounce has completed
  95413. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  95414. this._attachedCamera.wheelPrecision = Infinity;
  95415. this._attachedCamera.inertialRadiusOffset = 0;
  95416. // Animate to the radius limit
  95417. this.stopAllAnimations();
  95418. this._radiusIsAnimating = true;
  95419. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  95420. if (animatable) {
  95421. this._animatables.push(animatable);
  95422. }
  95423. };
  95424. /**
  95425. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  95426. */
  95427. BouncingBehavior.prototype._clearAnimationLocks = function () {
  95428. this._radiusIsAnimating = false;
  95429. if (this._attachedCamera) {
  95430. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  95431. }
  95432. };
  95433. /**
  95434. * Stops and removes all animations that have been applied to the camera
  95435. */
  95436. BouncingBehavior.prototype.stopAllAnimations = function () {
  95437. if (this._attachedCamera) {
  95438. this._attachedCamera.animations = [];
  95439. }
  95440. while (this._animatables.length) {
  95441. this._animatables[0].onAnimationEnd = null;
  95442. this._animatables[0].stop();
  95443. this._animatables.shift();
  95444. }
  95445. };
  95446. /**
  95447. * The easing function used by animations
  95448. */
  95449. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  95450. /**
  95451. * The easing mode used by animations
  95452. */
  95453. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  95454. return BouncingBehavior;
  95455. }());
  95456. BABYLON.BouncingBehavior = BouncingBehavior;
  95457. })(BABYLON || (BABYLON = {}));
  95458. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  95459. var BABYLON;
  95460. (function (BABYLON) {
  95461. var AutoRotationBehavior = /** @class */ (function () {
  95462. function AutoRotationBehavior() {
  95463. this._zoomStopsAnimation = false;
  95464. this._idleRotationSpeed = 0.05;
  95465. this._idleRotationWaitTime = 2000;
  95466. this._idleRotationSpinupTime = 2000;
  95467. this._isPointerDown = false;
  95468. this._lastFrameTime = null;
  95469. this._lastInteractionTime = -Infinity;
  95470. this._cameraRotationSpeed = 0;
  95471. this._lastFrameRadius = 0;
  95472. }
  95473. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  95474. get: function () {
  95475. return "AutoRotation";
  95476. },
  95477. enumerable: true,
  95478. configurable: true
  95479. });
  95480. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  95481. /**
  95482. * Gets the flag that indicates if user zooming should stop animation.
  95483. */
  95484. get: function () {
  95485. return this._zoomStopsAnimation;
  95486. },
  95487. /**
  95488. * Sets the flag that indicates if user zooming should stop animation.
  95489. */
  95490. set: function (flag) {
  95491. this._zoomStopsAnimation = flag;
  95492. },
  95493. enumerable: true,
  95494. configurable: true
  95495. });
  95496. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  95497. /**
  95498. * Gets the default speed at which the camera rotates around the model.
  95499. */
  95500. get: function () {
  95501. return this._idleRotationSpeed;
  95502. },
  95503. /**
  95504. * Sets the default speed at which the camera rotates around the model.
  95505. */
  95506. set: function (speed) {
  95507. this._idleRotationSpeed = speed;
  95508. },
  95509. enumerable: true,
  95510. configurable: true
  95511. });
  95512. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  95513. /**
  95514. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  95515. */
  95516. get: function () {
  95517. return this._idleRotationWaitTime;
  95518. },
  95519. /**
  95520. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  95521. */
  95522. set: function (time) {
  95523. this._idleRotationWaitTime = time;
  95524. },
  95525. enumerable: true,
  95526. configurable: true
  95527. });
  95528. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  95529. /**
  95530. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  95531. */
  95532. get: function () {
  95533. return this._idleRotationSpinupTime;
  95534. },
  95535. /**
  95536. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  95537. */
  95538. set: function (time) {
  95539. this._idleRotationSpinupTime = time;
  95540. },
  95541. enumerable: true,
  95542. configurable: true
  95543. });
  95544. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  95545. /**
  95546. * Gets a value indicating if the camera is currently rotating because of this behavior
  95547. */
  95548. get: function () {
  95549. return Math.abs(this._cameraRotationSpeed) > 0;
  95550. },
  95551. enumerable: true,
  95552. configurable: true
  95553. });
  95554. AutoRotationBehavior.prototype.init = function () {
  95555. // Do notihng
  95556. };
  95557. AutoRotationBehavior.prototype.attach = function (camera) {
  95558. var _this = this;
  95559. this._attachedCamera = camera;
  95560. var scene = this._attachedCamera.getScene();
  95561. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  95562. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  95563. _this._isPointerDown = true;
  95564. return;
  95565. }
  95566. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  95567. _this._isPointerDown = false;
  95568. }
  95569. });
  95570. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  95571. var now = BABYLON.Tools.Now;
  95572. var dt = 0;
  95573. if (_this._lastFrameTime != null) {
  95574. dt = now - _this._lastFrameTime;
  95575. }
  95576. _this._lastFrameTime = now;
  95577. // Stop the animation if there is user interaction and the animation should stop for this interaction
  95578. _this._applyUserInteraction();
  95579. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  95580. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  95581. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  95582. // Step camera rotation by rotation speed
  95583. if (_this._attachedCamera) {
  95584. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  95585. }
  95586. });
  95587. };
  95588. AutoRotationBehavior.prototype.detach = function () {
  95589. if (!this._attachedCamera) {
  95590. return;
  95591. }
  95592. var scene = this._attachedCamera.getScene();
  95593. if (this._onPrePointerObservableObserver) {
  95594. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  95595. }
  95596. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  95597. this._attachedCamera = null;
  95598. };
  95599. /**
  95600. * Returns true if user is scrolling.
  95601. * @return true if user is scrolling.
  95602. */
  95603. AutoRotationBehavior.prototype._userIsZooming = function () {
  95604. if (!this._attachedCamera) {
  95605. return false;
  95606. }
  95607. return this._attachedCamera.inertialRadiusOffset !== 0;
  95608. };
  95609. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  95610. if (!this._attachedCamera) {
  95611. return false;
  95612. }
  95613. var zoomHasHitLimit = false;
  95614. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  95615. zoomHasHitLimit = true;
  95616. }
  95617. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  95618. this._lastFrameRadius = this._attachedCamera.radius;
  95619. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  95620. };
  95621. /**
  95622. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  95623. */
  95624. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  95625. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  95626. this._lastInteractionTime = BABYLON.Tools.Now;
  95627. }
  95628. };
  95629. // Tools
  95630. AutoRotationBehavior.prototype._userIsMoving = function () {
  95631. if (!this._attachedCamera) {
  95632. return false;
  95633. }
  95634. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  95635. this._attachedCamera.inertialBetaOffset !== 0 ||
  95636. this._attachedCamera.inertialRadiusOffset !== 0 ||
  95637. this._attachedCamera.inertialPanningX !== 0 ||
  95638. this._attachedCamera.inertialPanningY !== 0 ||
  95639. this._isPointerDown;
  95640. };
  95641. return AutoRotationBehavior;
  95642. }());
  95643. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  95644. })(BABYLON || (BABYLON = {}));
  95645. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  95646. var BABYLON;
  95647. (function (BABYLON) {
  95648. var NullEngineOptions = /** @class */ (function () {
  95649. function NullEngineOptions() {
  95650. this.renderWidth = 512;
  95651. this.renderHeight = 256;
  95652. this.textureSize = 512;
  95653. this.deterministicLockstep = false;
  95654. this.lockstepMaxSteps = 4;
  95655. }
  95656. return NullEngineOptions;
  95657. }());
  95658. BABYLON.NullEngineOptions = NullEngineOptions;
  95659. /**
  95660. * The null engine class provides support for headless version of babylon.js.
  95661. * This can be used in server side scenario or for testing purposes
  95662. */
  95663. var NullEngine = /** @class */ (function (_super) {
  95664. __extends(NullEngine, _super);
  95665. function NullEngine(options) {
  95666. if (options === void 0) { options = new NullEngineOptions(); }
  95667. var _this = _super.call(this, null) || this;
  95668. if (options.deterministicLockstep === undefined) {
  95669. options.deterministicLockstep = false;
  95670. }
  95671. if (options.lockstepMaxSteps === undefined) {
  95672. options.lockstepMaxSteps = 4;
  95673. }
  95674. _this._options = options;
  95675. // Init caps
  95676. // We consider we are on a webgl1 capable device
  95677. _this._caps = new BABYLON.EngineCapabilities();
  95678. _this._caps.maxTexturesImageUnits = 16;
  95679. _this._caps.maxVertexTextureImageUnits = 16;
  95680. _this._caps.maxTextureSize = 512;
  95681. _this._caps.maxCubemapTextureSize = 512;
  95682. _this._caps.maxRenderTextureSize = 512;
  95683. _this._caps.maxVertexAttribs = 16;
  95684. _this._caps.maxVaryingVectors = 16;
  95685. _this._caps.maxFragmentUniformVectors = 16;
  95686. _this._caps.maxVertexUniformVectors = 16;
  95687. // Extensions
  95688. _this._caps.standardDerivatives = false;
  95689. _this._caps.astc = null;
  95690. _this._caps.s3tc = null;
  95691. _this._caps.pvrtc = null;
  95692. _this._caps.etc1 = null;
  95693. _this._caps.etc2 = null;
  95694. _this._caps.textureAnisotropicFilterExtension = null;
  95695. _this._caps.maxAnisotropy = 0;
  95696. _this._caps.uintIndices = false;
  95697. _this._caps.fragmentDepthSupported = false;
  95698. _this._caps.highPrecisionShaderSupported = true;
  95699. _this._caps.colorBufferFloat = false;
  95700. _this._caps.textureFloat = false;
  95701. _this._caps.textureFloatLinearFiltering = false;
  95702. _this._caps.textureFloatRender = false;
  95703. _this._caps.textureHalfFloat = false;
  95704. _this._caps.textureHalfFloatLinearFiltering = false;
  95705. _this._caps.textureHalfFloatRender = false;
  95706. _this._caps.textureLOD = false;
  95707. _this._caps.drawBuffersExtension = false;
  95708. _this._caps.depthTextureExtension = false;
  95709. _this._caps.vertexArrayObject = false;
  95710. _this._caps.instancedArrays = false;
  95711. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  95712. // Wrappers
  95713. if (typeof URL === "undefined") {
  95714. URL = {
  95715. createObjectURL: function () { },
  95716. revokeObjectURL: function () { }
  95717. };
  95718. }
  95719. if (typeof Blob === "undefined") {
  95720. Blob = function () { };
  95721. }
  95722. return _this;
  95723. }
  95724. NullEngine.prototype.isDeterministicLockStep = function () {
  95725. return this._options.deterministicLockstep;
  95726. };
  95727. NullEngine.prototype.getLockstepMaxSteps = function () {
  95728. return this._options.lockstepMaxSteps;
  95729. };
  95730. NullEngine.prototype.getHardwareScalingLevel = function () {
  95731. return 1.0;
  95732. };
  95733. NullEngine.prototype.createVertexBuffer = function (vertices) {
  95734. return {
  95735. capacity: 0,
  95736. references: 1,
  95737. is32Bits: false
  95738. };
  95739. };
  95740. NullEngine.prototype.createIndexBuffer = function (indices) {
  95741. return {
  95742. capacity: 0,
  95743. references: 1,
  95744. is32Bits: false
  95745. };
  95746. };
  95747. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  95748. if (stencil === void 0) { stencil = false; }
  95749. };
  95750. NullEngine.prototype.getRenderWidth = function (useScreen) {
  95751. if (useScreen === void 0) { useScreen = false; }
  95752. if (!useScreen && this._currentRenderTarget) {
  95753. return this._currentRenderTarget.width;
  95754. }
  95755. return this._options.renderWidth;
  95756. };
  95757. NullEngine.prototype.getRenderHeight = function (useScreen) {
  95758. if (useScreen === void 0) { useScreen = false; }
  95759. if (!useScreen && this._currentRenderTarget) {
  95760. return this._currentRenderTarget.height;
  95761. }
  95762. return this._options.renderHeight;
  95763. };
  95764. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  95765. this._cachedViewport = viewport;
  95766. };
  95767. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  95768. return {
  95769. transformFeedback: null,
  95770. __SPECTOR_rebuildProgram: null
  95771. };
  95772. };
  95773. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  95774. return [];
  95775. };
  95776. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  95777. return [];
  95778. };
  95779. NullEngine.prototype.bindSamplers = function (effect) {
  95780. this._currentEffect = null;
  95781. };
  95782. NullEngine.prototype.enableEffect = function (effect) {
  95783. this._currentEffect = effect;
  95784. if (effect.onBind) {
  95785. effect.onBind(effect);
  95786. }
  95787. effect.onBindObservable.notifyObservers(effect);
  95788. };
  95789. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  95790. if (zOffset === void 0) { zOffset = 0; }
  95791. if (reverseSide === void 0) { reverseSide = false; }
  95792. };
  95793. NullEngine.prototype.setIntArray = function (uniform, array) {
  95794. };
  95795. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  95796. };
  95797. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  95798. };
  95799. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  95800. };
  95801. NullEngine.prototype.setFloatArray = function (uniform, array) {
  95802. };
  95803. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  95804. };
  95805. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  95806. };
  95807. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  95808. };
  95809. NullEngine.prototype.setArray = function (uniform, array) {
  95810. };
  95811. NullEngine.prototype.setArray2 = function (uniform, array) {
  95812. };
  95813. NullEngine.prototype.setArray3 = function (uniform, array) {
  95814. };
  95815. NullEngine.prototype.setArray4 = function (uniform, array) {
  95816. };
  95817. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  95818. };
  95819. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  95820. };
  95821. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  95822. };
  95823. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  95824. };
  95825. NullEngine.prototype.setFloat = function (uniform, value) {
  95826. };
  95827. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  95828. };
  95829. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  95830. };
  95831. NullEngine.prototype.setBool = function (uniform, bool) {
  95832. };
  95833. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  95834. };
  95835. NullEngine.prototype.setColor3 = function (uniform, color3) {
  95836. };
  95837. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  95838. };
  95839. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  95840. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  95841. if (this._alphaMode === mode) {
  95842. return;
  95843. }
  95844. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  95845. if (!noDepthWriteChange) {
  95846. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  95847. }
  95848. this._alphaMode = mode;
  95849. };
  95850. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  95851. };
  95852. NullEngine.prototype.wipeCaches = function (bruteForce) {
  95853. if (this.preventCacheWipeBetweenFrames) {
  95854. return;
  95855. }
  95856. this.resetTextureCache();
  95857. this._currentEffect = null;
  95858. if (bruteForce) {
  95859. this._currentProgram = null;
  95860. this._stencilState.reset();
  95861. this._depthCullingState.reset();
  95862. this._alphaState.reset();
  95863. }
  95864. this._cachedVertexBuffers = null;
  95865. this._cachedIndexBuffer = null;
  95866. this._cachedEffectForVertexBuffers = null;
  95867. };
  95868. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  95869. };
  95870. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  95871. };
  95872. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  95873. };
  95874. NullEngine.prototype._createTexture = function () {
  95875. return {};
  95876. };
  95877. NullEngine.prototype._releaseTexture = function (texture) {
  95878. };
  95879. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  95880. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95881. if (onLoad === void 0) { onLoad = null; }
  95882. if (onError === void 0) { onError = null; }
  95883. if (buffer === void 0) { buffer = null; }
  95884. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  95885. var url = String(urlArg);
  95886. texture.url = url;
  95887. texture.generateMipMaps = !noMipmap;
  95888. texture.samplingMode = samplingMode;
  95889. texture.invertY = invertY;
  95890. texture.baseWidth = this._options.textureSize;
  95891. texture.baseHeight = this._options.textureSize;
  95892. texture.width = this._options.textureSize;
  95893. texture.height = this._options.textureSize;
  95894. if (format) {
  95895. texture.format = format;
  95896. }
  95897. texture.isReady = true;
  95898. if (onLoad) {
  95899. onLoad();
  95900. }
  95901. this._internalTexturesCache.push(texture);
  95902. return texture;
  95903. };
  95904. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  95905. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  95906. if (options !== undefined && typeof options === "object") {
  95907. fullOptions.generateMipMaps = options.generateMipMaps;
  95908. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  95909. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  95910. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  95911. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  95912. }
  95913. else {
  95914. fullOptions.generateMipMaps = options;
  95915. fullOptions.generateDepthBuffer = true;
  95916. fullOptions.generateStencilBuffer = false;
  95917. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95918. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  95919. }
  95920. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  95921. var width = size.width || size;
  95922. var height = size.height || size;
  95923. texture._depthStencilBuffer = {};
  95924. texture._framebuffer = {};
  95925. texture.baseWidth = width;
  95926. texture.baseHeight = height;
  95927. texture.width = width;
  95928. texture.height = height;
  95929. texture.isReady = true;
  95930. texture.samples = 1;
  95931. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  95932. texture.samplingMode = fullOptions.samplingMode;
  95933. texture.type = fullOptions.type;
  95934. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  95935. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  95936. this._internalTexturesCache.push(texture);
  95937. return texture;
  95938. };
  95939. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  95940. texture.samplingMode = samplingMode;
  95941. };
  95942. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  95943. if (this._currentRenderTarget) {
  95944. this.unBindFramebuffer(this._currentRenderTarget);
  95945. }
  95946. this._currentRenderTarget = texture;
  95947. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  95948. if (this._cachedViewport && !forceFullscreenViewport) {
  95949. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  95950. }
  95951. };
  95952. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  95953. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  95954. this._currentRenderTarget = null;
  95955. if (onBeforeUnbind) {
  95956. if (texture._MSAAFramebuffer) {
  95957. this._currentFramebuffer = texture._framebuffer;
  95958. }
  95959. onBeforeUnbind();
  95960. }
  95961. this._currentFramebuffer = null;
  95962. };
  95963. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  95964. var vbo = {
  95965. capacity: 1,
  95966. references: 1,
  95967. is32Bits: false
  95968. };
  95969. return vbo;
  95970. };
  95971. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  95972. if (offset === void 0) { offset = 0; }
  95973. };
  95974. /**
  95975. * Updates a dynamic vertex buffer.
  95976. * @param vertexBuffer the vertex buffer to update
  95977. * @param data the data used to update the vertex buffer
  95978. * @param byteOffset the byte offset of the data (optional)
  95979. * @param byteLength the byte length of the data (optional)
  95980. */
  95981. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  95982. };
  95983. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  95984. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  95985. this._boundTexturesCache[this._activeChannel] = texture;
  95986. }
  95987. };
  95988. NullEngine.prototype._bindTexture = function (channel, texture) {
  95989. if (channel < 0) {
  95990. return;
  95991. }
  95992. this._bindTextureDirectly(0, texture);
  95993. };
  95994. NullEngine.prototype._releaseBuffer = function (buffer) {
  95995. buffer.references--;
  95996. if (buffer.references === 0) {
  95997. return true;
  95998. }
  95999. return false;
  96000. };
  96001. NullEngine.prototype.releaseEffects = function () {
  96002. };
  96003. return NullEngine;
  96004. }(BABYLON.Engine));
  96005. BABYLON.NullEngine = NullEngine;
  96006. })(BABYLON || (BABYLON = {}));
  96007. //# sourceMappingURL=babylon.nullEngine.js.map
  96008. var BABYLON;
  96009. (function (BABYLON) {
  96010. /**
  96011. * This class can be used to get instrumentation data from a Babylon engine
  96012. */
  96013. var EngineInstrumentation = /** @class */ (function () {
  96014. function EngineInstrumentation(engine) {
  96015. this.engine = engine;
  96016. this._captureGPUFrameTime = false;
  96017. this._gpuFrameTime = new BABYLON.PerfCounter();
  96018. this._captureShaderCompilationTime = false;
  96019. this._shaderCompilationTime = new BABYLON.PerfCounter();
  96020. // Observers
  96021. this._onBeginFrameObserver = null;
  96022. this._onEndFrameObserver = null;
  96023. this._onBeforeShaderCompilationObserver = null;
  96024. this._onAfterShaderCompilationObserver = null;
  96025. }
  96026. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  96027. // Properties
  96028. /**
  96029. * Gets the perf counter used for GPU frame time
  96030. */
  96031. get: function () {
  96032. return this._gpuFrameTime;
  96033. },
  96034. enumerable: true,
  96035. configurable: true
  96036. });
  96037. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  96038. /**
  96039. * Gets the GPU frame time capture status
  96040. */
  96041. get: function () {
  96042. return this._captureGPUFrameTime;
  96043. },
  96044. /**
  96045. * Enable or disable the GPU frame time capture
  96046. */
  96047. set: function (value) {
  96048. var _this = this;
  96049. if (value === this._captureGPUFrameTime) {
  96050. return;
  96051. }
  96052. this._captureGPUFrameTime = value;
  96053. if (value) {
  96054. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  96055. if (!_this._gpuFrameTimeToken) {
  96056. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  96057. }
  96058. });
  96059. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  96060. if (!_this._gpuFrameTimeToken) {
  96061. return;
  96062. }
  96063. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  96064. if (time > -1) {
  96065. _this._gpuFrameTimeToken = null;
  96066. _this._gpuFrameTime.fetchNewFrame();
  96067. _this._gpuFrameTime.addCount(time, true);
  96068. }
  96069. });
  96070. }
  96071. else {
  96072. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  96073. this._onBeginFrameObserver = null;
  96074. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  96075. this._onEndFrameObserver = null;
  96076. }
  96077. },
  96078. enumerable: true,
  96079. configurable: true
  96080. });
  96081. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  96082. /**
  96083. * Gets the perf counter used for shader compilation time
  96084. */
  96085. get: function () {
  96086. return this._shaderCompilationTime;
  96087. },
  96088. enumerable: true,
  96089. configurable: true
  96090. });
  96091. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  96092. /**
  96093. * Gets the shader compilation time capture status
  96094. */
  96095. get: function () {
  96096. return this._captureShaderCompilationTime;
  96097. },
  96098. /**
  96099. * Enable or disable the shader compilation time capture
  96100. */
  96101. set: function (value) {
  96102. var _this = this;
  96103. if (value === this._captureShaderCompilationTime) {
  96104. return;
  96105. }
  96106. this._captureShaderCompilationTime = value;
  96107. if (value) {
  96108. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  96109. _this._shaderCompilationTime.fetchNewFrame();
  96110. _this._shaderCompilationTime.beginMonitoring();
  96111. });
  96112. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  96113. _this._shaderCompilationTime.endMonitoring();
  96114. });
  96115. }
  96116. else {
  96117. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  96118. this._onBeforeShaderCompilationObserver = null;
  96119. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  96120. this._onAfterShaderCompilationObserver = null;
  96121. }
  96122. },
  96123. enumerable: true,
  96124. configurable: true
  96125. });
  96126. EngineInstrumentation.prototype.dispose = function () {
  96127. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  96128. this._onBeginFrameObserver = null;
  96129. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  96130. this._onEndFrameObserver = null;
  96131. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  96132. this._onBeforeShaderCompilationObserver = null;
  96133. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  96134. this._onAfterShaderCompilationObserver = null;
  96135. this.engine = null;
  96136. };
  96137. return EngineInstrumentation;
  96138. }());
  96139. BABYLON.EngineInstrumentation = EngineInstrumentation;
  96140. })(BABYLON || (BABYLON = {}));
  96141. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  96142. var BABYLON;
  96143. (function (BABYLON) {
  96144. /**
  96145. * This class can be used to get instrumentation data from a Babylon engine
  96146. */
  96147. var SceneInstrumentation = /** @class */ (function () {
  96148. function SceneInstrumentation(scene) {
  96149. var _this = this;
  96150. this.scene = scene;
  96151. this._captureActiveMeshesEvaluationTime = false;
  96152. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  96153. this._captureRenderTargetsRenderTime = false;
  96154. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  96155. this._captureFrameTime = false;
  96156. this._frameTime = new BABYLON.PerfCounter();
  96157. this._captureRenderTime = false;
  96158. this._renderTime = new BABYLON.PerfCounter();
  96159. this._captureInterFrameTime = false;
  96160. this._interFrameTime = new BABYLON.PerfCounter();
  96161. this._captureParticlesRenderTime = false;
  96162. this._particlesRenderTime = new BABYLON.PerfCounter();
  96163. this._captureSpritesRenderTime = false;
  96164. this._spritesRenderTime = new BABYLON.PerfCounter();
  96165. this._capturePhysicsTime = false;
  96166. this._physicsTime = new BABYLON.PerfCounter();
  96167. this._captureAnimationsTime = false;
  96168. this._animationsTime = new BABYLON.PerfCounter();
  96169. // Observers
  96170. this._onBeforeActiveMeshesEvaluationObserver = null;
  96171. this._onAfterActiveMeshesEvaluationObserver = null;
  96172. this._onBeforeRenderTargetsRenderObserver = null;
  96173. this._onAfterRenderTargetsRenderObserver = null;
  96174. this._onAfterRenderObserver = null;
  96175. this._onBeforeDrawPhaseObserver = null;
  96176. this._onAfterDrawPhaseObserver = null;
  96177. this._onBeforeAnimationsObserver = null;
  96178. this._onBeforeParticlesRenderingObserver = null;
  96179. this._onAfterParticlesRenderingObserver = null;
  96180. this._onBeforeSpritesRenderingObserver = null;
  96181. this._onAfterSpritesRenderingObserver = null;
  96182. this._onBeforePhysicsObserver = null;
  96183. this._onAfterPhysicsObserver = null;
  96184. this._onAfterAnimationsObserver = null;
  96185. // Before render
  96186. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  96187. if (_this._captureActiveMeshesEvaluationTime) {
  96188. _this._activeMeshesEvaluationTime.fetchNewFrame();
  96189. }
  96190. if (_this._captureRenderTargetsRenderTime) {
  96191. _this._renderTargetsRenderTime.fetchNewFrame();
  96192. }
  96193. if (_this._captureFrameTime) {
  96194. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  96195. _this._frameTime.beginMonitoring();
  96196. }
  96197. if (_this._captureInterFrameTime) {
  96198. _this._interFrameTime.endMonitoring();
  96199. }
  96200. if (_this._captureParticlesRenderTime) {
  96201. _this._particlesRenderTime.fetchNewFrame();
  96202. }
  96203. if (_this._captureSpritesRenderTime) {
  96204. _this._spritesRenderTime.fetchNewFrame();
  96205. }
  96206. if (_this._captureAnimationsTime) {
  96207. _this._animationsTime.beginMonitoring();
  96208. }
  96209. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  96210. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  96211. });
  96212. // After render
  96213. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  96214. if (_this._captureFrameTime) {
  96215. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  96216. _this._frameTime.endMonitoring();
  96217. }
  96218. if (_this._captureRenderTime) {
  96219. _this._renderTime.endMonitoring(false);
  96220. }
  96221. if (_this._captureInterFrameTime) {
  96222. _this._interFrameTime.beginMonitoring();
  96223. }
  96224. });
  96225. }
  96226. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  96227. // Properties
  96228. /**
  96229. * Gets the perf counter used for active meshes evaluation time
  96230. */
  96231. get: function () {
  96232. return this._activeMeshesEvaluationTime;
  96233. },
  96234. enumerable: true,
  96235. configurable: true
  96236. });
  96237. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  96238. /**
  96239. * Gets the active meshes evaluation time capture status
  96240. */
  96241. get: function () {
  96242. return this._captureActiveMeshesEvaluationTime;
  96243. },
  96244. /**
  96245. * Enable or disable the active meshes evaluation time capture
  96246. */
  96247. set: function (value) {
  96248. var _this = this;
  96249. if (value === this._captureActiveMeshesEvaluationTime) {
  96250. return;
  96251. }
  96252. this._captureActiveMeshesEvaluationTime = value;
  96253. if (value) {
  96254. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  96255. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  96256. _this._activeMeshesEvaluationTime.beginMonitoring();
  96257. });
  96258. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  96259. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  96260. _this._activeMeshesEvaluationTime.endMonitoring();
  96261. });
  96262. }
  96263. else {
  96264. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  96265. this._onBeforeActiveMeshesEvaluationObserver = null;
  96266. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  96267. this._onAfterActiveMeshesEvaluationObserver = null;
  96268. }
  96269. },
  96270. enumerable: true,
  96271. configurable: true
  96272. });
  96273. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  96274. /**
  96275. * Gets the perf counter used for render targets render time
  96276. */
  96277. get: function () {
  96278. return this._renderTargetsRenderTime;
  96279. },
  96280. enumerable: true,
  96281. configurable: true
  96282. });
  96283. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  96284. /**
  96285. * Gets the render targets render time capture status
  96286. */
  96287. get: function () {
  96288. return this._captureRenderTargetsRenderTime;
  96289. },
  96290. /**
  96291. * Enable or disable the render targets render time capture
  96292. */
  96293. set: function (value) {
  96294. var _this = this;
  96295. if (value === this._captureRenderTargetsRenderTime) {
  96296. return;
  96297. }
  96298. this._captureRenderTargetsRenderTime = value;
  96299. if (value) {
  96300. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  96301. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  96302. _this._renderTargetsRenderTime.beginMonitoring();
  96303. });
  96304. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  96305. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  96306. _this._renderTargetsRenderTime.endMonitoring(false);
  96307. });
  96308. }
  96309. else {
  96310. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  96311. this._onBeforeRenderTargetsRenderObserver = null;
  96312. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  96313. this._onAfterRenderTargetsRenderObserver = null;
  96314. }
  96315. },
  96316. enumerable: true,
  96317. configurable: true
  96318. });
  96319. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  96320. /**
  96321. * Gets the perf counter used for particles render time
  96322. */
  96323. get: function () {
  96324. return this._particlesRenderTime;
  96325. },
  96326. enumerable: true,
  96327. configurable: true
  96328. });
  96329. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  96330. /**
  96331. * Gets the particles render time capture status
  96332. */
  96333. get: function () {
  96334. return this._captureParticlesRenderTime;
  96335. },
  96336. /**
  96337. * Enable or disable the particles render time capture
  96338. */
  96339. set: function (value) {
  96340. var _this = this;
  96341. if (value === this._captureParticlesRenderTime) {
  96342. return;
  96343. }
  96344. this._captureParticlesRenderTime = value;
  96345. if (value) {
  96346. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  96347. BABYLON.Tools.StartPerformanceCounter("Particles");
  96348. _this._particlesRenderTime.beginMonitoring();
  96349. });
  96350. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  96351. BABYLON.Tools.EndPerformanceCounter("Particles");
  96352. _this._particlesRenderTime.endMonitoring(false);
  96353. });
  96354. }
  96355. else {
  96356. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  96357. this._onBeforeParticlesRenderingObserver = null;
  96358. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  96359. this._onAfterParticlesRenderingObserver = null;
  96360. }
  96361. },
  96362. enumerable: true,
  96363. configurable: true
  96364. });
  96365. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  96366. /**
  96367. * Gets the perf counter used for sprites render time
  96368. */
  96369. get: function () {
  96370. return this._spritesRenderTime;
  96371. },
  96372. enumerable: true,
  96373. configurable: true
  96374. });
  96375. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  96376. /**
  96377. * Gets the sprites render time capture status
  96378. */
  96379. get: function () {
  96380. return this._captureSpritesRenderTime;
  96381. },
  96382. /**
  96383. * Enable or disable the sprites render time capture
  96384. */
  96385. set: function (value) {
  96386. var _this = this;
  96387. if (value === this._captureSpritesRenderTime) {
  96388. return;
  96389. }
  96390. this._captureSpritesRenderTime = value;
  96391. if (value) {
  96392. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  96393. BABYLON.Tools.StartPerformanceCounter("Sprites");
  96394. _this._spritesRenderTime.beginMonitoring();
  96395. });
  96396. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  96397. BABYLON.Tools.EndPerformanceCounter("Sprites");
  96398. _this._spritesRenderTime.endMonitoring(false);
  96399. });
  96400. }
  96401. else {
  96402. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  96403. this._onBeforeSpritesRenderingObserver = null;
  96404. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  96405. this._onAfterSpritesRenderingObserver = null;
  96406. }
  96407. },
  96408. enumerable: true,
  96409. configurable: true
  96410. });
  96411. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  96412. /**
  96413. * Gets the perf counter used for physics time
  96414. */
  96415. get: function () {
  96416. return this._physicsTime;
  96417. },
  96418. enumerable: true,
  96419. configurable: true
  96420. });
  96421. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  96422. /**
  96423. * Gets the physics time capture status
  96424. */
  96425. get: function () {
  96426. return this._capturePhysicsTime;
  96427. },
  96428. /**
  96429. * Enable or disable the physics time capture
  96430. */
  96431. set: function (value) {
  96432. var _this = this;
  96433. if (value === this._capturePhysicsTime) {
  96434. return;
  96435. }
  96436. this._capturePhysicsTime = value;
  96437. if (value) {
  96438. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  96439. BABYLON.Tools.StartPerformanceCounter("Physics");
  96440. _this._physicsTime.beginMonitoring();
  96441. });
  96442. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  96443. BABYLON.Tools.EndPerformanceCounter("Physics");
  96444. _this._physicsTime.endMonitoring();
  96445. });
  96446. }
  96447. else {
  96448. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  96449. this._onBeforePhysicsObserver = null;
  96450. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  96451. this._onAfterPhysicsObserver = null;
  96452. }
  96453. },
  96454. enumerable: true,
  96455. configurable: true
  96456. });
  96457. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  96458. /**
  96459. * Gets the perf counter used for animations time
  96460. */
  96461. get: function () {
  96462. return this._animationsTime;
  96463. },
  96464. enumerable: true,
  96465. configurable: true
  96466. });
  96467. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  96468. /**
  96469. * Gets the animations time capture status
  96470. */
  96471. get: function () {
  96472. return this._captureAnimationsTime;
  96473. },
  96474. /**
  96475. * Enable or disable the animations time capture
  96476. */
  96477. set: function (value) {
  96478. var _this = this;
  96479. if (value === this._captureAnimationsTime) {
  96480. return;
  96481. }
  96482. this._captureAnimationsTime = value;
  96483. if (value) {
  96484. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  96485. _this._animationsTime.endMonitoring();
  96486. });
  96487. }
  96488. else {
  96489. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  96490. this._onAfterAnimationsObserver = null;
  96491. }
  96492. },
  96493. enumerable: true,
  96494. configurable: true
  96495. });
  96496. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  96497. /**
  96498. * Gets the perf counter used for frame time capture
  96499. */
  96500. get: function () {
  96501. return this._frameTime;
  96502. },
  96503. enumerable: true,
  96504. configurable: true
  96505. });
  96506. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  96507. /**
  96508. * Gets the frame time capture status
  96509. */
  96510. get: function () {
  96511. return this._captureFrameTime;
  96512. },
  96513. /**
  96514. * Enable or disable the frame time capture
  96515. */
  96516. set: function (value) {
  96517. this._captureFrameTime = value;
  96518. },
  96519. enumerable: true,
  96520. configurable: true
  96521. });
  96522. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  96523. /**
  96524. * Gets the perf counter used for inter-frames time capture
  96525. */
  96526. get: function () {
  96527. return this._interFrameTime;
  96528. },
  96529. enumerable: true,
  96530. configurable: true
  96531. });
  96532. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  96533. /**
  96534. * Gets the inter-frames time capture status
  96535. */
  96536. get: function () {
  96537. return this._captureInterFrameTime;
  96538. },
  96539. /**
  96540. * Enable or disable the inter-frames time capture
  96541. */
  96542. set: function (value) {
  96543. this._captureInterFrameTime = value;
  96544. },
  96545. enumerable: true,
  96546. configurable: true
  96547. });
  96548. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  96549. /**
  96550. * Gets the perf counter used for render time capture
  96551. */
  96552. get: function () {
  96553. return this._renderTime;
  96554. },
  96555. enumerable: true,
  96556. configurable: true
  96557. });
  96558. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  96559. /**
  96560. * Gets the render time capture status
  96561. */
  96562. get: function () {
  96563. return this._captureRenderTime;
  96564. },
  96565. /**
  96566. * Enable or disable the render time capture
  96567. */
  96568. set: function (value) {
  96569. var _this = this;
  96570. if (value === this._captureRenderTime) {
  96571. return;
  96572. }
  96573. this._captureRenderTime = value;
  96574. if (value) {
  96575. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  96576. _this._renderTime.beginMonitoring();
  96577. BABYLON.Tools.StartPerformanceCounter("Main render");
  96578. });
  96579. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  96580. _this._renderTime.endMonitoring(false);
  96581. BABYLON.Tools.EndPerformanceCounter("Main render");
  96582. });
  96583. }
  96584. else {
  96585. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  96586. this._onBeforeDrawPhaseObserver = null;
  96587. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  96588. this._onAfterDrawPhaseObserver = null;
  96589. }
  96590. },
  96591. enumerable: true,
  96592. configurable: true
  96593. });
  96594. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  96595. /**
  96596. * Gets the perf counter used for draw calls
  96597. */
  96598. get: function () {
  96599. return this.scene.getEngine()._drawCalls;
  96600. },
  96601. enumerable: true,
  96602. configurable: true
  96603. });
  96604. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  96605. /**
  96606. * Gets the perf counter used for texture collisions
  96607. */
  96608. get: function () {
  96609. return this.scene.getEngine()._textureCollisions;
  96610. },
  96611. enumerable: true,
  96612. configurable: true
  96613. });
  96614. SceneInstrumentation.prototype.dispose = function () {
  96615. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  96616. this._onAfterRenderObserver = null;
  96617. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  96618. this._onBeforeActiveMeshesEvaluationObserver = null;
  96619. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  96620. this._onAfterActiveMeshesEvaluationObserver = null;
  96621. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  96622. this._onBeforeRenderTargetsRenderObserver = null;
  96623. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  96624. this._onAfterRenderTargetsRenderObserver = null;
  96625. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  96626. this._onBeforeAnimationsObserver = null;
  96627. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  96628. this._onBeforeParticlesRenderingObserver = null;
  96629. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  96630. this._onAfterParticlesRenderingObserver = null;
  96631. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  96632. this._onBeforeSpritesRenderingObserver = null;
  96633. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  96634. this._onAfterSpritesRenderingObserver = null;
  96635. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  96636. this._onBeforeDrawPhaseObserver = null;
  96637. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  96638. this._onAfterDrawPhaseObserver = null;
  96639. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  96640. this._onBeforePhysicsObserver = null;
  96641. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  96642. this._onAfterPhysicsObserver = null;
  96643. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  96644. this._onAfterAnimationsObserver = null;
  96645. this.scene = null;
  96646. };
  96647. return SceneInstrumentation;
  96648. }());
  96649. BABYLON.SceneInstrumentation = SceneInstrumentation;
  96650. })(BABYLON || (BABYLON = {}));
  96651. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  96652. var BABYLON;
  96653. (function (BABYLON) {
  96654. /**
  96655. * @hidden
  96656. **/
  96657. var _TimeToken = /** @class */ (function () {
  96658. function _TimeToken() {
  96659. this._timeElapsedQueryEnded = false;
  96660. }
  96661. return _TimeToken;
  96662. }());
  96663. BABYLON._TimeToken = _TimeToken;
  96664. })(BABYLON || (BABYLON = {}));
  96665. //# sourceMappingURL=babylon.timeToken.js.map
  96666. var BABYLON;
  96667. (function (BABYLON) {
  96668. /**
  96669. * Background material defines definition.
  96670. * @hidden Mainly internal Use
  96671. */
  96672. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  96673. __extends(BackgroundMaterialDefines, _super);
  96674. /**
  96675. * Constructor of the defines.
  96676. */
  96677. function BackgroundMaterialDefines() {
  96678. var _this = _super.call(this) || this;
  96679. /**
  96680. * True if the diffuse texture is in use.
  96681. */
  96682. _this.DIFFUSE = false;
  96683. /**
  96684. * The direct UV channel to use.
  96685. */
  96686. _this.DIFFUSEDIRECTUV = 0;
  96687. /**
  96688. * True if the diffuse texture is in gamma space.
  96689. */
  96690. _this.GAMMADIFFUSE = false;
  96691. /**
  96692. * True if the diffuse texture has opacity in the alpha channel.
  96693. */
  96694. _this.DIFFUSEHASALPHA = false;
  96695. /**
  96696. * True if you want the material to fade to transparent at grazing angle.
  96697. */
  96698. _this.OPACITYFRESNEL = false;
  96699. /**
  96700. * True if an extra blur needs to be added in the reflection.
  96701. */
  96702. _this.REFLECTIONBLUR = false;
  96703. /**
  96704. * True if you want the material to fade to reflection at grazing angle.
  96705. */
  96706. _this.REFLECTIONFRESNEL = false;
  96707. /**
  96708. * True if you want the material to falloff as far as you move away from the scene center.
  96709. */
  96710. _this.REFLECTIONFALLOFF = false;
  96711. /**
  96712. * False if the current Webgl implementation does not support the texture lod extension.
  96713. */
  96714. _this.TEXTURELODSUPPORT = false;
  96715. /**
  96716. * True to ensure the data are premultiplied.
  96717. */
  96718. _this.PREMULTIPLYALPHA = false;
  96719. /**
  96720. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  96721. */
  96722. _this.USERGBCOLOR = false;
  96723. /**
  96724. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  96725. * stays aligned with the desired configuration.
  96726. */
  96727. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  96728. /**
  96729. * True to add noise in order to reduce the banding effect.
  96730. */
  96731. _this.NOISE = false;
  96732. /**
  96733. * is the reflection texture in BGR color scheme?
  96734. * Mainly used to solve a bug in ios10 video tag
  96735. */
  96736. _this.REFLECTIONBGR = false;
  96737. _this.IMAGEPROCESSING = false;
  96738. _this.VIGNETTE = false;
  96739. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  96740. _this.VIGNETTEBLENDMODEOPAQUE = false;
  96741. _this.TONEMAPPING = false;
  96742. _this.CONTRAST = false;
  96743. _this.COLORCURVES = false;
  96744. _this.COLORGRADING = false;
  96745. _this.COLORGRADING3D = false;
  96746. _this.SAMPLER3DGREENDEPTH = false;
  96747. _this.SAMPLER3DBGRMAP = false;
  96748. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  96749. _this.EXPOSURE = false;
  96750. // Reflection.
  96751. _this.REFLECTION = false;
  96752. _this.REFLECTIONMAP_3D = false;
  96753. _this.REFLECTIONMAP_SPHERICAL = false;
  96754. _this.REFLECTIONMAP_PLANAR = false;
  96755. _this.REFLECTIONMAP_CUBIC = false;
  96756. _this.REFLECTIONMAP_PROJECTION = false;
  96757. _this.REFLECTIONMAP_SKYBOX = false;
  96758. _this.REFLECTIONMAP_EXPLICIT = false;
  96759. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96760. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96761. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96762. _this.INVERTCUBICMAP = false;
  96763. _this.REFLECTIONMAP_OPPOSITEZ = false;
  96764. _this.LODINREFLECTIONALPHA = false;
  96765. _this.GAMMAREFLECTION = false;
  96766. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  96767. // Default BJS.
  96768. _this.MAINUV1 = false;
  96769. _this.MAINUV2 = false;
  96770. _this.UV1 = false;
  96771. _this.UV2 = false;
  96772. _this.CLIPPLANE = false;
  96773. _this.POINTSIZE = false;
  96774. _this.FOG = false;
  96775. _this.NORMAL = false;
  96776. _this.NUM_BONE_INFLUENCERS = 0;
  96777. _this.BonesPerMesh = 0;
  96778. _this.INSTANCES = false;
  96779. _this.SHADOWFLOAT = false;
  96780. _this.rebuild();
  96781. return _this;
  96782. }
  96783. return BackgroundMaterialDefines;
  96784. }(BABYLON.MaterialDefines));
  96785. /**
  96786. * Background material used to create an efficient environement around your scene.
  96787. */
  96788. var BackgroundMaterial = /** @class */ (function (_super) {
  96789. __extends(BackgroundMaterial, _super);
  96790. /**
  96791. * Instantiates a Background Material in the given scene
  96792. * @param name The friendly name of the material
  96793. * @param scene The scene to add the material to
  96794. */
  96795. function BackgroundMaterial(name, scene) {
  96796. var _this = _super.call(this, name, scene) || this;
  96797. /**
  96798. * Key light Color (multiply against the environement texture)
  96799. */
  96800. _this.primaryColor = BABYLON.Color3.White();
  96801. _this._primaryColorShadowLevel = 0;
  96802. _this._primaryColorHighlightLevel = 0;
  96803. /**
  96804. * Reflection Texture used in the material.
  96805. * Should be author in a specific way for the best result (refer to the documentation).
  96806. */
  96807. _this.reflectionTexture = null;
  96808. /**
  96809. * Reflection Texture level of blur.
  96810. *
  96811. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  96812. * texture twice.
  96813. */
  96814. _this.reflectionBlur = 0;
  96815. /**
  96816. * Diffuse Texture used in the material.
  96817. * Should be author in a specific way for the best result (refer to the documentation).
  96818. */
  96819. _this.diffuseTexture = null;
  96820. _this._shadowLights = null;
  96821. /**
  96822. * Specify the list of lights casting shadow on the material.
  96823. * All scene shadow lights will be included if null.
  96824. */
  96825. _this.shadowLights = null;
  96826. /**
  96827. * Helps adjusting the shadow to a softer level if required.
  96828. * 0 means black shadows and 1 means no shadows.
  96829. */
  96830. _this.shadowLevel = 0;
  96831. /**
  96832. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  96833. * It is usually zero but might be interesting to modify according to your setup.
  96834. */
  96835. _this.sceneCenter = BABYLON.Vector3.Zero();
  96836. /**
  96837. * This helps specifying that the material is falling off to the sky box at grazing angle.
  96838. * This helps ensuring a nice transition when the camera goes under the ground.
  96839. */
  96840. _this.opacityFresnel = true;
  96841. /**
  96842. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  96843. * This helps adding a mirror texture on the ground.
  96844. */
  96845. _this.reflectionFresnel = false;
  96846. /**
  96847. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  96848. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  96849. */
  96850. _this.reflectionFalloffDistance = 0.0;
  96851. /**
  96852. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  96853. */
  96854. _this.reflectionAmount = 1.0;
  96855. /**
  96856. * This specifies the weight of the reflection at grazing angle.
  96857. */
  96858. _this.reflectionReflectance0 = 0.05;
  96859. /**
  96860. * This specifies the weight of the reflection at a perpendicular point of view.
  96861. */
  96862. _this.reflectionReflectance90 = 0.5;
  96863. /**
  96864. * Helps to directly use the maps channels instead of their level.
  96865. */
  96866. _this.useRGBColor = true;
  96867. /**
  96868. * This helps reducing the banding effect that could occur on the background.
  96869. */
  96870. _this.enableNoise = false;
  96871. _this._fovMultiplier = 1.0;
  96872. /**
  96873. * Enable the FOV adjustment feature controlled by fovMultiplier.
  96874. */
  96875. _this.useEquirectangularFOV = false;
  96876. _this._maxSimultaneousLights = 4;
  96877. /**
  96878. * Number of Simultaneous lights allowed on the material.
  96879. */
  96880. _this.maxSimultaneousLights = 4;
  96881. /**
  96882. * Keep track of the image processing observer to allow dispose and replace.
  96883. */
  96884. _this._imageProcessingObserver = null;
  96885. /**
  96886. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  96887. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  96888. */
  96889. _this.switchToBGR = false;
  96890. // Temp values kept as cache in the material.
  96891. _this._renderTargets = new BABYLON.SmartArray(16);
  96892. _this._reflectionControls = BABYLON.Vector4.Zero();
  96893. _this._white = BABYLON.Color3.White();
  96894. _this._primaryShadowColor = BABYLON.Color3.Black();
  96895. _this._primaryHighlightColor = BABYLON.Color3.Black();
  96896. // Setup the default processing configuration to the scene.
  96897. _this._attachImageProcessingConfiguration(null);
  96898. _this.getRenderTargetTextures = function () {
  96899. _this._renderTargets.reset();
  96900. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  96901. _this._renderTargets.push(_this._diffuseTexture);
  96902. }
  96903. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  96904. _this._renderTargets.push(_this._reflectionTexture);
  96905. }
  96906. return _this._renderTargets;
  96907. };
  96908. return _this;
  96909. }
  96910. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  96911. /**
  96912. * Experimental Internal Use Only.
  96913. *
  96914. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  96915. * This acts as a helper to set the primary color to a more "human friendly" value.
  96916. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  96917. * output color as close as possible from the chosen value.
  96918. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  96919. * part of lighting setup.)
  96920. */
  96921. get: function () {
  96922. return this.__perceptualColor;
  96923. },
  96924. set: function (value) {
  96925. this.__perceptualColor = value;
  96926. this._computePrimaryColorFromPerceptualColor();
  96927. this._markAllSubMeshesAsLightsDirty();
  96928. },
  96929. enumerable: true,
  96930. configurable: true
  96931. });
  96932. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  96933. /**
  96934. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  96935. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  96936. */
  96937. get: function () {
  96938. return this._primaryColorShadowLevel;
  96939. },
  96940. set: function (value) {
  96941. this._primaryColorShadowLevel = value;
  96942. this._computePrimaryColors();
  96943. this._markAllSubMeshesAsLightsDirty();
  96944. },
  96945. enumerable: true,
  96946. configurable: true
  96947. });
  96948. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  96949. /**
  96950. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  96951. * The primary color is used at the level chosen to define what the white area would look.
  96952. */
  96953. get: function () {
  96954. return this._primaryColorHighlightLevel;
  96955. },
  96956. set: function (value) {
  96957. this._primaryColorHighlightLevel = value;
  96958. this._computePrimaryColors();
  96959. this._markAllSubMeshesAsLightsDirty();
  96960. },
  96961. enumerable: true,
  96962. configurable: true
  96963. });
  96964. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  96965. /**
  96966. * Sets the reflection reflectance fresnel values according to the default standard
  96967. * empirically know to work well :-)
  96968. */
  96969. set: function (value) {
  96970. var reflectionWeight = value;
  96971. if (reflectionWeight < 0.5) {
  96972. reflectionWeight = reflectionWeight * 2.0;
  96973. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  96974. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  96975. }
  96976. else {
  96977. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  96978. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  96979. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  96980. }
  96981. },
  96982. enumerable: true,
  96983. configurable: true
  96984. });
  96985. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  96986. /**
  96987. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  96988. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  96989. * Recommended to be keep at 1.0 except for special cases.
  96990. */
  96991. get: function () {
  96992. return this._fovMultiplier;
  96993. },
  96994. set: function (value) {
  96995. if (isNaN(value)) {
  96996. value = 1.0;
  96997. }
  96998. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  96999. },
  97000. enumerable: true,
  97001. configurable: true
  97002. });
  97003. /**
  97004. * Attaches a new image processing configuration to the PBR Material.
  97005. * @param configuration (if null the scene configuration will be use)
  97006. */
  97007. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  97008. var _this = this;
  97009. if (configuration === this._imageProcessingConfiguration) {
  97010. return;
  97011. }
  97012. // Detaches observer.
  97013. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  97014. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  97015. }
  97016. // Pick the scene configuration if needed.
  97017. if (!configuration) {
  97018. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  97019. }
  97020. else {
  97021. this._imageProcessingConfiguration = configuration;
  97022. }
  97023. // Attaches observer.
  97024. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  97025. _this._computePrimaryColorFromPerceptualColor();
  97026. _this._markAllSubMeshesAsImageProcessingDirty();
  97027. });
  97028. };
  97029. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  97030. /**
  97031. * Gets the image processing configuration used either in this material.
  97032. */
  97033. get: function () {
  97034. return this._imageProcessingConfiguration;
  97035. },
  97036. /**
  97037. * Sets the Default image processing configuration used either in the this material.
  97038. *
  97039. * If sets to null, the scene one is in use.
  97040. */
  97041. set: function (value) {
  97042. this._attachImageProcessingConfiguration(value);
  97043. // Ensure the effect will be rebuilt.
  97044. this._markAllSubMeshesAsTexturesDirty();
  97045. },
  97046. enumerable: true,
  97047. configurable: true
  97048. });
  97049. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  97050. /**
  97051. * Gets wether the color curves effect is enabled.
  97052. */
  97053. get: function () {
  97054. return this.imageProcessingConfiguration.colorCurvesEnabled;
  97055. },
  97056. /**
  97057. * Sets wether the color curves effect is enabled.
  97058. */
  97059. set: function (value) {
  97060. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  97061. },
  97062. enumerable: true,
  97063. configurable: true
  97064. });
  97065. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  97066. /**
  97067. * Gets wether the color grading effect is enabled.
  97068. */
  97069. get: function () {
  97070. return this.imageProcessingConfiguration.colorGradingEnabled;
  97071. },
  97072. /**
  97073. * Gets wether the color grading effect is enabled.
  97074. */
  97075. set: function (value) {
  97076. this.imageProcessingConfiguration.colorGradingEnabled = value;
  97077. },
  97078. enumerable: true,
  97079. configurable: true
  97080. });
  97081. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  97082. /**
  97083. * Gets wether tonemapping is enabled or not.
  97084. */
  97085. get: function () {
  97086. return this._imageProcessingConfiguration.toneMappingEnabled;
  97087. },
  97088. /**
  97089. * Sets wether tonemapping is enabled or not
  97090. */
  97091. set: function (value) {
  97092. this._imageProcessingConfiguration.toneMappingEnabled = value;
  97093. },
  97094. enumerable: true,
  97095. configurable: true
  97096. });
  97097. ;
  97098. ;
  97099. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  97100. /**
  97101. * The camera exposure used on this material.
  97102. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  97103. * This corresponds to a photographic exposure.
  97104. */
  97105. get: function () {
  97106. return this._imageProcessingConfiguration.exposure;
  97107. },
  97108. /**
  97109. * The camera exposure used on this material.
  97110. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  97111. * This corresponds to a photographic exposure.
  97112. */
  97113. set: function (value) {
  97114. this._imageProcessingConfiguration.exposure = value;
  97115. },
  97116. enumerable: true,
  97117. configurable: true
  97118. });
  97119. ;
  97120. ;
  97121. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  97122. /**
  97123. * Gets The camera contrast used on this material.
  97124. */
  97125. get: function () {
  97126. return this._imageProcessingConfiguration.contrast;
  97127. },
  97128. /**
  97129. * Sets The camera contrast used on this material.
  97130. */
  97131. set: function (value) {
  97132. this._imageProcessingConfiguration.contrast = value;
  97133. },
  97134. enumerable: true,
  97135. configurable: true
  97136. });
  97137. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  97138. /**
  97139. * Gets the Color Grading 2D Lookup Texture.
  97140. */
  97141. get: function () {
  97142. return this._imageProcessingConfiguration.colorGradingTexture;
  97143. },
  97144. /**
  97145. * Sets the Color Grading 2D Lookup Texture.
  97146. */
  97147. set: function (value) {
  97148. this.imageProcessingConfiguration.colorGradingTexture = value;
  97149. },
  97150. enumerable: true,
  97151. configurable: true
  97152. });
  97153. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  97154. /**
  97155. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  97156. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  97157. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  97158. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  97159. */
  97160. get: function () {
  97161. return this.imageProcessingConfiguration.colorCurves;
  97162. },
  97163. /**
  97164. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  97165. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  97166. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  97167. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  97168. */
  97169. set: function (value) {
  97170. this.imageProcessingConfiguration.colorCurves = value;
  97171. },
  97172. enumerable: true,
  97173. configurable: true
  97174. });
  97175. /**
  97176. * The entire material has been created in order to prevent overdraw.
  97177. * @returns false
  97178. */
  97179. BackgroundMaterial.prototype.needAlphaTesting = function () {
  97180. return true;
  97181. };
  97182. /**
  97183. * The entire material has been created in order to prevent overdraw.
  97184. * @returns true if blending is enable
  97185. */
  97186. BackgroundMaterial.prototype.needAlphaBlending = function () {
  97187. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  97188. };
  97189. /**
  97190. * Checks wether the material is ready to be rendered for a given mesh.
  97191. * @param mesh The mesh to render
  97192. * @param subMesh The submesh to check against
  97193. * @param useInstances Specify wether or not the material is used with instances
  97194. * @returns true if all the dependencies are ready (Textures, Effects...)
  97195. */
  97196. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  97197. var _this = this;
  97198. if (useInstances === void 0) { useInstances = false; }
  97199. if (subMesh.effect && this.isFrozen) {
  97200. if (this._wasPreviouslyReady) {
  97201. return true;
  97202. }
  97203. }
  97204. if (!subMesh._materialDefines) {
  97205. subMesh._materialDefines = new BackgroundMaterialDefines();
  97206. }
  97207. var scene = this.getScene();
  97208. var defines = subMesh._materialDefines;
  97209. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  97210. if (defines._renderId === scene.getRenderId()) {
  97211. return true;
  97212. }
  97213. }
  97214. var engine = scene.getEngine();
  97215. // Lights
  97216. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  97217. defines._needNormals = true;
  97218. // Textures
  97219. if (defines._areTexturesDirty) {
  97220. defines._needUVs = false;
  97221. if (scene.texturesEnabled) {
  97222. if (scene.getEngine().getCaps().textureLOD) {
  97223. defines.TEXTURELODSUPPORT = true;
  97224. }
  97225. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  97226. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  97227. return false;
  97228. }
  97229. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  97230. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  97231. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  97232. defines.OPACITYFRESNEL = this._opacityFresnel;
  97233. }
  97234. else {
  97235. defines.DIFFUSE = false;
  97236. defines.DIFFUSEHASALPHA = false;
  97237. defines.GAMMADIFFUSE = false;
  97238. defines.OPACITYFRESNEL = false;
  97239. }
  97240. var reflectionTexture = this._reflectionTexture;
  97241. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  97242. if (!reflectionTexture.isReadyOrNotBlocking()) {
  97243. return false;
  97244. }
  97245. defines.REFLECTION = true;
  97246. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  97247. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  97248. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  97249. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  97250. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  97251. defines.REFLECTIONBGR = this.switchToBGR;
  97252. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  97253. defines.INVERTCUBICMAP = true;
  97254. }
  97255. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  97256. switch (reflectionTexture.coordinatesMode) {
  97257. case BABYLON.Texture.EXPLICIT_MODE:
  97258. defines.REFLECTIONMAP_EXPLICIT = true;
  97259. break;
  97260. case BABYLON.Texture.PLANAR_MODE:
  97261. defines.REFLECTIONMAP_PLANAR = true;
  97262. break;
  97263. case BABYLON.Texture.PROJECTION_MODE:
  97264. defines.REFLECTIONMAP_PROJECTION = true;
  97265. break;
  97266. case BABYLON.Texture.SKYBOX_MODE:
  97267. defines.REFLECTIONMAP_SKYBOX = true;
  97268. break;
  97269. case BABYLON.Texture.SPHERICAL_MODE:
  97270. defines.REFLECTIONMAP_SPHERICAL = true;
  97271. break;
  97272. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  97273. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  97274. break;
  97275. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  97276. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  97277. break;
  97278. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  97279. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  97280. break;
  97281. case BABYLON.Texture.CUBIC_MODE:
  97282. case BABYLON.Texture.INVCUBIC_MODE:
  97283. default:
  97284. defines.REFLECTIONMAP_CUBIC = true;
  97285. break;
  97286. }
  97287. if (this.reflectionFresnel) {
  97288. defines.REFLECTIONFRESNEL = true;
  97289. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  97290. this._reflectionControls.x = this.reflectionAmount;
  97291. this._reflectionControls.y = this.reflectionReflectance0;
  97292. this._reflectionControls.z = this.reflectionReflectance90;
  97293. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  97294. }
  97295. else {
  97296. defines.REFLECTIONFRESNEL = false;
  97297. defines.REFLECTIONFALLOFF = false;
  97298. }
  97299. }
  97300. else {
  97301. defines.REFLECTION = false;
  97302. defines.REFLECTIONFRESNEL = false;
  97303. defines.REFLECTIONFALLOFF = false;
  97304. defines.REFLECTIONBLUR = false;
  97305. defines.REFLECTIONMAP_3D = false;
  97306. defines.REFLECTIONMAP_SPHERICAL = false;
  97307. defines.REFLECTIONMAP_PLANAR = false;
  97308. defines.REFLECTIONMAP_CUBIC = false;
  97309. defines.REFLECTIONMAP_PROJECTION = false;
  97310. defines.REFLECTIONMAP_SKYBOX = false;
  97311. defines.REFLECTIONMAP_EXPLICIT = false;
  97312. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  97313. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  97314. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  97315. defines.INVERTCUBICMAP = false;
  97316. defines.REFLECTIONMAP_OPPOSITEZ = false;
  97317. defines.LODINREFLECTIONALPHA = false;
  97318. defines.GAMMAREFLECTION = false;
  97319. }
  97320. }
  97321. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  97322. defines.USERGBCOLOR = this._useRGBColor;
  97323. defines.NOISE = this._enableNoise;
  97324. }
  97325. if (defines._areLightsDirty) {
  97326. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  97327. }
  97328. if (defines._areImageProcessingDirty) {
  97329. if (!this._imageProcessingConfiguration.isReady()) {
  97330. return false;
  97331. }
  97332. this._imageProcessingConfiguration.prepareDefines(defines);
  97333. }
  97334. // Misc.
  97335. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  97336. // Values that need to be evaluated on every frame
  97337. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  97338. // Attribs
  97339. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  97340. if (mesh) {
  97341. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  97342. mesh.createNormals(true);
  97343. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  97344. }
  97345. }
  97346. }
  97347. // Get correct effect
  97348. if (defines.isDirty) {
  97349. defines.markAsProcessed();
  97350. scene.resetCachedMaterial();
  97351. // Fallbacks
  97352. var fallbacks = new BABYLON.EffectFallbacks();
  97353. if (defines.FOG) {
  97354. fallbacks.addFallback(0, "FOG");
  97355. }
  97356. if (defines.POINTSIZE) {
  97357. fallbacks.addFallback(1, "POINTSIZE");
  97358. }
  97359. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  97360. if (defines.NUM_BONE_INFLUENCERS > 0) {
  97361. fallbacks.addCPUSkinningFallback(0, mesh);
  97362. }
  97363. //Attributes
  97364. var attribs = [BABYLON.VertexBuffer.PositionKind];
  97365. if (defines.NORMAL) {
  97366. attribs.push(BABYLON.VertexBuffer.NormalKind);
  97367. }
  97368. if (defines.UV1) {
  97369. attribs.push(BABYLON.VertexBuffer.UVKind);
  97370. }
  97371. if (defines.UV2) {
  97372. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  97373. }
  97374. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  97375. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  97376. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  97377. "vFogInfos", "vFogColor", "pointSize",
  97378. "vClipPlane", "mBones",
  97379. "vPrimaryColor", "vPrimaryColorShadow",
  97380. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  97381. "shadowLevel", "alpha",
  97382. "vBackgroundCenter", "vReflectionControl",
  97383. "vDiffuseInfos", "diffuseMatrix",
  97384. ];
  97385. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  97386. var uniformBuffers = ["Material", "Scene"];
  97387. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  97388. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  97389. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  97390. uniformsNames: uniforms,
  97391. uniformBuffersNames: uniformBuffers,
  97392. samplers: samplers,
  97393. defines: defines,
  97394. maxSimultaneousLights: this._maxSimultaneousLights
  97395. });
  97396. var onCompiled = function (effect) {
  97397. if (_this.onCompiled) {
  97398. _this.onCompiled(effect);
  97399. }
  97400. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  97401. };
  97402. var join = defines.toString();
  97403. subMesh.setEffect(scene.getEngine().createEffect("background", {
  97404. attributes: attribs,
  97405. uniformsNames: uniforms,
  97406. uniformBuffersNames: uniformBuffers,
  97407. samplers: samplers,
  97408. defines: join,
  97409. fallbacks: fallbacks,
  97410. onCompiled: onCompiled,
  97411. onError: this.onError,
  97412. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  97413. }, engine), defines);
  97414. this.buildUniformLayout();
  97415. }
  97416. if (!subMesh.effect || !subMesh.effect.isReady()) {
  97417. return false;
  97418. }
  97419. defines._renderId = scene.getRenderId();
  97420. this._wasPreviouslyReady = true;
  97421. return true;
  97422. };
  97423. /**
  97424. * Compute the primary color according to the chosen perceptual color.
  97425. */
  97426. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  97427. if (!this.__perceptualColor) {
  97428. return;
  97429. }
  97430. this._primaryColor.copyFrom(this.__perceptualColor);
  97431. // Revert gamma space.
  97432. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  97433. // Revert image processing configuration.
  97434. if (this._imageProcessingConfiguration) {
  97435. // Revert Exposure.
  97436. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  97437. }
  97438. this._computePrimaryColors();
  97439. };
  97440. /**
  97441. * Compute the highlights and shadow colors according to their chosen levels.
  97442. */
  97443. BackgroundMaterial.prototype._computePrimaryColors = function () {
  97444. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  97445. return;
  97446. }
  97447. // Find the highlight color based on the configuration.
  97448. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  97449. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  97450. // Find the shadow color based on the configuration.
  97451. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  97452. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  97453. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  97454. };
  97455. /**
  97456. * Build the uniform buffer used in the material.
  97457. */
  97458. BackgroundMaterial.prototype.buildUniformLayout = function () {
  97459. // Order is important !
  97460. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  97461. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  97462. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  97463. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  97464. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  97465. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  97466. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  97467. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  97468. this._uniformBuffer.addUniform("pointSize", 1);
  97469. this._uniformBuffer.addUniform("shadowLevel", 1);
  97470. this._uniformBuffer.addUniform("alpha", 1);
  97471. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  97472. this._uniformBuffer.addUniform("vReflectionControl", 4);
  97473. this._uniformBuffer.create();
  97474. };
  97475. /**
  97476. * Unbind the material.
  97477. */
  97478. BackgroundMaterial.prototype.unbind = function () {
  97479. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  97480. this._uniformBuffer.setTexture("diffuseSampler", null);
  97481. }
  97482. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  97483. this._uniformBuffer.setTexture("reflectionSampler", null);
  97484. }
  97485. _super.prototype.unbind.call(this);
  97486. };
  97487. /**
  97488. * Bind only the world matrix to the material.
  97489. * @param world The world matrix to bind.
  97490. */
  97491. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  97492. this._activeEffect.setMatrix("world", world);
  97493. };
  97494. /**
  97495. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  97496. * @param world The world matrix to bind.
  97497. * @param subMesh The submesh to bind for.
  97498. */
  97499. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  97500. var scene = this.getScene();
  97501. var defines = subMesh._materialDefines;
  97502. if (!defines) {
  97503. return;
  97504. }
  97505. var effect = subMesh.effect;
  97506. if (!effect) {
  97507. return;
  97508. }
  97509. this._activeEffect = effect;
  97510. // Matrices
  97511. this.bindOnlyWorldMatrix(world);
  97512. // Bones
  97513. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  97514. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  97515. if (mustRebind) {
  97516. this._uniformBuffer.bindToEffect(effect, "Material");
  97517. this.bindViewProjection(effect);
  97518. var reflectionTexture = this._reflectionTexture;
  97519. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  97520. // Texture uniforms
  97521. if (scene.texturesEnabled) {
  97522. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  97523. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  97524. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  97525. }
  97526. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  97527. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  97528. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  97529. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  97530. }
  97531. }
  97532. if (this.shadowLevel > 0) {
  97533. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  97534. }
  97535. this._uniformBuffer.updateFloat("alpha", this.alpha);
  97536. // Point size
  97537. if (this.pointsCloud) {
  97538. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  97539. }
  97540. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  97541. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  97542. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  97543. }
  97544. else {
  97545. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  97546. }
  97547. }
  97548. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  97549. // Textures
  97550. if (scene.texturesEnabled) {
  97551. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  97552. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  97553. }
  97554. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  97555. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  97556. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  97557. }
  97558. else if (!defines.REFLECTIONBLUR) {
  97559. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  97560. }
  97561. else {
  97562. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  97563. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  97564. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  97565. }
  97566. if (defines.REFLECTIONFRESNEL) {
  97567. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  97568. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  97569. }
  97570. }
  97571. }
  97572. // Clip plane
  97573. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  97574. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  97575. }
  97576. if (mustRebind || !this.isFrozen) {
  97577. if (scene.lightsEnabled) {
  97578. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  97579. }
  97580. // View
  97581. this.bindView(effect);
  97582. // Fog
  97583. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  97584. // image processing
  97585. this._imageProcessingConfiguration.bind(this._activeEffect);
  97586. }
  97587. this._uniformBuffer.update();
  97588. this._afterBind(mesh);
  97589. };
  97590. /**
  97591. * Dispose the material.
  97592. * @param forceDisposeEffect Force disposal of the associated effect.
  97593. * @param forceDisposeTextures Force disposal of the associated textures.
  97594. */
  97595. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  97596. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  97597. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  97598. if (forceDisposeTextures) {
  97599. if (this.diffuseTexture) {
  97600. this.diffuseTexture.dispose();
  97601. }
  97602. if (this.reflectionTexture) {
  97603. this.reflectionTexture.dispose();
  97604. }
  97605. }
  97606. this._renderTargets.dispose();
  97607. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  97608. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  97609. }
  97610. _super.prototype.dispose.call(this, forceDisposeEffect);
  97611. };
  97612. /**
  97613. * Clones the material.
  97614. * @param name The cloned name.
  97615. * @returns The cloned material.
  97616. */
  97617. BackgroundMaterial.prototype.clone = function (name) {
  97618. var _this = this;
  97619. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  97620. };
  97621. /**
  97622. * Serializes the current material to its JSON representation.
  97623. * @returns The JSON representation.
  97624. */
  97625. BackgroundMaterial.prototype.serialize = function () {
  97626. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97627. serializationObject.customType = "BABYLON.BackgroundMaterial";
  97628. return serializationObject;
  97629. };
  97630. /**
  97631. * Gets the class name of the material
  97632. * @returns "BackgroundMaterial"
  97633. */
  97634. BackgroundMaterial.prototype.getClassName = function () {
  97635. return "BackgroundMaterial";
  97636. };
  97637. /**
  97638. * Parse a JSON input to create back a background material.
  97639. * @param source The JSON data to parse
  97640. * @param scene The scene to create the parsed material in
  97641. * @param rootUrl The root url of the assets the material depends upon
  97642. * @returns the instantiated BackgroundMaterial.
  97643. */
  97644. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  97645. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  97646. };
  97647. /**
  97648. * Standard reflectance value at parallel view angle.
  97649. */
  97650. BackgroundMaterial.StandardReflectance0 = 0.05;
  97651. /**
  97652. * Standard reflectance value at grazing angle.
  97653. */
  97654. BackgroundMaterial.StandardReflectance90 = 0.5;
  97655. __decorate([
  97656. BABYLON.serializeAsColor3()
  97657. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  97658. __decorate([
  97659. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  97660. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  97661. __decorate([
  97662. BABYLON.serializeAsColor3()
  97663. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  97664. __decorate([
  97665. BABYLON.serialize()
  97666. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  97667. __decorate([
  97668. BABYLON.serialize()
  97669. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  97670. __decorate([
  97671. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  97672. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  97673. __decorate([
  97674. BABYLON.serializeAsTexture()
  97675. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  97676. __decorate([
  97677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97678. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  97679. __decorate([
  97680. BABYLON.serialize()
  97681. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  97682. __decorate([
  97683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97684. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  97685. __decorate([
  97686. BABYLON.serializeAsTexture()
  97687. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  97688. __decorate([
  97689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97690. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  97691. __decorate([
  97692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97693. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  97694. __decorate([
  97695. BABYLON.serialize()
  97696. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  97697. __decorate([
  97698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97699. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  97700. __decorate([
  97701. BABYLON.serializeAsVector3()
  97702. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  97703. __decorate([
  97704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97705. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  97706. __decorate([
  97707. BABYLON.serialize()
  97708. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  97709. __decorate([
  97710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97711. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  97712. __decorate([
  97713. BABYLON.serialize()
  97714. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  97715. __decorate([
  97716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97717. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  97718. __decorate([
  97719. BABYLON.serialize()
  97720. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  97721. __decorate([
  97722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97723. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  97724. __decorate([
  97725. BABYLON.serialize()
  97726. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  97727. __decorate([
  97728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97729. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  97730. __decorate([
  97731. BABYLON.serialize()
  97732. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  97733. __decorate([
  97734. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97735. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  97736. __decorate([
  97737. BABYLON.serialize()
  97738. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  97739. __decorate([
  97740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97741. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  97742. __decorate([
  97743. BABYLON.serialize()
  97744. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  97745. __decorate([
  97746. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97747. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  97748. __decorate([
  97749. BABYLON.serialize()
  97750. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  97751. __decorate([
  97752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97753. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  97754. __decorate([
  97755. BABYLON.serialize()
  97756. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  97757. __decorate([
  97758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97759. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  97760. __decorate([
  97761. BABYLON.serializeAsImageProcessingConfiguration()
  97762. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  97763. return BackgroundMaterial;
  97764. }(BABYLON.PushMaterial));
  97765. BABYLON.BackgroundMaterial = BackgroundMaterial;
  97766. })(BABYLON || (BABYLON = {}));
  97767. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  97768. var __assign = (this && this.__assign) || Object.assign || function(t) {
  97769. for (var s, i = 1, n = arguments.length; i < n; i++) {
  97770. s = arguments[i];
  97771. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  97772. t[p] = s[p];
  97773. }
  97774. return t;
  97775. };
  97776. var BABYLON;
  97777. (function (BABYLON) {
  97778. /**
  97779. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  97780. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  97781. * It also helps with the default setup of your imageProcessing configuration.
  97782. */
  97783. var EnvironmentHelper = /** @class */ (function () {
  97784. /**
  97785. * constructor
  97786. * @param options
  97787. * @param scene The scene to add the material to
  97788. */
  97789. function EnvironmentHelper(options, scene) {
  97790. var _this = this;
  97791. this._errorHandler = function (message, exception) {
  97792. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  97793. };
  97794. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  97795. this._scene = scene;
  97796. this.onErrorObservable = new BABYLON.Observable();
  97797. this._setupBackground();
  97798. this._setupImageProcessing();
  97799. }
  97800. /**
  97801. * Creates the default options for the helper.
  97802. */
  97803. EnvironmentHelper._getDefaultOptions = function () {
  97804. return {
  97805. createGround: true,
  97806. groundSize: 15,
  97807. groundTexture: this._groundTextureCDNUrl,
  97808. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97809. groundOpacity: 0.9,
  97810. enableGroundShadow: true,
  97811. groundShadowLevel: 0.5,
  97812. enableGroundMirror: false,
  97813. groundMirrorSizeRatio: 0.3,
  97814. groundMirrorBlurKernel: 64,
  97815. groundMirrorAmount: 1,
  97816. groundMirrorFresnelWeight: 1,
  97817. groundMirrorFallOffDistance: 0,
  97818. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  97819. groundYBias: 0.00001,
  97820. createSkybox: true,
  97821. skyboxSize: 20,
  97822. skyboxTexture: this._skyboxTextureCDNUrl,
  97823. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97824. backgroundYRotation: 0,
  97825. sizeAuto: true,
  97826. rootPosition: BABYLON.Vector3.Zero(),
  97827. setupImageProcessing: true,
  97828. environmentTexture: this._environmentTextureCDNUrl,
  97829. cameraExposure: 0.8,
  97830. cameraContrast: 1.2,
  97831. toneMappingEnabled: true,
  97832. };
  97833. };
  97834. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  97835. /**
  97836. * Gets the root mesh created by the helper.
  97837. */
  97838. get: function () {
  97839. return this._rootMesh;
  97840. },
  97841. enumerable: true,
  97842. configurable: true
  97843. });
  97844. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  97845. /**
  97846. * Gets the skybox created by the helper.
  97847. */
  97848. get: function () {
  97849. return this._skybox;
  97850. },
  97851. enumerable: true,
  97852. configurable: true
  97853. });
  97854. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  97855. /**
  97856. * Gets the skybox texture created by the helper.
  97857. */
  97858. get: function () {
  97859. return this._skyboxTexture;
  97860. },
  97861. enumerable: true,
  97862. configurable: true
  97863. });
  97864. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  97865. /**
  97866. * Gets the skybox material created by the helper.
  97867. */
  97868. get: function () {
  97869. return this._skyboxMaterial;
  97870. },
  97871. enumerable: true,
  97872. configurable: true
  97873. });
  97874. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  97875. /**
  97876. * Gets the ground mesh created by the helper.
  97877. */
  97878. get: function () {
  97879. return this._ground;
  97880. },
  97881. enumerable: true,
  97882. configurable: true
  97883. });
  97884. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  97885. /**
  97886. * Gets the ground texture created by the helper.
  97887. */
  97888. get: function () {
  97889. return this._groundTexture;
  97890. },
  97891. enumerable: true,
  97892. configurable: true
  97893. });
  97894. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  97895. /**
  97896. * Gets the ground mirror created by the helper.
  97897. */
  97898. get: function () {
  97899. return this._groundMirror;
  97900. },
  97901. enumerable: true,
  97902. configurable: true
  97903. });
  97904. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  97905. /**
  97906. * Gets the ground mirror render list to helps pushing the meshes
  97907. * you wish in the ground reflection.
  97908. */
  97909. get: function () {
  97910. if (this._groundMirror) {
  97911. return this._groundMirror.renderList;
  97912. }
  97913. return null;
  97914. },
  97915. enumerable: true,
  97916. configurable: true
  97917. });
  97918. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  97919. /**
  97920. * Gets the ground material created by the helper.
  97921. */
  97922. get: function () {
  97923. return this._groundMaterial;
  97924. },
  97925. enumerable: true,
  97926. configurable: true
  97927. });
  97928. /**
  97929. * Updates the background according to the new options
  97930. * @param options
  97931. */
  97932. EnvironmentHelper.prototype.updateOptions = function (options) {
  97933. var newOptions = __assign({}, this._options, options);
  97934. if (this._ground && !newOptions.createGround) {
  97935. this._ground.dispose();
  97936. this._ground = null;
  97937. }
  97938. if (this._groundMaterial && !newOptions.createGround) {
  97939. this._groundMaterial.dispose();
  97940. this._groundMaterial = null;
  97941. }
  97942. if (this._groundTexture) {
  97943. if (this._options.groundTexture != newOptions.groundTexture) {
  97944. this._groundTexture.dispose();
  97945. this._groundTexture = null;
  97946. }
  97947. }
  97948. if (this._skybox && !newOptions.createSkybox) {
  97949. this._skybox.dispose();
  97950. this._skybox = null;
  97951. }
  97952. if (this._skyboxMaterial && !newOptions.createSkybox) {
  97953. this._skyboxMaterial.dispose();
  97954. this._skyboxMaterial = null;
  97955. }
  97956. if (this._skyboxTexture) {
  97957. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  97958. this._skyboxTexture.dispose();
  97959. this._skyboxTexture = null;
  97960. }
  97961. }
  97962. if (this._groundMirror && !newOptions.enableGroundMirror) {
  97963. this._groundMirror.dispose();
  97964. this._groundMirror = null;
  97965. }
  97966. if (this._scene.environmentTexture) {
  97967. if (this._options.environmentTexture != newOptions.environmentTexture) {
  97968. this._scene.environmentTexture.dispose();
  97969. }
  97970. }
  97971. this._options = newOptions;
  97972. this._setupBackground();
  97973. this._setupImageProcessing();
  97974. };
  97975. /**
  97976. * Sets the primary color of all the available elements.
  97977. * @param color the main color to affect to the ground and the background
  97978. */
  97979. EnvironmentHelper.prototype.setMainColor = function (color) {
  97980. if (this.groundMaterial) {
  97981. this.groundMaterial.primaryColor = color;
  97982. }
  97983. if (this.skyboxMaterial) {
  97984. this.skyboxMaterial.primaryColor = color;
  97985. }
  97986. if (this.groundMirror) {
  97987. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  97988. }
  97989. };
  97990. /**
  97991. * Setup the image processing according to the specified options.
  97992. */
  97993. EnvironmentHelper.prototype._setupImageProcessing = function () {
  97994. if (this._options.setupImageProcessing) {
  97995. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  97996. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  97997. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  97998. this._setupEnvironmentTexture();
  97999. }
  98000. };
  98001. /**
  98002. * Setup the environment texture according to the specified options.
  98003. */
  98004. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  98005. if (this._scene.environmentTexture) {
  98006. return;
  98007. }
  98008. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  98009. this._scene.environmentTexture = this._options.environmentTexture;
  98010. return;
  98011. }
  98012. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  98013. this._scene.environmentTexture = environmentTexture;
  98014. };
  98015. /**
  98016. * Setup the background according to the specified options.
  98017. */
  98018. EnvironmentHelper.prototype._setupBackground = function () {
  98019. if (!this._rootMesh) {
  98020. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  98021. }
  98022. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  98023. var sceneSize = this._getSceneSize();
  98024. if (this._options.createGround) {
  98025. this._setupGround(sceneSize);
  98026. this._setupGroundMaterial();
  98027. this._setupGroundDiffuseTexture();
  98028. if (this._options.enableGroundMirror) {
  98029. this._setupGroundMirrorTexture(sceneSize);
  98030. }
  98031. this._setupMirrorInGroundMaterial();
  98032. }
  98033. if (this._options.createSkybox) {
  98034. this._setupSkybox(sceneSize);
  98035. this._setupSkyboxMaterial();
  98036. this._setupSkyboxReflectionTexture();
  98037. }
  98038. this._rootMesh.position.x = sceneSize.rootPosition.x;
  98039. this._rootMesh.position.z = sceneSize.rootPosition.z;
  98040. this._rootMesh.position.y = sceneSize.rootPosition.y;
  98041. };
  98042. /**
  98043. * Get the scene sizes according to the setup.
  98044. */
  98045. EnvironmentHelper.prototype._getSceneSize = function () {
  98046. var _this = this;
  98047. var groundSize = this._options.groundSize;
  98048. var skyboxSize = this._options.skyboxSize;
  98049. var rootPosition = this._options.rootPosition;
  98050. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  98051. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  98052. }
  98053. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  98054. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  98055. });
  98056. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  98057. if (this._options.sizeAuto) {
  98058. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  98059. this._scene.activeCamera.upperRadiusLimit) {
  98060. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  98061. skyboxSize = groundSize;
  98062. }
  98063. var sceneDiagonalLenght = sceneDiagonal.length();
  98064. if (sceneDiagonalLenght > groundSize) {
  98065. groundSize = sceneDiagonalLenght * 2;
  98066. skyboxSize = groundSize;
  98067. }
  98068. // 10 % bigger.
  98069. groundSize *= 1.1;
  98070. skyboxSize *= 1.5;
  98071. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  98072. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  98073. }
  98074. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  98075. };
  98076. /**
  98077. * Setup the ground according to the specified options.
  98078. */
  98079. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  98080. var _this = this;
  98081. if (!this._ground) {
  98082. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  98083. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  98084. this._ground.parent = this._rootMesh;
  98085. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  98086. }
  98087. this._ground.receiveShadows = this._options.enableGroundShadow;
  98088. };
  98089. /**
  98090. * Setup the ground material according to the specified options.
  98091. */
  98092. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  98093. if (!this._groundMaterial) {
  98094. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  98095. }
  98096. this._groundMaterial.alpha = this._options.groundOpacity;
  98097. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  98098. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  98099. this._groundMaterial.primaryColor = this._options.groundColor;
  98100. this._groundMaterial.useRGBColor = false;
  98101. this._groundMaterial.enableNoise = true;
  98102. if (this._ground) {
  98103. this._ground.material = this._groundMaterial;
  98104. }
  98105. };
  98106. /**
  98107. * Setup the ground diffuse texture according to the specified options.
  98108. */
  98109. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  98110. if (!this._groundMaterial) {
  98111. return;
  98112. }
  98113. if (this._groundTexture) {
  98114. return;
  98115. }
  98116. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  98117. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  98118. return;
  98119. }
  98120. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  98121. diffuseTexture.gammaSpace = false;
  98122. diffuseTexture.hasAlpha = true;
  98123. this._groundMaterial.diffuseTexture = diffuseTexture;
  98124. };
  98125. /**
  98126. * Setup the ground mirror texture according to the specified options.
  98127. */
  98128. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  98129. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98130. if (!this._groundMirror) {
  98131. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  98132. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  98133. this._groundMirror.anisotropicFilteringLevel = 1;
  98134. this._groundMirror.wrapU = wrapping;
  98135. this._groundMirror.wrapV = wrapping;
  98136. this._groundMirror.gammaSpace = false;
  98137. if (this._groundMirror.renderList) {
  98138. for (var i = 0; i < this._scene.meshes.length; i++) {
  98139. var mesh = this._scene.meshes[i];
  98140. if (mesh !== this._ground &&
  98141. mesh !== this._skybox &&
  98142. mesh !== this._rootMesh) {
  98143. this._groundMirror.renderList.push(mesh);
  98144. }
  98145. }
  98146. }
  98147. }
  98148. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  98149. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  98150. };
  98151. /**
  98152. * Setup the ground to receive the mirror texture.
  98153. */
  98154. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  98155. if (this._groundMaterial) {
  98156. this._groundMaterial.reflectionTexture = this._groundMirror;
  98157. this._groundMaterial.reflectionFresnel = true;
  98158. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  98159. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  98160. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  98161. }
  98162. };
  98163. /**
  98164. * Setup the skybox according to the specified options.
  98165. */
  98166. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  98167. var _this = this;
  98168. if (!this._skybox) {
  98169. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  98170. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  98171. }
  98172. this._skybox.parent = this._rootMesh;
  98173. };
  98174. /**
  98175. * Setup the skybox material according to the specified options.
  98176. */
  98177. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  98178. if (!this._skybox) {
  98179. return;
  98180. }
  98181. if (!this._skyboxMaterial) {
  98182. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  98183. }
  98184. this._skyboxMaterial.useRGBColor = false;
  98185. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  98186. this._skyboxMaterial.enableNoise = true;
  98187. this._skybox.material = this._skyboxMaterial;
  98188. };
  98189. /**
  98190. * Setup the skybox reflection texture according to the specified options.
  98191. */
  98192. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  98193. if (!this._skyboxMaterial) {
  98194. return;
  98195. }
  98196. if (this._skyboxTexture) {
  98197. return;
  98198. }
  98199. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  98200. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  98201. return;
  98202. }
  98203. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  98204. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  98205. this._skyboxTexture.gammaSpace = false;
  98206. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  98207. };
  98208. /**
  98209. * Dispose all the elements created by the Helper.
  98210. */
  98211. EnvironmentHelper.prototype.dispose = function () {
  98212. if (this._groundMaterial) {
  98213. this._groundMaterial.dispose(true, true);
  98214. }
  98215. if (this._skyboxMaterial) {
  98216. this._skyboxMaterial.dispose(true, true);
  98217. }
  98218. this._rootMesh.dispose(false);
  98219. };
  98220. /**
  98221. * Default ground texture URL.
  98222. */
  98223. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  98224. /**
  98225. * Default skybox texture URL.
  98226. */
  98227. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  98228. /**
  98229. * Default environment texture URL.
  98230. */
  98231. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  98232. return EnvironmentHelper;
  98233. }());
  98234. BABYLON.EnvironmentHelper = EnvironmentHelper;
  98235. })(BABYLON || (BABYLON = {}));
  98236. //# sourceMappingURL=babylon.environmentHelper.js.map
  98237. var BABYLON;
  98238. (function (BABYLON) {
  98239. /**
  98240. * This class is made for on one-liner static method to help creating particle systems.
  98241. */
  98242. var ParticleHelper = /** @class */ (function () {
  98243. function ParticleHelper() {
  98244. }
  98245. /**
  98246. * This is the main static method (one-liner) of this helper to create different particle systems.
  98247. * @param type This string represents the type to the particle system to create
  98248. * @param emitter The object where the particle system will start to emit from.
  98249. * @param scene The scene where the particle system should live.
  98250. * @param gpu If the system will use gpu.
  98251. * @returns the ParticleSystem created.
  98252. */
  98253. ParticleHelper.CreateAsync = function (type, emitter, scene, gpu) {
  98254. var _this = this;
  98255. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  98256. if (gpu === void 0) { gpu = false; }
  98257. return new Promise(function (resolve, reject) {
  98258. if (scene) {
  98259. _this._scene = scene;
  98260. }
  98261. else {
  98262. return reject("A particle system need a scene.");
  98263. }
  98264. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  98265. return reject("Particle system with GPU is not supported.");
  98266. }
  98267. _this._emitter = emitter;
  98268. BABYLON.Tools.LoadFile(_this._baseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  98269. var newData = JSON.parse(data.toString());
  98270. return resolve(_this._createSystem(newData));
  98271. }, undefined, undefined, undefined, function (req, exception) {
  98272. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  98273. });
  98274. });
  98275. };
  98276. ParticleHelper._createSystem = function (data) {
  98277. // Create a particle system
  98278. var system = new BABYLON.ParticleSystem(data.type, data.capacity, this._scene);
  98279. // Texture of each particle
  98280. system.particleTexture = new BABYLON.Texture(this._baseAssetsUrl + "/textures/" + data.textureFile, this._scene);
  98281. // Where the particles come from
  98282. system.emitter = this._emitter; // the starting object, the emitter
  98283. // Colors of all particles
  98284. system.color1 = new BABYLON.Color4(data.color1.r, data.color1.g, data.color1.b, data.color1.a);
  98285. system.color2 = new BABYLON.Color4(data.color2.r, data.color2.g, data.color2.b, data.color2.a);
  98286. system.colorDead = new BABYLON.Color4(data.colorDead.r, data.colorDead.g, data.colorDead.b, data.colorDead.a);
  98287. // Size of each particle (random between...
  98288. system.minSize = data.minSize;
  98289. system.maxSize = data.maxSize;
  98290. // Life time of each particle (random between...
  98291. system.minLifeTime = data.minLifeTime;
  98292. system.maxLifeTime = data.maxLifeTime;
  98293. // Emission rate
  98294. system.emitRate = data.emitRate;
  98295. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  98296. system.blendMode = data.blendMode;
  98297. // Set the gravity of all particles
  98298. system.gravity = new BABYLON.Vector3(data.gravity.x, data.gravity.y, data.gravity.z);
  98299. // Angular speed, in radians
  98300. system.minAngularSpeed = data.minAngularSpeed;
  98301. system.maxAngularSpeed = data.maxAngularSpeed;
  98302. // Speed
  98303. system.minEmitPower = data.minEmitPower;
  98304. system.maxEmitPower = data.maxEmitPower;
  98305. system.updateSpeed = data.updateSpeed;
  98306. switch (data.emitterType) {
  98307. case "box":
  98308. if (!data.direction1 || !data.direction2) {
  98309. throw new Error("Directions are missing in this particle system.");
  98310. }
  98311. if (!data.minEmitBox || !data.maxEmitBox) {
  98312. throw new Error("EmitBox is missing in this particle system.");
  98313. }
  98314. system.createBoxEmitter(new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z), new BABYLON.Vector3(data.minEmitBox.x, data.minEmitBox.y, data.minEmitBox.z), new BABYLON.Vector3(data.maxEmitBox.x, data.maxEmitBox.y, data.maxEmitBox.z));
  98315. break;
  98316. case "sphere":
  98317. system.createSphereEmitter(data.radius);
  98318. break;
  98319. case "directed_sphere":
  98320. if (!data.direction1 || !data.direction2) {
  98321. throw new Error("Directions are missing in this particle system.");
  98322. }
  98323. system.createDirectedSphereEmitter(data.radius, new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z));
  98324. break;
  98325. case "cone":
  98326. system.createConeEmitter(data.radius, data.angle);
  98327. break;
  98328. default:
  98329. break;
  98330. }
  98331. return system;
  98332. };
  98333. /**
  98334. * Base Assets URL.
  98335. */
  98336. ParticleHelper._baseAssetsUrl = "https://assets.babylonjs.com/particles";
  98337. return ParticleHelper;
  98338. }());
  98339. BABYLON.ParticleHelper = ParticleHelper;
  98340. })(BABYLON || (BABYLON = {}));
  98341. //# sourceMappingURL=babylon.particleHelper.js.map
  98342. var BABYLON;
  98343. (function (BABYLON) {
  98344. /**
  98345. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  98346. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  98347. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  98348. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  98349. */
  98350. var VideoDome = /** @class */ (function (_super) {
  98351. __extends(VideoDome, _super);
  98352. /**
  98353. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  98354. * @param name Element's name, child elements will append suffixes for their own names.
  98355. * @param urlsOrVideo
  98356. * @param options An object containing optional or exposed sub element properties:
  98357. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  98358. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  98359. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  98360. * @param options **loop=true** Automatically loop video on end.
  98361. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  98362. */
  98363. function VideoDome(name, urlsOrVideo, options, scene) {
  98364. var _this = _super.call(this, name, scene) || this;
  98365. // set defaults and manage values
  98366. name = name || "videoDome";
  98367. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  98368. options.clickToPlay = Boolean(options.clickToPlay);
  98369. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  98370. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  98371. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  98372. // create
  98373. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  98374. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  98375. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  98376. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  98377. flat: false,
  98378. radius: options.size,
  98379. subdivisions: options.resolution,
  98380. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  98381. }, scene);
  98382. // configure material
  98383. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  98384. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  98385. material.reflectionTexture = _this._videoTexture;
  98386. material.useEquirectangularFOV = true;
  98387. material.fovMultiplier = 1.0;
  98388. // configure mesh
  98389. _this._mesh.material = material;
  98390. _this._mesh.parent = _this;
  98391. // optional configuration
  98392. if (options.clickToPlay) {
  98393. scene.onPointerUp = function () {
  98394. _this._videoTexture.video.play();
  98395. };
  98396. }
  98397. return _this;
  98398. }
  98399. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  98400. /**
  98401. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  98402. * Also see the options.resolution property.
  98403. */
  98404. get: function () {
  98405. return this._material.fovMultiplier;
  98406. },
  98407. set: function (value) {
  98408. this._material.fovMultiplier = value;
  98409. },
  98410. enumerable: true,
  98411. configurable: true
  98412. });
  98413. /**
  98414. * Releases resources associated with this node.
  98415. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  98416. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  98417. */
  98418. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  98419. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  98420. this._videoTexture.dispose();
  98421. this._mesh.dispose();
  98422. this._material.dispose();
  98423. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  98424. };
  98425. return VideoDome;
  98426. }(BABYLON.Node));
  98427. BABYLON.VideoDome = VideoDome;
  98428. })(BABYLON || (BABYLON = {}));
  98429. //# sourceMappingURL=babylon.videoDome.js.map
  98430. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec2 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nin vec2 angle;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\nvec2 cornerPos=offset*size;\n\nvec4 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nrotatedCorner.z=0.;\nrotatedCorner.w=0.;\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+rotatedCorner);\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform vec2 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float coneAngle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\nin vec2 angle;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nout vec2 outAngle;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\noutAngle=angle;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=0.;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (coneAngle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  98431. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  98432. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  98433. globalObject["BABYLON"] = BABYLON;
  98434. //backwards compatibility
  98435. if(typeof earcut !== 'undefined') {
  98436. globalObject["Earcut"] = {
  98437. earcut: earcut
  98438. };
  98439. }
  98440. return BABYLON;
  98441. });
  98442. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(25)))
  98443. /***/ }),
  98444. /* 1 */
  98445. /***/ (function(module, exports, __webpack_require__) {
  98446. (function (global, factory) {
  98447. true ? module.exports = factory() :
  98448. typeof define === 'function' && define.amd ? define(factory) :
  98449. (global.deepmerge = factory());
  98450. }(this, (function () { 'use strict';
  98451. var isMergeableObject = function isMergeableObject(value) {
  98452. return isNonNullObject(value)
  98453. && !isSpecial(value)
  98454. };
  98455. function isNonNullObject(value) {
  98456. return !!value && typeof value === 'object'
  98457. }
  98458. function isSpecial(value) {
  98459. var stringValue = Object.prototype.toString.call(value);
  98460. return stringValue === '[object RegExp]'
  98461. || stringValue === '[object Date]'
  98462. || isReactElement(value)
  98463. }
  98464. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  98465. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  98466. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  98467. function isReactElement(value) {
  98468. return value.$$typeof === REACT_ELEMENT_TYPE
  98469. }
  98470. function emptyTarget(val) {
  98471. return Array.isArray(val) ? [] : {}
  98472. }
  98473. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  98474. var clone = !optionsArgument || optionsArgument.clone !== false;
  98475. return (clone && isMergeableObject(value))
  98476. ? deepmerge(emptyTarget(value), value, optionsArgument)
  98477. : value
  98478. }
  98479. function defaultArrayMerge(target, source, optionsArgument) {
  98480. return target.concat(source).map(function(element) {
  98481. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  98482. })
  98483. }
  98484. function mergeObject(target, source, optionsArgument) {
  98485. var destination = {};
  98486. if (isMergeableObject(target)) {
  98487. Object.keys(target).forEach(function(key) {
  98488. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  98489. });
  98490. }
  98491. Object.keys(source).forEach(function(key) {
  98492. if (!isMergeableObject(source[key]) || !target[key]) {
  98493. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  98494. } else {
  98495. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  98496. }
  98497. });
  98498. return destination
  98499. }
  98500. function deepmerge(target, source, optionsArgument) {
  98501. var sourceIsArray = Array.isArray(source);
  98502. var targetIsArray = Array.isArray(target);
  98503. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  98504. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  98505. if (!sourceAndTargetTypesMatch) {
  98506. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  98507. } else if (sourceIsArray) {
  98508. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  98509. return arrayMerge(target, source, optionsArgument)
  98510. } else {
  98511. return mergeObject(target, source, optionsArgument)
  98512. }
  98513. }
  98514. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  98515. if (!Array.isArray(array)) {
  98516. throw new Error('first argument should be an array')
  98517. }
  98518. return array.reduce(function(prev, next) {
  98519. return deepmerge(prev, next, optionsArgument)
  98520. }, {})
  98521. };
  98522. var deepmerge_1 = deepmerge;
  98523. return deepmerge_1;
  98524. })));
  98525. /***/ }),
  98526. /* 2 */
  98527. /***/ (function(module, exports, __webpack_require__) {
  98528. "use strict";
  98529. Object.defineProperty(exports, "__esModule", { value: true });
  98530. /**
  98531. * Is the provided string a URL?
  98532. *
  98533. * @param urlToCheck the url to inspect
  98534. */
  98535. function isUrl(urlToCheck) {
  98536. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  98537. return true;
  98538. }
  98539. return false;
  98540. }
  98541. exports.isUrl = isUrl;
  98542. /**
  98543. * Convert a string from kebab-case to camelCase
  98544. * @param s string to convert
  98545. */
  98546. function kebabToCamel(s) {
  98547. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  98548. }
  98549. exports.kebabToCamel = kebabToCamel;
  98550. //https://gist.github.com/youssman/745578062609e8acac9f
  98551. /**
  98552. * Convert a string from camelCase to kebab-case
  98553. * @param str string to convert
  98554. */
  98555. function camelToKebab(str) {
  98556. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  98557. }
  98558. exports.camelToKebab = camelToKebab;
  98559. /**
  98560. * This will extend an object with configuration values.
  98561. * What it practically does it take the keys from the configuration and set them on the object.
  98562. * I the configuration is a tree, it will traverse into the tree.
  98563. * @param object the object to extend
  98564. * @param config the configuration object that will extend the object
  98565. */
  98566. function extendClassWithConfig(object, config) {
  98567. if (!config)
  98568. return;
  98569. Object.keys(config).forEach(function (key) {
  98570. if (key in object && typeof object[key] !== 'function') {
  98571. // if (typeof object[key] === 'function') return;
  98572. // if it is an object, iterate internally until reaching basic types
  98573. if (typeof object[key] === 'object') {
  98574. extendClassWithConfig(object[key], config[key]);
  98575. }
  98576. else {
  98577. if (config[key] !== undefined) {
  98578. object[key] = config[key];
  98579. }
  98580. }
  98581. }
  98582. });
  98583. }
  98584. exports.extendClassWithConfig = extendClassWithConfig;
  98585. /***/ }),
  98586. /* 3 */
  98587. /***/ (function(module, exports, __webpack_require__) {
  98588. "use strict";
  98589. Object.defineProperty(exports, "__esModule", { value: true });
  98590. var babylonjs_1 = __webpack_require__(0);
  98591. var helper_1 = __webpack_require__(2);
  98592. /**
  98593. * This is a simple HTML mapper.
  98594. * This mapper parses a single HTML element and returns the configuration from its attributes.
  98595. * it parses numbers and boolean values to the corresponding variable types.
  98596. * The following HTML element:
  98597. * <div test="1" random-flag="true" a.string.object="test"> will result in the following configuration:
  98598. *
  98599. * {
  98600. * test: 1, //a number!
  98601. * randomFlag: boolean, //camelCase and boolean
  98602. * a: {
  98603. * string: {
  98604. * object: "test" //dot-separated object levels
  98605. * }
  98606. * }
  98607. * }
  98608. */
  98609. var HTMLMapper = /** @class */ (function () {
  98610. function HTMLMapper() {
  98611. }
  98612. /**
  98613. * Map a specific element and get configuration from it
  98614. * @param element the HTML element to analyze.
  98615. */
  98616. HTMLMapper.prototype.map = function (element) {
  98617. var config = {};
  98618. var _loop_1 = function (attrIdx) {
  98619. var attr = element.attributes.item(attrIdx);
  98620. if (!attr) {
  98621. return "continue";
  98622. }
  98623. // map "object.property" to the right configuration place.
  98624. var split = attr.nodeName.split('.');
  98625. split.reduce(function (currentConfig, key, idx) {
  98626. //convert html-style to json-style
  98627. var camelKey = helper_1.kebabToCamel(key);
  98628. if (idx === split.length - 1) {
  98629. var val = attr.nodeValue; // firefox warns nodeValue is deprecated, but I found no sign of it anywhere.
  98630. if (val === "true") {
  98631. val = true;
  98632. }
  98633. else if (val === "false") {
  98634. val = false;
  98635. }
  98636. else {
  98637. var isnum = !isNaN(parseFloat(val)) && isFinite(val); ///^\d+$/.test(val);
  98638. if (isnum) {
  98639. var number = parseFloat(val);
  98640. if (!isNaN(number)) {
  98641. val = number;
  98642. }
  98643. }
  98644. }
  98645. currentConfig[camelKey] = val;
  98646. }
  98647. else {
  98648. currentConfig[camelKey] = currentConfig[camelKey] || {};
  98649. }
  98650. return currentConfig[camelKey];
  98651. }, config);
  98652. };
  98653. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  98654. _loop_1(attrIdx);
  98655. }
  98656. return config;
  98657. };
  98658. return HTMLMapper;
  98659. }());
  98660. /**
  98661. * A simple string-to-JSON mapper.
  98662. * This is the main mapper, used to analyze downloaded JSON-Configuration or JSON payload
  98663. */
  98664. var JSONMapper = /** @class */ (function () {
  98665. function JSONMapper() {
  98666. }
  98667. JSONMapper.prototype.map = function (rawSource) {
  98668. return JSON.parse(rawSource);
  98669. };
  98670. return JSONMapper;
  98671. }());
  98672. /**
  98673. * The DOM Mapper will traverse an entire DOM Tree and will load the configuration from the
  98674. * DOM elements and attributes.
  98675. */
  98676. var DOMMapper = /** @class */ (function () {
  98677. function DOMMapper() {
  98678. }
  98679. /**
  98680. * The mapping function that will convert HTML data to a viewer configuration object
  98681. * @param baseElement the baseElement from which to start traversing
  98682. * @returns a ViewerCOnfiguration object from the provided HTML Element
  98683. */
  98684. DOMMapper.prototype.map = function (baseElement) {
  98685. var htmlMapper = new HTMLMapper();
  98686. var config = htmlMapper.map(baseElement);
  98687. var traverseChildren = function (element, partConfig) {
  98688. var children = element.children;
  98689. if (children.length) {
  98690. for (var i = 0; i < children.length; ++i) {
  98691. var item = children.item(i);
  98692. // use the HTML Mapper to read configuration from a single element
  98693. var configMapped = htmlMapper.map(item);
  98694. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  98695. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  98696. partConfig[key] = [];
  98697. }
  98698. else {
  98699. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  98700. partConfig.push(configMapped);
  98701. }
  98702. else if (partConfig[key]) {
  98703. //exists already! probably an array
  98704. element.setAttribute('array', 'true');
  98705. var oldItem = partConfig[key];
  98706. partConfig = [oldItem, configMapped];
  98707. }
  98708. else {
  98709. partConfig[key] = configMapped;
  98710. }
  98711. }
  98712. traverseChildren(item, partConfig[key] || configMapped);
  98713. }
  98714. }
  98715. return partConfig;
  98716. };
  98717. traverseChildren(baseElement, config);
  98718. return config;
  98719. };
  98720. return DOMMapper;
  98721. }());
  98722. /**
  98723. * The MapperManager manages the different implemented mappers.
  98724. * It allows the user to register new mappers as well and use them to parse their own configuration data
  98725. */
  98726. var MapperManager = /** @class */ (function () {
  98727. function MapperManager() {
  98728. this._mappers = {
  98729. "html": new HTMLMapper(),
  98730. "json": new JSONMapper(),
  98731. "dom": new DOMMapper()
  98732. };
  98733. }
  98734. /**
  98735. * Get a specific configuration mapper.
  98736. *
  98737. * @param type the name of the mapper to load
  98738. */
  98739. MapperManager.prototype.getMapper = function (type) {
  98740. if (!this._mappers[type]) {
  98741. babylonjs_1.Tools.Error("No mapper defined for " + type);
  98742. }
  98743. return this._mappers[type];
  98744. };
  98745. /**
  98746. * Use this functio to register your own configuration mapper.
  98747. * After a mapper is registered, it can be used to parse the specific type fo configuration to the standard ViewerConfiguration.
  98748. * @param type the name of the mapper. This will be used to define the configuration type and/or to get the mapper
  98749. * @param mapper The implemented mapper
  98750. */
  98751. MapperManager.prototype.registerMapper = function (type, mapper) {
  98752. this._mappers[type] = mapper;
  98753. };
  98754. /**
  98755. * Dispose the mapper manager and all of its mappers.
  98756. */
  98757. MapperManager.prototype.dispose = function () {
  98758. this._mappers = {};
  98759. };
  98760. /**
  98761. * The default mapper is the JSON mapper.
  98762. */
  98763. MapperManager.DefaultMapper = 'json';
  98764. return MapperManager;
  98765. }());
  98766. exports.MapperManager = MapperManager;
  98767. /**
  98768. * mapperManager is a singleton of the type MapperManager.
  98769. * The mapperManager can be disposed directly with calling mapperManager.dispose()
  98770. * or indirectly with using BabylonViewer.disposeAll()
  98771. */
  98772. exports.mapperManager = new MapperManager();
  98773. /***/ }),
  98774. /* 4 */
  98775. /***/ (function(module, exports, __webpack_require__) {
  98776. "use strict";
  98777. Object.defineProperty(exports, "__esModule", { value: true });
  98778. var babylonjs_1 = __webpack_require__(0);
  98779. var modelAnimation_1 = __webpack_require__(30);
  98780. var deepmerge = __webpack_require__(1);
  98781. var helper_1 = __webpack_require__(2);
  98782. /**
  98783. * The current state of the model
  98784. */
  98785. var ModelState;
  98786. (function (ModelState) {
  98787. ModelState[ModelState["INIT"] = 0] = "INIT";
  98788. ModelState[ModelState["LOADING"] = 1] = "LOADING";
  98789. ModelState[ModelState["LOADED"] = 2] = "LOADED";
  98790. ModelState[ModelState["ENTRY"] = 3] = "ENTRY";
  98791. ModelState[ModelState["ENTRYDONE"] = 4] = "ENTRYDONE";
  98792. ModelState[ModelState["COMPLETE"] = 5] = "COMPLETE";
  98793. ModelState[ModelState["CANCELED"] = 6] = "CANCELED";
  98794. ModelState[ModelState["ERROR"] = 7] = "ERROR";
  98795. })(ModelState = exports.ModelState || (exports.ModelState = {}));
  98796. /**
  98797. * The viewer model is a container for all assets representing a sngle loaded model.
  98798. */
  98799. var ViewerModel = /** @class */ (function () {
  98800. function ViewerModel(_viewer, modelConfiguration) {
  98801. var _this = this;
  98802. this._viewer = _viewer;
  98803. /**
  98804. * the list of meshes that are a part of this model
  98805. */
  98806. this._meshes = [];
  98807. /**
  98808. * ParticleSystems connected to this model
  98809. */
  98810. this.particleSystems = [];
  98811. /**
  98812. * Skeletons defined in this model
  98813. */
  98814. this.skeletons = [];
  98815. this._loaderDone = false;
  98816. this._animatables = [];
  98817. this._frameRate = 60;
  98818. this._shadowsRenderedAfterLoad = false;
  98819. this.onLoadedObservable = new babylonjs_1.Observable();
  98820. this.onLoadErrorObservable = new babylonjs_1.Observable();
  98821. this.onLoadProgressObservable = new babylonjs_1.Observable();
  98822. this.onCompleteObservable = new babylonjs_1.Observable();
  98823. this.onAfterConfigure = new babylonjs_1.Observable();
  98824. this.state = ModelState.INIT;
  98825. this.rootMesh = new babylonjs_1.AbstractMesh("modelRootMesh", this._viewer.sceneManager.scene);
  98826. this._pivotMesh = new babylonjs_1.AbstractMesh("pivotMesh", this._viewer.sceneManager.scene);
  98827. this._pivotMesh.parent = this.rootMesh;
  98828. // rotate 180, gltf fun
  98829. this._pivotMesh.rotation.y += Math.PI;
  98830. this._scaleTransition = new babylonjs_1.Animation("scaleAnimation", "scaling", this._frameRate, babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3, babylonjs_1.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98831. this._animations = [];
  98832. //create a copy of the configuration to make sure it doesn't change even after it is changed in the viewer
  98833. this._modelConfiguration = deepmerge(this._viewer.configuration.model || {}, modelConfiguration);
  98834. this._viewer.sceneManager.models.push(this);
  98835. this._viewer.onModelAddedObservable.notifyObservers(this);
  98836. if (this._modelConfiguration.entryAnimation) {
  98837. this.rootMesh.setEnabled(false);
  98838. }
  98839. this.onLoadedObservable.add(function () {
  98840. _this.updateConfiguration(_this._modelConfiguration);
  98841. _this._viewer.onModelLoadedObservable.notifyObservers(_this);
  98842. _this._initAnimations();
  98843. });
  98844. this.onCompleteObservable.add(function () {
  98845. _this.state = ModelState.COMPLETE;
  98846. });
  98847. }
  98848. Object.defineProperty(ViewerModel.prototype, "shadowsRenderedAfterLoad", {
  98849. get: function () {
  98850. return this._shadowsRenderedAfterLoad;
  98851. },
  98852. set: function (rendered) {
  98853. if (!rendered) {
  98854. throw new Error("can only be enabled");
  98855. }
  98856. else {
  98857. this._shadowsRenderedAfterLoad = rendered;
  98858. }
  98859. },
  98860. enumerable: true,
  98861. configurable: true
  98862. });
  98863. Object.defineProperty(ViewerModel.prototype, "enabled", {
  98864. /**
  98865. * Is this model enabled?
  98866. */
  98867. get: function () {
  98868. return this.rootMesh.isEnabled();
  98869. },
  98870. /**
  98871. * Set whether this model is enabled or not.
  98872. */
  98873. set: function (enable) {
  98874. this.rootMesh.setEnabled(enable);
  98875. },
  98876. enumerable: true,
  98877. configurable: true
  98878. });
  98879. Object.defineProperty(ViewerModel.prototype, "loaderDone", {
  98880. set: function (done) {
  98881. this._loaderDone = done;
  98882. this._checkCompleteState();
  98883. },
  98884. enumerable: true,
  98885. configurable: true
  98886. });
  98887. ViewerModel.prototype._checkCompleteState = function () {
  98888. if (this._loaderDone && (this.state === ModelState.ENTRYDONE)) {
  98889. this._modelComplete();
  98890. }
  98891. };
  98892. /**
  98893. * Get the viewer showing this model
  98894. */
  98895. ViewerModel.prototype.getViewer = function () {
  98896. return this._viewer;
  98897. };
  98898. /**
  98899. * Add a mesh to this model.
  98900. * Any mesh that has no parent will be provided with the root mesh as its new parent.
  98901. *
  98902. * @param mesh the new mesh to add
  98903. * @param triggerLoaded should this mesh trigger the onLoaded observable. Used when adding meshes manually.
  98904. */
  98905. ViewerModel.prototype.addMesh = function (mesh, triggerLoaded) {
  98906. if (!mesh.parent) {
  98907. mesh.parent = this._pivotMesh;
  98908. }
  98909. mesh.receiveShadows = !!this.configuration.receiveShadows;
  98910. this._meshes.push(mesh);
  98911. if (triggerLoaded) {
  98912. return this.onLoadedObservable.notifyObserversWithPromise(this);
  98913. }
  98914. };
  98915. Object.defineProperty(ViewerModel.prototype, "meshes", {
  98916. /**
  98917. * get the list of meshes (excluding the root mesh)
  98918. */
  98919. get: function () {
  98920. return this._meshes;
  98921. },
  98922. enumerable: true,
  98923. configurable: true
  98924. });
  98925. Object.defineProperty(ViewerModel.prototype, "configuration", {
  98926. /**
  98927. * Get the model's configuration
  98928. */
  98929. get: function () {
  98930. return this._modelConfiguration;
  98931. },
  98932. /**
  98933. * (Re-)set the model's entire configuration
  98934. * @param newConfiguration the new configuration to replace the new one
  98935. */
  98936. set: function (newConfiguration) {
  98937. this._modelConfiguration = newConfiguration;
  98938. this._configureModel();
  98939. },
  98940. enumerable: true,
  98941. configurable: true
  98942. });
  98943. /**
  98944. * Update the current configuration with new values.
  98945. * Configuration will not be overwritten, but merged with the new configuration.
  98946. * Priority is to the new configuration
  98947. * @param newConfiguration the configuration to be merged into the current configuration;
  98948. */
  98949. ViewerModel.prototype.updateConfiguration = function (newConfiguration) {
  98950. this._modelConfiguration = deepmerge(this._modelConfiguration, newConfiguration);
  98951. this._configureModel();
  98952. };
  98953. ViewerModel.prototype._initAnimations = function () {
  98954. var _this = this;
  98955. // check if this is not a gltf loader and init the animations
  98956. if (this.skeletons.length) {
  98957. this.skeletons.forEach(function (skeleton, idx) {
  98958. var ag = new babylonjs_1.AnimationGroup("animation-" + idx, _this._viewer.sceneManager.scene);
  98959. skeleton.getAnimatables().forEach(function (a) {
  98960. if (a.animations[0]) {
  98961. ag.addTargetedAnimation(a.animations[0], a);
  98962. }
  98963. });
  98964. _this.addAnimationGroup(ag);
  98965. });
  98966. }
  98967. var completeCallback = function () {
  98968. };
  98969. if (this._modelConfiguration.animation) {
  98970. if (this._modelConfiguration.animation.playOnce) {
  98971. this._animations.forEach(function (a) {
  98972. a.playMode = 0 /* ONCE */;
  98973. });
  98974. }
  98975. if (this._modelConfiguration.animation.autoStart && this._animations.length) {
  98976. var animationName_1 = this._modelConfiguration.animation.autoStart === true ?
  98977. this._animations[0].name : this._modelConfiguration.animation.autoStart;
  98978. completeCallback = function () {
  98979. _this.playAnimation(animationName_1);
  98980. };
  98981. }
  98982. }
  98983. this._enterScene(completeCallback);
  98984. };
  98985. /**
  98986. * Animates the model from the current position to the default position
  98987. * @param completeCallback A function to call when the animation has completed
  98988. */
  98989. ViewerModel.prototype._enterScene = function (completeCallback) {
  98990. var _this = this;
  98991. var callback = function () {
  98992. _this.state = ModelState.ENTRYDONE;
  98993. _this._viewer.sceneManager.animationBlendingEnabled = true;
  98994. _this._checkCompleteState();
  98995. if (completeCallback)
  98996. completeCallback();
  98997. };
  98998. if (!this._entryAnimation) {
  98999. callback();
  99000. return;
  99001. }
  99002. this.rootMesh.setEnabled(true);
  99003. // disable blending for the sake of the entry animation;
  99004. this._viewer.sceneManager.animationBlendingEnabled = false;
  99005. this._applyAnimation(this._entryAnimation, true, callback);
  99006. };
  99007. /**
  99008. * Animates the model from the current position to the exit-screen position
  99009. * @param completeCallback A function to call when the animation has completed
  99010. */
  99011. ViewerModel.prototype._exitScene = function (completeCallback) {
  99012. if (!this._exitAnimation) {
  99013. completeCallback();
  99014. return;
  99015. }
  99016. this._applyAnimation(this._exitAnimation, false, completeCallback);
  99017. };
  99018. ViewerModel.prototype._modelComplete = function () {
  99019. var _this = this;
  99020. //reapply material defines to be sure:
  99021. var meshes = this._pivotMesh.getChildMeshes(false);
  99022. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  99023. _this._applyModelMaterialConfiguration(mesh.material);
  99024. });
  99025. this.state = ModelState.COMPLETE;
  99026. this.onCompleteObservable.notifyObservers(this);
  99027. };
  99028. /**
  99029. * Add a new animation group to this model.
  99030. * @param animationGroup the new animation group to be added
  99031. */
  99032. ViewerModel.prototype.addAnimationGroup = function (animationGroup) {
  99033. this._animations.push(new modelAnimation_1.GroupModelAnimation(animationGroup));
  99034. };
  99035. /**
  99036. * Get the ModelAnimation array
  99037. */
  99038. ViewerModel.prototype.getAnimations = function () {
  99039. return this._animations;
  99040. };
  99041. /**
  99042. * Get the animations' names. Using the names you can play a specific animation.
  99043. */
  99044. ViewerModel.prototype.getAnimationNames = function () {
  99045. return this._animations.map(function (a) { return a.name; });
  99046. };
  99047. /**
  99048. * Get an animation by the provided name. Used mainly when playing n animation.
  99049. * @param name the name of the animation to find
  99050. */
  99051. ViewerModel.prototype._getAnimationByName = function (name) {
  99052. // can't use .find, noe available on IE
  99053. var filtered = this._animations.filter(function (a) { return a.name === name; });
  99054. // what the next line means - if two animations have the same name, they will not be returned!
  99055. if (filtered.length === 1) {
  99056. return filtered[0];
  99057. }
  99058. else {
  99059. return null;
  99060. }
  99061. };
  99062. /**
  99063. * Choose an initialized animation using its name and start playing it
  99064. * @param name the name of the animation to play
  99065. * @returns The model aniamtion to be played.
  99066. */
  99067. ViewerModel.prototype.playAnimation = function (name) {
  99068. var animation = this.setCurrentAnimationByName(name);
  99069. if (animation) {
  99070. animation.start();
  99071. }
  99072. return animation;
  99073. };
  99074. ViewerModel.prototype.setCurrentAnimationByName = function (name) {
  99075. var animation = this._getAnimationByName(name);
  99076. if (animation) {
  99077. if (this.currentAnimation && this.currentAnimation.state !== 3 /* STOPPED */) {
  99078. this.currentAnimation.stop();
  99079. }
  99080. this.currentAnimation = animation;
  99081. return animation;
  99082. }
  99083. else {
  99084. throw new Error("animation not found - " + name);
  99085. }
  99086. };
  99087. ViewerModel.prototype._configureModel = function () {
  99088. var _this = this;
  99089. // this can be changed to the meshes that have rootMesh a parent without breaking anything.
  99090. var meshesWithNoParent = [this.rootMesh]; //this._meshes.filter(m => m.parent === this.rootMesh);
  99091. var updateMeshesWithNoParent = function (variable, value, param) {
  99092. meshesWithNoParent.forEach(function (mesh) {
  99093. if (param) {
  99094. mesh[variable][param] = value;
  99095. }
  99096. else {
  99097. mesh[variable] = value;
  99098. }
  99099. });
  99100. };
  99101. var updateXYZ = function (variable, configValues) {
  99102. if (configValues.x !== undefined) {
  99103. updateMeshesWithNoParent(variable, configValues.x, 'x');
  99104. }
  99105. if (configValues.y !== undefined) {
  99106. updateMeshesWithNoParent(variable, configValues.y, 'y');
  99107. }
  99108. if (configValues.z !== undefined) {
  99109. updateMeshesWithNoParent(variable, configValues.z, 'z');
  99110. }
  99111. if (configValues.w !== undefined) {
  99112. updateMeshesWithNoParent(variable, configValues.w, 'w');
  99113. }
  99114. };
  99115. if (this._modelConfiguration.normalize) {
  99116. var center = false;
  99117. var unitSize = false;
  99118. var parentIndex = void 0;
  99119. if (this._modelConfiguration.normalize === true) {
  99120. center = true;
  99121. unitSize = true;
  99122. }
  99123. else {
  99124. center = !!this._modelConfiguration.normalize.center;
  99125. unitSize = !!this._modelConfiguration.normalize.unitSize;
  99126. parentIndex = this._modelConfiguration.normalize.parentIndex;
  99127. }
  99128. var meshesToNormalize = [];
  99129. if (parentIndex !== undefined) {
  99130. meshesToNormalize.push(this._meshes[parentIndex]);
  99131. }
  99132. else {
  99133. meshesToNormalize = this._pivotMesh.getChildMeshes(true).length === 1 ? [this._pivotMesh] : meshesWithNoParent;
  99134. }
  99135. if (unitSize) {
  99136. meshesToNormalize.forEach(function (mesh) {
  99137. mesh.normalizeToUnitCube(true);
  99138. mesh.computeWorldMatrix(true);
  99139. });
  99140. }
  99141. if (center) {
  99142. meshesToNormalize.forEach(function (mesh) {
  99143. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  99144. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  99145. var halfSizeVec = sizeVec.scale(0.5);
  99146. var center = boundingInfo.min.add(halfSizeVec);
  99147. mesh.position = center.scale(-1);
  99148. mesh.position.y += halfSizeVec.y;
  99149. // Recompute Info.
  99150. mesh.computeWorldMatrix(true);
  99151. });
  99152. }
  99153. }
  99154. else {
  99155. // if centered, should be done here
  99156. }
  99157. // position?
  99158. if (this._modelConfiguration.position) {
  99159. updateXYZ('position', this._modelConfiguration.position);
  99160. }
  99161. if (this._modelConfiguration.rotation) {
  99162. //quaternion?
  99163. if (this._modelConfiguration.rotation.w) {
  99164. meshesWithNoParent.forEach(function (mesh) {
  99165. if (!mesh.rotationQuaternion) {
  99166. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  99167. }
  99168. });
  99169. updateXYZ('rotationQuaternion', this._modelConfiguration.rotation);
  99170. }
  99171. else {
  99172. updateXYZ('rotation', this._modelConfiguration.rotation);
  99173. }
  99174. }
  99175. if (this._modelConfiguration.rotationOffsetAxis) {
  99176. var rotationAxis_1 = new babylonjs_1.Vector3(0, 0, 0).copyFrom(this._modelConfiguration.rotationOffsetAxis);
  99177. meshesWithNoParent.forEach(function (m) {
  99178. if (_this._modelConfiguration.rotationOffsetAngle) {
  99179. m.rotate(rotationAxis_1, _this._modelConfiguration.rotationOffsetAngle);
  99180. }
  99181. });
  99182. }
  99183. if (this._modelConfiguration.scaling) {
  99184. updateXYZ('scaling', this._modelConfiguration.scaling);
  99185. }
  99186. if (this._modelConfiguration.castShadow) {
  99187. this._meshes.forEach(function (mesh) {
  99188. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  99189. });
  99190. }
  99191. var meshes = this._pivotMesh.getChildMeshes(false);
  99192. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  99193. _this._applyModelMaterialConfiguration(mesh.material);
  99194. });
  99195. if (this._modelConfiguration.entryAnimation) {
  99196. this._entryAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.entryAnimation);
  99197. }
  99198. if (this._modelConfiguration.exitAnimation) {
  99199. this._exitAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.exitAnimation);
  99200. }
  99201. this.onAfterConfigure.notifyObservers(this);
  99202. };
  99203. ViewerModel.prototype._modelAnimationConfigurationToObject = function (animConfig) {
  99204. var anim = {
  99205. time: 0.5
  99206. };
  99207. if (animConfig.scaling) {
  99208. anim.scaling = babylonjs_1.Vector3.Zero();
  99209. }
  99210. if (animConfig.easingFunction !== undefined) {
  99211. anim.easingFunction = animConfig.easingFunction;
  99212. }
  99213. if (animConfig.easingMode !== undefined) {
  99214. anim.easingMode = animConfig.easingMode;
  99215. }
  99216. helper_1.extendClassWithConfig(anim, animConfig);
  99217. return anim;
  99218. };
  99219. /**
  99220. * Apply a material configuration to a material
  99221. * @param material Material to apply configuration to
  99222. */
  99223. ViewerModel.prototype._applyModelMaterialConfiguration = function (material) {
  99224. if (!this._modelConfiguration.material)
  99225. return;
  99226. helper_1.extendClassWithConfig(material, this._modelConfiguration.material);
  99227. if (material instanceof babylonjs_1.PBRMaterial) {
  99228. if (this._modelConfiguration.material.directIntensity !== undefined) {
  99229. material.directIntensity = this._modelConfiguration.material.directIntensity;
  99230. }
  99231. if (this._modelConfiguration.material.emissiveIntensity !== undefined) {
  99232. material.emissiveIntensity = this._modelConfiguration.material.emissiveIntensity;
  99233. }
  99234. if (this._modelConfiguration.material.environmentIntensity !== undefined) {
  99235. material.environmentIntensity = this._modelConfiguration.material.environmentIntensity;
  99236. }
  99237. if (this._modelConfiguration.material.directEnabled !== undefined) {
  99238. material.disableLighting = !this._modelConfiguration.material.directEnabled;
  99239. }
  99240. if (this._viewer.sceneManager.reflectionColor) {
  99241. material.reflectionColor = this._viewer.sceneManager.reflectionColor;
  99242. }
  99243. }
  99244. else if (material instanceof babylonjs_1.MultiMaterial) {
  99245. for (var i = 0; i < material.subMaterials.length; i++) {
  99246. var subMaterial = material.subMaterials[i];
  99247. if (subMaterial) {
  99248. this._applyModelMaterialConfiguration(subMaterial);
  99249. }
  99250. }
  99251. }
  99252. };
  99253. /**
  99254. * Start entry/exit animation given an animation configuration
  99255. * @param animationConfiguration Entry/Exit animation configuration
  99256. * @param isEntry Pass true if the animation is an entry animation
  99257. * @param completeCallback Callback to execute when the animation completes
  99258. */
  99259. ViewerModel.prototype._applyAnimation = function (animationConfiguration, isEntry, completeCallback) {
  99260. var animations = [];
  99261. //scale
  99262. if (animationConfiguration.scaling) {
  99263. var scaleStart = isEntry ? animationConfiguration.scaling : new babylonjs_1.Vector3(1, 1, 1);
  99264. var scaleEnd = isEntry ? new babylonjs_1.Vector3(1, 1, 1) : animationConfiguration.scaling;
  99265. if (!scaleStart.equals(scaleEnd)) {
  99266. this.rootMesh.scaling = scaleStart;
  99267. this._setLinearKeys(this._scaleTransition, this.rootMesh.scaling, scaleEnd, animationConfiguration.time);
  99268. animations.push(this._scaleTransition);
  99269. }
  99270. }
  99271. //Start the animation(s)
  99272. this.transitionTo(animations, animationConfiguration.time, this._createEasingFunction(animationConfiguration.easingFunction), animationConfiguration.easingMode, function () { if (completeCallback)
  99273. completeCallback(); });
  99274. };
  99275. /**
  99276. * Begin @animations with the specified @easingFunction
  99277. * @param animations The BABYLON Animations to begin
  99278. * @param duration of transition, in seconds
  99279. * @param easingFunction An easing function to apply
  99280. * @param easingMode A easing mode to apply to the easingFunction
  99281. * @param onAnimationEnd Call back trigger at the end of the animation.
  99282. */
  99283. ViewerModel.prototype.transitionTo = function (animations, duration, easingFunction, easingMode, onAnimationEnd) {
  99284. if (easingMode === void 0) { easingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT; }
  99285. if (easingFunction) {
  99286. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  99287. var animation = animations_1[_i];
  99288. easingFunction.setEasingMode(easingMode);
  99289. animation.setEasingFunction(easingFunction);
  99290. }
  99291. }
  99292. //Stop any current animations before starting the new one - merging not yet supported.
  99293. this.stopAllAnimations();
  99294. this.rootMesh.animations = animations;
  99295. if (this._viewer.sceneManager.scene.beginAnimation) {
  99296. var animatable = this._viewer.sceneManager.scene.beginAnimation(this.rootMesh, 0, this._frameRate * duration, false, 1, function () {
  99297. if (onAnimationEnd) {
  99298. onAnimationEnd();
  99299. }
  99300. });
  99301. this._animatables.push(animatable);
  99302. }
  99303. };
  99304. /**
  99305. * Sets key values on an Animation from first to last frame.
  99306. * @param animation The Babylon animation object to set keys on
  99307. * @param startValue The value of the first key
  99308. * @param endValue The value of the last key
  99309. * @param duration The duration of the animation, used to determine the end frame
  99310. */
  99311. ViewerModel.prototype._setLinearKeys = function (animation, startValue, endValue, duration) {
  99312. animation.setKeys([
  99313. {
  99314. frame: 0,
  99315. value: startValue
  99316. },
  99317. {
  99318. frame: this._frameRate * duration,
  99319. value: endValue
  99320. }
  99321. ]);
  99322. };
  99323. /**
  99324. * Creates and returns a Babylon easing funtion object based on a string representing the Easing function
  99325. * @param easingFunctionID The enum of the easing funtion to create
  99326. * @return The newly created Babylon easing function object
  99327. */
  99328. ViewerModel.prototype._createEasingFunction = function (easingFunctionID) {
  99329. var easingFunction;
  99330. switch (easingFunctionID) {
  99331. case 1 /* CircleEase */:
  99332. easingFunction = new babylonjs_1.CircleEase();
  99333. break;
  99334. case 2 /* BackEase */:
  99335. easingFunction = new babylonjs_1.BackEase(0.3);
  99336. break;
  99337. case 3 /* BounceEase */:
  99338. easingFunction = new babylonjs_1.BounceEase();
  99339. break;
  99340. case 4 /* CubicEase */:
  99341. easingFunction = new babylonjs_1.CubicEase();
  99342. break;
  99343. case 5 /* ElasticEase */:
  99344. easingFunction = new babylonjs_1.ElasticEase();
  99345. break;
  99346. case 6 /* ExponentialEase */:
  99347. easingFunction = new babylonjs_1.ExponentialEase();
  99348. break;
  99349. case 7 /* PowerEase */:
  99350. easingFunction = new babylonjs_1.PowerEase();
  99351. break;
  99352. case 8 /* QuadraticEase */:
  99353. easingFunction = new babylonjs_1.QuadraticEase();
  99354. break;
  99355. case 9 /* QuarticEase */:
  99356. easingFunction = new babylonjs_1.QuarticEase();
  99357. break;
  99358. case 10 /* QuinticEase */:
  99359. easingFunction = new babylonjs_1.QuinticEase();
  99360. break;
  99361. case 11 /* SineEase */:
  99362. easingFunction = new babylonjs_1.SineEase();
  99363. break;
  99364. default:
  99365. babylonjs_1.Tools.Log("No ease function found");
  99366. break;
  99367. }
  99368. return easingFunction;
  99369. };
  99370. /**
  99371. * Stops and removes all animations that have been applied to the model
  99372. */
  99373. ViewerModel.prototype.stopAllAnimations = function () {
  99374. if (this.rootMesh) {
  99375. this.rootMesh.animations = [];
  99376. }
  99377. if (this.currentAnimation) {
  99378. this.currentAnimation.stop();
  99379. }
  99380. while (this._animatables.length) {
  99381. this._animatables[0].onAnimationEnd = null;
  99382. this._animatables[0].stop();
  99383. this._animatables.shift();
  99384. }
  99385. };
  99386. /**
  99387. * Will remove this model from the viewer (but NOT dispose it).
  99388. */
  99389. ViewerModel.prototype.remove = function () {
  99390. this.stopAllAnimations();
  99391. this._viewer.sceneManager.models.splice(this._viewer.sceneManager.models.indexOf(this), 1);
  99392. // hide it
  99393. this.rootMesh.isVisible = false;
  99394. this._viewer.onModelRemovedObservable.notifyObservers(this);
  99395. };
  99396. /**
  99397. * Dispose this model, including all of its associated assets.
  99398. */
  99399. ViewerModel.prototype.dispose = function () {
  99400. this.remove();
  99401. this.onAfterConfigure.clear();
  99402. this.onLoadedObservable.clear();
  99403. this.onLoadErrorObservable.clear();
  99404. this.onLoadProgressObservable.clear();
  99405. if (this.loader && this.loader.name === "gltf") {
  99406. this.loader.dispose();
  99407. }
  99408. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  99409. this.particleSystems.length = 0;
  99410. this.skeletons.forEach(function (s) { return s.dispose(); });
  99411. this.skeletons.length = 0;
  99412. this._animations.forEach(function (ag) { return ag.dispose(); });
  99413. this._animations.length = 0;
  99414. this.rootMesh.dispose(false, true);
  99415. };
  99416. return ViewerModel;
  99417. }());
  99418. exports.ViewerModel = ViewerModel;
  99419. /***/ }),
  99420. /* 5 */
  99421. /***/ (function(module, exports, __webpack_require__) {
  99422. "use strict";
  99423. Object.defineProperty(exports, "__esModule", { value: true });
  99424. var babylonjs_1 = __webpack_require__(0);
  99425. /**
  99426. * Receives Telemetry events and raises events to the API
  99427. */
  99428. var TelemetryManager = /** @class */ (function () {
  99429. function TelemetryManager() {
  99430. this.onEventBroadcastedObservable = new babylonjs_1.Observable();
  99431. this._event = this._eventEnabled;
  99432. }
  99433. Object.defineProperty(TelemetryManager.prototype, "broadcast", {
  99434. /**
  99435. * Receives a telemetry event
  99436. * @param event The name of the Telemetry event
  99437. * @param details An additional value, or an object containing a list of property/value pairs
  99438. */
  99439. get: function () {
  99440. return this._event;
  99441. },
  99442. enumerable: true,
  99443. configurable: true
  99444. });
  99445. /**
  99446. * Log a Telemetry event for errors raised on the WebGL context.
  99447. * @param engine The Babylon engine with the WebGL context.
  99448. */
  99449. TelemetryManager.prototype.flushWebGLErrors = function (viewer) {
  99450. var engine = viewer.engine;
  99451. if (!engine) {
  99452. return;
  99453. }
  99454. var logErrors = true;
  99455. while (logErrors) {
  99456. var gl = engine._gl;
  99457. if (gl && gl.getError) {
  99458. var error = gl.getError();
  99459. if (error === gl.NO_ERROR) {
  99460. logErrors = false;
  99461. }
  99462. else {
  99463. this.broadcast("WebGL Error", viewer, { error: error });
  99464. }
  99465. }
  99466. else {
  99467. logErrors = false;
  99468. }
  99469. }
  99470. };
  99471. Object.defineProperty(TelemetryManager.prototype, "enable", {
  99472. /**
  99473. * Enable or disable telemetry events
  99474. * @param enabled Boolan, true if events are enabled
  99475. */
  99476. set: function (enabled) {
  99477. if (enabled) {
  99478. this._event = this._eventEnabled;
  99479. }
  99480. else {
  99481. this._event = this._eventDisabled;
  99482. }
  99483. },
  99484. enumerable: true,
  99485. configurable: true
  99486. });
  99487. /**
  99488. * Called on event when disabled, typically do nothing here
  99489. */
  99490. TelemetryManager.prototype._eventDisabled = function () {
  99491. // nothing to do
  99492. };
  99493. /**
  99494. * Called on event when enabled
  99495. * @param event - The name of the Telemetry event
  99496. * @param details An additional value, or an object containing a list of property/value pairs
  99497. */
  99498. TelemetryManager.prototype._eventEnabled = function (event, viewer, details) {
  99499. var telemetryData = {
  99500. viewer: viewer,
  99501. event: event,
  99502. session: this.session,
  99503. date: new Date(),
  99504. now: window.performance ? window.performance.now() : Date.now(),
  99505. detail: null
  99506. };
  99507. if (typeof details === "object") {
  99508. for (var attr in details) {
  99509. if (details.hasOwnProperty(attr)) {
  99510. telemetryData[attr] = details[attr];
  99511. }
  99512. }
  99513. }
  99514. else if (details) {
  99515. telemetryData.detail = details;
  99516. }
  99517. this.onEventBroadcastedObservable.notifyObservers(telemetryData);
  99518. };
  99519. Object.defineProperty(TelemetryManager.prototype, "session", {
  99520. /**
  99521. * Returns the current session ID or creates one if it doesn't exixt
  99522. * @return The current session ID
  99523. */
  99524. get: function () {
  99525. if (!this._currentSessionId) {
  99526. //String + Timestamp + Random Integer
  99527. this._currentSessionId = "SESSION_" + Date.now() + Math.floor(Math.random() * 0x10000);
  99528. }
  99529. return this._currentSessionId;
  99530. },
  99531. enumerable: true,
  99532. configurable: true
  99533. });
  99534. /**
  99535. * Disposes the telemetry manager
  99536. */
  99537. TelemetryManager.prototype.dispose = function () {
  99538. this.onEventBroadcastedObservable.clear();
  99539. delete this.onEventBroadcastedObservable;
  99540. };
  99541. return TelemetryManager;
  99542. }());
  99543. exports.TelemetryManager = TelemetryManager;
  99544. exports.telemetryManager = new TelemetryManager();
  99545. /***/ }),
  99546. /* 6 */
  99547. /***/ (function(module, exports, __webpack_require__) {
  99548. "use strict";
  99549. function __export(m) {
  99550. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  99551. }
  99552. Object.defineProperty(exports, "__esModule", { value: true });
  99553. /// <reference path="../../dist/babylon.glTF2Interface.d.ts"/>
  99554. var mappers_1 = __webpack_require__(3);
  99555. exports.mapperManager = mappers_1.mapperManager;
  99556. var globals_1 = __webpack_require__(7);
  99557. exports.viewerGlobals = globals_1.viewerGlobals;
  99558. var viewerManager_1 = __webpack_require__(8);
  99559. exports.viewerManager = viewerManager_1.viewerManager;
  99560. var defaultViewer_1 = __webpack_require__(9);
  99561. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  99562. var viewer_1 = __webpack_require__(10);
  99563. exports.AbstractViewer = viewer_1.AbstractViewer;
  99564. var telemetryManager_1 = __webpack_require__(5);
  99565. exports.telemetryManager = telemetryManager_1.telemetryManager;
  99566. var modelLoader_1 = __webpack_require__(22);
  99567. exports.ModelLoader = modelLoader_1.ModelLoader;
  99568. var viewerModel_1 = __webpack_require__(4);
  99569. exports.ViewerModel = viewerModel_1.ViewerModel;
  99570. exports.ModelState = viewerModel_1.ModelState;
  99571. /**
  99572. * BabylonJS Viewer
  99573. *
  99574. * An HTML-Based viewer for 3D models, based on BabylonJS and its extensions.
  99575. */
  99576. var BABYLON = __webpack_require__(0);
  99577. exports.BABYLON = BABYLON;
  99578. // load needed modules.
  99579. __webpack_require__(23);
  99580. __webpack_require__(56);
  99581. var initializer_1 = __webpack_require__(57);
  99582. exports.InitTags = initializer_1.InitTags;
  99583. // promise polyfill, if needed!
  99584. BABYLON.PromisePolyfill.Apply();
  99585. initializer_1.initListeners();
  99586. //deprectaed, here for backwards compatibility
  99587. var disableInit = globals_1.viewerGlobals.disableInit;
  99588. exports.disableInit = disableInit;
  99589. /**
  99590. * Dispose all viewers currently registered
  99591. */
  99592. function disposeAll() {
  99593. viewerManager_1.viewerManager.dispose();
  99594. mappers_1.mapperManager.dispose();
  99595. telemetryManager_1.telemetryManager.dispose();
  99596. }
  99597. exports.disposeAll = disposeAll;
  99598. var Version = BABYLON.Engine.Version;
  99599. exports.Version = Version;
  99600. console.log("Babylon.js viewer (v" + Version + ")");
  99601. // export publicliy all configuration interfaces
  99602. __export(__webpack_require__(21));
  99603. /***/ }),
  99604. /* 7 */
  99605. /***/ (function(module, exports, __webpack_require__) {
  99606. "use strict";
  99607. Object.defineProperty(exports, "__esModule", { value: true });
  99608. var ViewerGlobals = /** @class */ (function () {
  99609. function ViewerGlobals() {
  99610. this.disableInit = false;
  99611. this.disableWebGL2Support = false;
  99612. }
  99613. return ViewerGlobals;
  99614. }());
  99615. exports.ViewerGlobals = ViewerGlobals;
  99616. exports.viewerGlobals = new ViewerGlobals();
  99617. /***/ }),
  99618. /* 8 */
  99619. /***/ (function(module, exports, __webpack_require__) {
  99620. "use strict";
  99621. Object.defineProperty(exports, "__esModule", { value: true });
  99622. var babylonjs_1 = __webpack_require__(0);
  99623. /**
  99624. * The viewer manager is the container for all viewers currently registered on this page.
  99625. * It is possible to have more than one viewer on a single page.
  99626. */
  99627. var ViewerManager = /** @class */ (function () {
  99628. function ViewerManager() {
  99629. this._viewers = {};
  99630. this.onViewerAddedObservable = new babylonjs_1.Observable();
  99631. this.onViewerRemovedObservable = new babylonjs_1.Observable();
  99632. }
  99633. /**
  99634. * Adding a new viewer to the viewer manager and start tracking it.
  99635. * @param viewer the viewer to add
  99636. */
  99637. ViewerManager.prototype.addViewer = function (viewer) {
  99638. this._viewers[viewer.getBaseId()] = viewer;
  99639. this._onViewerAdded(viewer);
  99640. };
  99641. /**
  99642. * remove a viewer from the viewer manager
  99643. * @param viewer the viewer to remove
  99644. */
  99645. ViewerManager.prototype.removeViewer = function (viewer) {
  99646. var id = viewer.getBaseId();
  99647. delete this._viewers[id];
  99648. this.onViewerRemovedObservable.notifyObservers(id);
  99649. };
  99650. /**
  99651. * Get a viewer by its baseId (if the container element has an ID, it is the this is. if not, a random id was assigned)
  99652. * @param id the id of the HTMl element (or the viewer's, if none provided)
  99653. */
  99654. ViewerManager.prototype.getViewerById = function (id) {
  99655. return this._viewers[id];
  99656. };
  99657. /**
  99658. * Get a viewer using a container element
  99659. * @param element the HTML element to search viewers associated with
  99660. */
  99661. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  99662. for (var id in this._viewers) {
  99663. if (this._viewers[id].containerElement === element) {
  99664. return this.getViewerById(id);
  99665. }
  99666. }
  99667. };
  99668. /**
  99669. * Get a promise that will fullfil when this viewer was initialized.
  99670. * Since viewer initialization and template injection is asynchronous, using the promise will guaranty that
  99671. * you will get the viewer after everything was already configured.
  99672. * @param id the viewer id to find
  99673. */
  99674. ViewerManager.prototype.getViewerPromiseById = function (id) {
  99675. var _this = this;
  99676. return new Promise(function (resolve, reject) {
  99677. var localViewer = _this.getViewerById(id);
  99678. if (localViewer) {
  99679. return resolve(localViewer);
  99680. }
  99681. var viewerFunction = function (viewer) {
  99682. if (viewer.getBaseId() === id) {
  99683. resolve(viewer);
  99684. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  99685. }
  99686. };
  99687. _this.onViewerAddedObservable.add(viewerFunction);
  99688. });
  99689. };
  99690. ViewerManager.prototype._onViewerAdded = function (viewer) {
  99691. this.onViewerAdded && this.onViewerAdded(viewer);
  99692. this.onViewerAddedObservable.notifyObservers(viewer);
  99693. };
  99694. /**
  99695. * dispose the manager and all of its associated viewers
  99696. */
  99697. ViewerManager.prototype.dispose = function () {
  99698. delete this._onViewerAdded;
  99699. for (var id in this._viewers) {
  99700. this._viewers[id].dispose();
  99701. }
  99702. this.onViewerAddedObservable.clear();
  99703. this.onViewerRemovedObservable.clear();
  99704. };
  99705. return ViewerManager;
  99706. }());
  99707. exports.ViewerManager = ViewerManager;
  99708. exports.viewerManager = new ViewerManager();
  99709. /***/ }),
  99710. /* 9 */
  99711. /***/ (function(module, exports, __webpack_require__) {
  99712. "use strict";
  99713. var __extends = (this && this.__extends) || (function () {
  99714. var extendStatics = Object.setPrototypeOf ||
  99715. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  99716. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  99717. return function (d, b) {
  99718. extendStatics(d, b);
  99719. function __() { this.constructor = d; }
  99720. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  99721. };
  99722. })();
  99723. Object.defineProperty(exports, "__esModule", { value: true });
  99724. var viewer_1 = __webpack_require__(10);
  99725. var babylonjs_1 = __webpack_require__(0);
  99726. /**
  99727. * The Default viewer is the default implementation of the AbstractViewer.
  99728. * It uses the templating system to render a new canvas and controls.
  99729. */
  99730. var DefaultViewer = /** @class */ (function (_super) {
  99731. __extends(DefaultViewer, _super);
  99732. /**
  99733. * Create a new default viewer
  99734. * @param containerElement the element in which the templates will be rendered
  99735. * @param initialConfiguration the initial configuration. Defaults to extending the default configuration
  99736. */
  99737. function DefaultViewer(containerElement, initialConfiguration) {
  99738. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  99739. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  99740. _this.containerElement = containerElement;
  99741. _this._handlePointerDown = function (event) {
  99742. var pointerDown = event.event;
  99743. if (pointerDown.button !== 0)
  99744. return;
  99745. var element = event.event.target;
  99746. if (!element) {
  99747. return;
  99748. }
  99749. var parentClasses = element.parentElement.classList;
  99750. switch (element.id) {
  99751. case "speed-button":
  99752. case "types-button":
  99753. if (parentClasses.contains("open")) {
  99754. parentClasses.remove("open");
  99755. }
  99756. else {
  99757. parentClasses.add("open");
  99758. }
  99759. break;
  99760. case "play-pause-button":
  99761. _this._togglePlayPause();
  99762. break;
  99763. case "label-option-button":
  99764. var label = element.dataset["value"];
  99765. if (label) {
  99766. _this._updateAnimationType(label);
  99767. }
  99768. break;
  99769. case "speed-option-button":
  99770. if (!_this._currentAnimation) {
  99771. return;
  99772. }
  99773. var speed = element.dataset["value"];
  99774. if (speed)
  99775. _this._updateAnimationSpeed(speed);
  99776. break;
  99777. case "progress-wrapper":
  99778. _this._resumePlay = !_this._isAnimationPaused;
  99779. if (_this._resumePlay) {
  99780. _this._togglePlayPause(true);
  99781. }
  99782. break;
  99783. case "fullscreen-button":
  99784. _this.toggleFullscreen();
  99785. default:
  99786. return;
  99787. }
  99788. };
  99789. /**
  99790. * Plays or Pauses animation
  99791. */
  99792. _this._togglePlayPause = function (noUiUpdate) {
  99793. if (!_this._currentAnimation) {
  99794. return;
  99795. }
  99796. if (_this._isAnimationPaused) {
  99797. _this._currentAnimation.restart();
  99798. }
  99799. else {
  99800. _this._currentAnimation.pause();
  99801. }
  99802. _this._isAnimationPaused = !_this._isAnimationPaused;
  99803. if (noUiUpdate)
  99804. return;
  99805. var navbar = _this.templateManager.getTemplate('navBar');
  99806. if (!navbar)
  99807. return;
  99808. navbar.updateParams({
  99809. paused: _this._isAnimationPaused,
  99810. });
  99811. };
  99812. /**
  99813. * Control progress bar position based on animation current frame
  99814. */
  99815. _this._updateProgressBar = function () {
  99816. var navbar = _this.templateManager.getTemplate('navBar');
  99817. if (!navbar)
  99818. return;
  99819. var progressSlider = navbar.parent.querySelector("input#progress-wrapper");
  99820. if (progressSlider && _this._currentAnimation) {
  99821. var progress = _this._currentAnimation.currentFrame / _this._currentAnimation.frames * 100;
  99822. var currentValue = progressSlider.valueAsNumber;
  99823. if (Math.abs(currentValue - progress) > 0.5) { // Only move if greater than a 1% change
  99824. progressSlider.value = '' + progress;
  99825. }
  99826. if (_this._currentAnimation.state === 1 /* PLAYING */) {
  99827. if (_this.sceneManager.camera.autoRotationBehavior && !_this._oldIdleRotationValue) {
  99828. _this._oldIdleRotationValue = _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed;
  99829. _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = 0;
  99830. }
  99831. }
  99832. else {
  99833. if (_this.sceneManager.camera.autoRotationBehavior && _this._oldIdleRotationValue) {
  99834. _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = _this._oldIdleRotationValue;
  99835. _this._oldIdleRotationValue = 0;
  99836. }
  99837. }
  99838. }
  99839. };
  99840. /**
  99841. * Update Current Animation Speed
  99842. */
  99843. _this._updateAnimationSpeed = function (speed, paramsObject) {
  99844. var navbar = _this.templateManager.getTemplate('navBar');
  99845. if (!navbar)
  99846. return;
  99847. if (speed && _this._currentAnimation) {
  99848. _this._currentAnimation.speedRatio = parseFloat(speed);
  99849. if (!_this._isAnimationPaused) {
  99850. _this._currentAnimation.restart();
  99851. }
  99852. if (paramsObject) {
  99853. paramsObject.selectedSpeed = speed + "x";
  99854. }
  99855. else {
  99856. navbar.updateParams({
  99857. selectedSpeed: speed + "x",
  99858. });
  99859. }
  99860. }
  99861. };
  99862. /**
  99863. * Update Current Animation Type
  99864. */
  99865. _this._updateAnimationType = function (label, paramsObject) {
  99866. var navbar = _this.templateManager.getTemplate('navBar');
  99867. if (!navbar)
  99868. return;
  99869. if (label) {
  99870. _this._currentAnimation = _this.sceneManager.models[0].setCurrentAnimationByName(label);
  99871. }
  99872. if (paramsObject) {
  99873. paramsObject.selectedAnimation = (_this._animationList.indexOf(label) + 1);
  99874. paramsObject.selectedAnimationName = label;
  99875. }
  99876. else {
  99877. navbar.updateParams({
  99878. selectedAnimation: (_this._animationList.indexOf(label) + 1),
  99879. selectedAnimationName: label
  99880. });
  99881. }
  99882. _this._updateAnimationSpeed("1.0", paramsObject);
  99883. };
  99884. /**
  99885. * Toggle fullscreen of the entire viewer
  99886. */
  99887. _this.toggleFullscreen = function () {
  99888. var viewerTemplate = _this.templateManager.getTemplate('viewer');
  99889. var viewerElement = viewerTemplate && viewerTemplate.parent;
  99890. if (viewerElement) {
  99891. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  99892. if (!fullscreenElement) {
  99893. var requestFullScreen = viewerElement.requestFullscreen || viewerElement.webkitRequestFullscreen || viewerElement.msRequestFullscreen || viewerElement.mozRequestFullScreen;
  99894. requestFullScreen.call(viewerElement);
  99895. }
  99896. else {
  99897. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  99898. exitFullscreen.call(document);
  99899. }
  99900. }
  99901. };
  99902. _this._onModelLoaded = function (model) {
  99903. _this._configureTemplate(model);
  99904. // with a short timeout, making sure everything is there already.
  99905. var hideLoadingDelay = 20;
  99906. if (_this._configuration.lab && _this._configuration.lab.hideLoadingDelay !== undefined) {
  99907. hideLoadingDelay = _this._configuration.lab.hideLoadingDelay;
  99908. }
  99909. setTimeout(function () {
  99910. _this.sceneManager.scene.executeWhenReady(function () {
  99911. _this.hideLoadingScreen();
  99912. });
  99913. }, hideLoadingDelay);
  99914. return;
  99915. };
  99916. _this.onModelLoadedObservable.add(_this._onModelLoaded);
  99917. _this.sceneManager.onLightsConfiguredObservable.add(function (data) {
  99918. _this._configureLights(data.newConfiguration, data.model);
  99919. });
  99920. return _this;
  99921. }
  99922. /**
  99923. * This will be executed when the templates initialize.
  99924. */
  99925. DefaultViewer.prototype._onTemplatesLoaded = function () {
  99926. var _this = this;
  99927. this.showLoadingScreen();
  99928. // navbar
  99929. this._initNavbar();
  99930. // close overlay button
  99931. var closeButton = document.getElementById('close-button');
  99932. if (closeButton) {
  99933. closeButton.addEventListener('pointerdown', function () {
  99934. _this.hideOverlayScreen();
  99935. });
  99936. }
  99937. if (this.configuration.templates && this.configuration.templates.viewer) {
  99938. if (this.configuration.templates.viewer.params && this.configuration.templates.viewer.params.enableDragAndDrop) {
  99939. var filesInput = new babylonjs_1.FilesInput(this.engine, this.sceneManager.scene, function () {
  99940. }, function () {
  99941. }, function () {
  99942. }, function () {
  99943. }, function () {
  99944. }, function (file) {
  99945. _this.loadModel(file);
  99946. }, function () {
  99947. });
  99948. filesInput.monitorElementForDragNDrop(this.templateManager.getCanvas());
  99949. }
  99950. }
  99951. return _super.prototype._onTemplatesLoaded.call(this);
  99952. };
  99953. DefaultViewer.prototype._dropped = function (evt) {
  99954. };
  99955. DefaultViewer.prototype._initNavbar = function () {
  99956. var _this = this;
  99957. var navbar = this.templateManager.getTemplate('navBar');
  99958. if (navbar) {
  99959. this.onFrameRenderedObservable.add(this._updateProgressBar);
  99960. this.templateManager.eventManager.registerCallback('navBar', this._handlePointerDown, 'pointerdown');
  99961. // an example how to trigger the help button. publiclly available
  99962. this.templateManager.eventManager.registerCallback("navBar", function () {
  99963. // do your thing
  99964. }, "pointerdown", "#help-button");
  99965. this.templateManager.eventManager.registerCallback("navBar", function (event) {
  99966. var evt = event.event;
  99967. var element = (evt.target);
  99968. if (!_this._currentAnimation)
  99969. return;
  99970. var gotoFrame = +element.value / 100 * _this._currentAnimation.frames;
  99971. if (isNaN(gotoFrame))
  99972. return;
  99973. _this._currentAnimation.goToFrame(gotoFrame);
  99974. }, "input");
  99975. this.templateManager.eventManager.registerCallback("navBar", function (e) {
  99976. if (_this._resumePlay) {
  99977. _this._togglePlayPause(true);
  99978. }
  99979. _this._resumePlay = false;
  99980. }, "pointerup", "#progress-wrapper");
  99981. }
  99982. };
  99983. /**
  99984. * Preparing the container element to present the viewer
  99985. */
  99986. DefaultViewer.prototype._prepareContainerElement = function () {
  99987. this.containerElement.style.position = 'relative';
  99988. this.containerElement.style.height = '100%';
  99989. this.containerElement.style.display = 'flex';
  99990. };
  99991. /**
  99992. * This function will configure the templates and update them after a model was loaded
  99993. * It is mainly responsible to changing the title and subtitle etc'.
  99994. * @param model the model to be used to configure the templates by
  99995. */
  99996. DefaultViewer.prototype._configureTemplate = function (model) {
  99997. var navbar = this.templateManager.getTemplate('navBar');
  99998. if (!navbar)
  99999. return;
  100000. var newParams = {};
  100001. var animationNames = model.getAnimationNames();
  100002. if (animationNames.length >= 1) {
  100003. this._isAnimationPaused = (model.configuration.animation && !model.configuration.animation.autoStart) || !model.configuration.animation;
  100004. this._animationList = animationNames;
  100005. newParams.animations = this._animationList;
  100006. newParams.paused = this._isAnimationPaused;
  100007. var animationIndex = 0;
  100008. if (model.configuration.animation && typeof model.configuration.animation.autoStart === 'string') {
  100009. animationIndex = animationNames.indexOf(model.configuration.animation.autoStart);
  100010. if (animationIndex === -1) {
  100011. animationIndex = 0;
  100012. }
  100013. }
  100014. this._updateAnimationType(animationNames[animationIndex], newParams);
  100015. }
  100016. if (model.configuration.thumbnail) {
  100017. newParams.logoImage = model.configuration.thumbnail;
  100018. }
  100019. navbar.updateParams(newParams);
  100020. };
  100021. /**
  100022. * This will load a new model to the default viewer
  100023. * overriding the AbstractViewer's loadModel.
  100024. * The scene will automatically be cleared of the old models, if exist.
  100025. * @param model the configuration object (or URL) to load.
  100026. */
  100027. DefaultViewer.prototype.loadModel = function (model) {
  100028. var _this = this;
  100029. if (!model) {
  100030. model = this.configuration.model;
  100031. }
  100032. this.showLoadingScreen();
  100033. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  100034. console.log(error);
  100035. _this.hideLoadingScreen();
  100036. _this.showOverlayScreen('error');
  100037. return Promise.reject(error);
  100038. });
  100039. };
  100040. /**
  100041. * Show the overlay and the defined sub-screen.
  100042. * Mainly used for help and errors
  100043. * @param subScreen the name of the subScreen. Those can be defined in the configuration object
  100044. */
  100045. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  100046. var _this = this;
  100047. var template = this.templateManager.getTemplate('overlay');
  100048. if (!template)
  100049. return Promise.resolve('Overlay template not found');
  100050. return template.show((function (template) {
  100051. var canvasRect = _this.containerElement.getBoundingClientRect();
  100052. template.parent.style.display = 'flex';
  100053. template.parent.style.width = canvasRect.width + "px";
  100054. template.parent.style.height = canvasRect.height + "px";
  100055. template.parent.style.opacity = "1";
  100056. var subTemplate = _this.templateManager.getTemplate(subScreen);
  100057. if (!subTemplate) {
  100058. return Promise.reject(subScreen + ' template not found');
  100059. }
  100060. return subTemplate.show((function (template) {
  100061. template.parent.style.display = 'flex';
  100062. return Promise.resolve(template);
  100063. }));
  100064. }));
  100065. };
  100066. /**
  100067. * Hide the overlay screen.
  100068. */
  100069. DefaultViewer.prototype.hideOverlayScreen = function () {
  100070. var template = this.templateManager.getTemplate('overlay');
  100071. if (!template)
  100072. return Promise.resolve('Overlay template not found');
  100073. return template.hide((function (template) {
  100074. template.parent.style.opacity = "0";
  100075. var onTransitionEnd = function () {
  100076. template.parent.removeEventListener("transitionend", onTransitionEnd);
  100077. template.parent.style.display = 'none';
  100078. };
  100079. template.parent.addEventListener("transitionend", onTransitionEnd);
  100080. var overlays = template.parent.querySelectorAll('.overlay');
  100081. if (overlays) {
  100082. for (var i = 0; i < overlays.length; ++i) {
  100083. var htmlElement = overlays.item(i);
  100084. htmlElement.style.display = 'none';
  100085. }
  100086. }
  100087. return Promise.resolve(template);
  100088. }));
  100089. };
  100090. /**
  100091. * show the viewer (in case it was hidden)
  100092. *
  100093. * @param visibilityFunction an optional function to execute in order to show the container
  100094. */
  100095. DefaultViewer.prototype.show = function (visibilityFunction) {
  100096. var template = this.templateManager.getTemplate('main');
  100097. //not possible, but yet:
  100098. if (!template)
  100099. return Promise.reject('Main template not found');
  100100. return template.show(visibilityFunction);
  100101. };
  100102. /**
  100103. * hide the viewer (in case it is visible)
  100104. *
  100105. * @param visibilityFunction an optional function to execute in order to hide the container
  100106. */
  100107. DefaultViewer.prototype.hide = function (visibilityFunction) {
  100108. var template = this.templateManager.getTemplate('main');
  100109. //not possible, but yet:
  100110. if (!template)
  100111. return Promise.reject('Main template not found');
  100112. return template.hide(visibilityFunction);
  100113. };
  100114. /**
  100115. * Show the loading screen.
  100116. * The loading screen can be configured using the configuration object
  100117. */
  100118. DefaultViewer.prototype.showLoadingScreen = function () {
  100119. var _this = this;
  100120. var template = this.templateManager.getTemplate('loadingScreen');
  100121. if (!template)
  100122. return Promise.resolve('Loading Screen template not found');
  100123. return template.show((function (template) {
  100124. var canvasRect = _this.containerElement.getBoundingClientRect();
  100125. // var canvasPositioning = window.getComputedStyle(this.containerElement).position;
  100126. template.parent.style.display = 'flex';
  100127. template.parent.style.width = canvasRect.width + "px";
  100128. template.parent.style.height = canvasRect.height + "px";
  100129. template.parent.style.opacity = "1";
  100130. // from the configuration!!!
  100131. var color = "black";
  100132. if (_this.configuration.templates && _this.configuration.templates.loadingScreen) {
  100133. color = (_this.configuration.templates.loadingScreen.params &&
  100134. _this.configuration.templates.loadingScreen.params.backgroundColor) || color;
  100135. }
  100136. template.parent.style.backgroundColor = color;
  100137. return Promise.resolve(template);
  100138. }));
  100139. };
  100140. /**
  100141. * Hide the loading screen
  100142. */
  100143. DefaultViewer.prototype.hideLoadingScreen = function () {
  100144. var template = this.templateManager.getTemplate('loadingScreen');
  100145. if (!template)
  100146. return Promise.resolve('Loading Screen template not found');
  100147. return template.hide((function (template) {
  100148. template.parent.style.opacity = "0";
  100149. var onTransitionEnd = function () {
  100150. template.parent.removeEventListener("transitionend", onTransitionEnd);
  100151. template.parent.style.display = 'none';
  100152. };
  100153. template.parent.addEventListener("transitionend", onTransitionEnd);
  100154. return Promise.resolve(template);
  100155. }));
  100156. };
  100157. /**
  100158. * An extension of the light configuration of the abstract viewer.
  100159. * @param lightsConfiguration the light configuration to use
  100160. * @param model the model that will be used to configure the lights (if the lights are model-dependant)
  100161. */
  100162. DefaultViewer.prototype._configureLights = function (lightsConfiguration, model) {
  100163. var _this = this;
  100164. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  100165. // labs feature - flashlight
  100166. if (this._configuration.lab && this._configuration.lab.flashlight) {
  100167. var pointerPosition = babylonjs_1.Vector3.Zero();
  100168. var lightTarget_1;
  100169. var angle = 0.5;
  100170. var exponent = Math.PI / 2;
  100171. if (typeof this._configuration.lab.flashlight === "object") {
  100172. exponent = this._configuration.lab.flashlight.exponent || exponent;
  100173. angle = this._configuration.lab.flashlight.angle || angle;
  100174. }
  100175. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.sceneManager.scene);
  100176. if (typeof this._configuration.lab.flashlight === "object") {
  100177. flashlight.intensity = this._configuration.lab.flashlight.intensity || flashlight.intensity;
  100178. if (this._configuration.lab.flashlight.diffuse) {
  100179. flashlight.diffuse.r = this._configuration.lab.flashlight.diffuse.r;
  100180. flashlight.diffuse.g = this._configuration.lab.flashlight.diffuse.g;
  100181. flashlight.diffuse.b = this._configuration.lab.flashlight.diffuse.b;
  100182. }
  100183. if (this._configuration.lab.flashlight.specular) {
  100184. flashlight.specular.r = this._configuration.lab.flashlight.specular.r;
  100185. flashlight.specular.g = this._configuration.lab.flashlight.specular.g;
  100186. flashlight.specular.b = this._configuration.lab.flashlight.specular.b;
  100187. }
  100188. }
  100189. this.sceneManager.scene.constantlyUpdateMeshUnderPointer = true;
  100190. this.sceneManager.scene.onPointerObservable.add(function (eventData, eventState) {
  100191. if (eventData.type === 4 && eventData.pickInfo) {
  100192. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  100193. }
  100194. else {
  100195. lightTarget_1 = undefined;
  100196. }
  100197. });
  100198. var updateFlashlightFunction = function () {
  100199. if (_this.sceneManager.camera && flashlight) {
  100200. flashlight.position.copyFrom(_this.sceneManager.camera.position);
  100201. if (lightTarget_1) {
  100202. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  100203. }
  100204. }
  100205. };
  100206. this.sceneManager.scene.registerBeforeRender(updateFlashlightFunction);
  100207. this._registeredOnBeforeRenderFunctions.push(updateFlashlightFunction);
  100208. }
  100209. };
  100210. return DefaultViewer;
  100211. }(viewer_1.AbstractViewer));
  100212. exports.DefaultViewer = DefaultViewer;
  100213. /***/ }),
  100214. /* 10 */
  100215. /***/ (function(module, exports, __webpack_require__) {
  100216. "use strict";
  100217. Object.defineProperty(exports, "__esModule", { value: true });
  100218. var viewerManager_1 = __webpack_require__(8);
  100219. var sceneManager_1 = __webpack_require__(29);
  100220. var templateManager_1 = __webpack_require__(35);
  100221. var loader_1 = __webpack_require__(38);
  100222. var babylonjs_1 = __webpack_require__(0);
  100223. var deepmerge = __webpack_require__(1);
  100224. var modelLoader_1 = __webpack_require__(22);
  100225. var globals_1 = __webpack_require__(7);
  100226. var telemetryManager_1 = __webpack_require__(5);
  100227. /**
  100228. * The AbstractViewr is the center of Babylon's viewer.
  100229. * It is the basic implementation of the default viewer and is responsible of loading and showing the model and the templates
  100230. */
  100231. var AbstractViewer = /** @class */ (function () {
  100232. function AbstractViewer(containerElement, initialConfiguration) {
  100233. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  100234. var _this = this;
  100235. this.containerElement = containerElement;
  100236. /**
  100237. * A flag that controls whether or not the render loop should be executed
  100238. */
  100239. this.runRenderLoop = true;
  100240. /**
  100241. * is this viewer disposed?
  100242. */
  100243. this._isDisposed = false;
  100244. /**
  100245. * The resize function that will be registered with the window object
  100246. */
  100247. this._resize = function () {
  100248. // Only resize if Canvas is in the DOM
  100249. if (!_this.isCanvasInDOM()) {
  100250. return;
  100251. }
  100252. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  100253. return;
  100254. }
  100255. if (_this._configuration.engine && _this._configuration.engine.disableResize) {
  100256. return;
  100257. }
  100258. _this.engine.resize();
  100259. };
  100260. /**
  100261. * render loop that will be executed by the engine
  100262. */
  100263. this._render = function (force) {
  100264. if (force === void 0) { force = false; }
  100265. if (force || (_this.sceneManager.scene && _this.sceneManager.scene.activeCamera)) {
  100266. if (_this.runRenderLoop || force) {
  100267. _this.engine.performanceMonitor.enable();
  100268. _this.sceneManager.scene.render();
  100269. _this.onFrameRenderedObservable.notifyObservers(_this);
  100270. }
  100271. else {
  100272. _this.engine.performanceMonitor.disable();
  100273. // update camera instead of rendering
  100274. _this.sceneManager.scene.activeCamera && _this.sceneManager.scene.activeCamera.update();
  100275. }
  100276. }
  100277. };
  100278. // if exists, use the container id. otherwise, generate a random string.
  100279. if (containerElement.id) {
  100280. this.baseId = containerElement.id;
  100281. }
  100282. else {
  100283. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  100284. }
  100285. this.onSceneInitObservable = new babylonjs_1.Observable();
  100286. this.onEngineInitObservable = new babylonjs_1.Observable();
  100287. this.onModelLoadedObservable = new babylonjs_1.Observable();
  100288. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  100289. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  100290. this.onModelAddedObservable = new babylonjs_1.Observable();
  100291. this.onModelRemovedObservable = new babylonjs_1.Observable();
  100292. this.onInitDoneObservable = new babylonjs_1.Observable();
  100293. this.onLoaderInitObservable = new babylonjs_1.Observable();
  100294. this.onFrameRenderedObservable = new babylonjs_1.Observable();
  100295. this._registeredOnBeforeRenderFunctions = [];
  100296. this.modelLoader = new modelLoader_1.ModelLoader(this);
  100297. // add this viewer to the viewer manager
  100298. viewerManager_1.viewerManager.addViewer(this);
  100299. // create a new template manager for this viewer
  100300. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  100301. this.sceneManager = new sceneManager_1.SceneManager(this);
  100302. this._prepareContainerElement();
  100303. babylonjs_1.RenderingManager.AUTOCLEAR = false;
  100304. // extend the configuration
  100305. this._configurationLoader = new loader_1.ConfigurationLoader();
  100306. this._configurationLoader.loadConfiguration(initialConfiguration, function (configuration) {
  100307. _this._configuration = deepmerge(_this._configuration || {}, configuration);
  100308. if (_this._configuration.observers) {
  100309. _this._configureObservers(_this._configuration.observers);
  100310. }
  100311. // TODO remove this after testing, as this is done in the updateCOnfiguration as well.
  100312. if (_this._configuration.loaderPlugins) {
  100313. Object.keys(_this._configuration.loaderPlugins).forEach((function (name) {
  100314. if (_this._configuration.loaderPlugins && _this._configuration.loaderPlugins[name]) {
  100315. _this.modelLoader.addPlugin(name);
  100316. }
  100317. }));
  100318. }
  100319. // initialize the templates
  100320. var templateConfiguration = _this._configuration.templates || {};
  100321. _this.templateManager.initTemplate(templateConfiguration);
  100322. // when done, execute onTemplatesLoaded()
  100323. _this.templateManager.onAllLoaded.add(function () {
  100324. var canvas = _this.templateManager.getCanvas();
  100325. if (canvas) {
  100326. _this._canvas = canvas;
  100327. }
  100328. _this._onTemplateLoaded();
  100329. });
  100330. });
  100331. this.onModelLoadedObservable.add(function (model) {
  100332. //this.updateConfiguration(this._configuration, model);
  100333. });
  100334. this.onSceneInitObservable.add(function () {
  100335. _this.updateConfiguration();
  100336. });
  100337. this.onInitDoneObservable.add(function () {
  100338. _this._isInit = true;
  100339. _this.engine.runRenderLoop(_this._render);
  100340. });
  100341. }
  100342. Object.defineProperty(AbstractViewer.prototype, "canvas", {
  100343. /**
  100344. * The (single) canvas of this viewer
  100345. */
  100346. get: function () {
  100347. return this._canvas;
  100348. },
  100349. enumerable: true,
  100350. configurable: true
  100351. });
  100352. /**
  100353. * get the baseId of this viewer
  100354. */
  100355. AbstractViewer.prototype.getBaseId = function () {
  100356. return this.baseId;
  100357. };
  100358. /**
  100359. * Do we have a canvas to render on, and is it a part of the scene
  100360. */
  100361. AbstractViewer.prototype.isCanvasInDOM = function () {
  100362. return !!this._canvas && !!this._canvas.parentElement;
  100363. };
  100364. Object.defineProperty(AbstractViewer.prototype, "renderInBackground", {
  100365. /**
  100366. * Is the engine currently set to rende even when the page is in background
  100367. */
  100368. get: function () {
  100369. return this.engine && this.engine.renderEvenInBackground;
  100370. },
  100371. /**
  100372. * Set the viewer's background rendering flag.
  100373. */
  100374. set: function (value) {
  100375. if (this.engine) {
  100376. this.engine.renderEvenInBackground = value;
  100377. }
  100378. },
  100379. enumerable: true,
  100380. configurable: true
  100381. });
  100382. Object.defineProperty(AbstractViewer.prototype, "configuration", {
  100383. /**
  100384. * Get the configuration object. This is a reference only.
  100385. * The configuration can ONLY be updated using the updateConfiguration function.
  100386. * changing this object will have no direct effect on the scene.
  100387. */
  100388. get: function () {
  100389. return this._configuration;
  100390. },
  100391. enumerable: true,
  100392. configurable: true
  100393. });
  100394. /**
  100395. * force resizing the engine.
  100396. */
  100397. AbstractViewer.prototype.forceResize = function () {
  100398. this._resize();
  100399. };
  100400. /**
  100401. * Force a single render loop execution.
  100402. */
  100403. AbstractViewer.prototype.forceRender = function () {
  100404. this._render(true);
  100405. };
  100406. /**
  100407. * Takes a screenshot of the scene and returns it as a base64 encoded png.
  100408. * @param callback optional callback that will be triggered when screenshot is done.
  100409. * @param width Optional screenshot width (default to 512).
  100410. * @param height Optional screenshot height (default to 512).
  100411. * @returns a promise with the screenshot data
  100412. */
  100413. AbstractViewer.prototype.takeScreenshot = function (callback, width, height) {
  100414. var _this = this;
  100415. if (width === void 0) { width = 0; }
  100416. if (height === void 0) { height = 0; }
  100417. width = width || this.canvas.clientWidth;
  100418. height = height || this.canvas.clientHeight;
  100419. // Create the screenshot
  100420. return new Promise(function (resolve, reject) {
  100421. try {
  100422. BABYLON.Tools.CreateScreenshot(_this.engine, _this.sceneManager.camera, { width: width, height: height }, function (data) {
  100423. if (callback) {
  100424. callback(data);
  100425. }
  100426. resolve(data);
  100427. });
  100428. }
  100429. catch (e) {
  100430. reject(e);
  100431. }
  100432. });
  100433. };
  100434. /**
  100435. * Update the current viewer configuration with new values.
  100436. * Only provided information will be updated, old configuration values will be kept.
  100437. * If this.configuration was manually changed, you can trigger this function with no parameters,
  100438. * and the entire configuration will be updated.
  100439. * @param newConfiguration the partial configuration to update
  100440. *
  100441. */
  100442. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  100443. var _this = this;
  100444. if (newConfiguration === void 0) { newConfiguration = this._configuration; }
  100445. // update this.configuration with the new data
  100446. this._configuration = deepmerge(this._configuration || {}, newConfiguration);
  100447. this.sceneManager.updateConfiguration(newConfiguration, this._configuration);
  100448. // observers in configuration
  100449. if (newConfiguration.observers) {
  100450. this._configureObservers(newConfiguration.observers);
  100451. }
  100452. if (newConfiguration.loaderPlugins) {
  100453. Object.keys(newConfiguration.loaderPlugins).forEach((function (name) {
  100454. if (newConfiguration.loaderPlugins && newConfiguration.loaderPlugins[name]) {
  100455. _this.modelLoader.addPlugin(name);
  100456. }
  100457. }));
  100458. }
  100459. };
  100460. /**
  100461. * this is used to register native functions using the configuration object.
  100462. * This will configure the observers.
  100463. * @param observersConfiguration observers configuration
  100464. */
  100465. AbstractViewer.prototype._configureObservers = function (observersConfiguration) {
  100466. if (observersConfiguration.onEngineInit) {
  100467. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  100468. }
  100469. else {
  100470. if (observersConfiguration.onEngineInit === '' && this._configuration.observers && this._configuration.observers.onEngineInit) {
  100471. this.onEngineInitObservable.removeCallback(window[this._configuration.observers.onEngineInit]);
  100472. }
  100473. }
  100474. if (observersConfiguration.onSceneInit) {
  100475. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  100476. }
  100477. else {
  100478. if (observersConfiguration.onSceneInit === '' && this._configuration.observers && this._configuration.observers.onSceneInit) {
  100479. this.onSceneInitObservable.removeCallback(window[this._configuration.observers.onSceneInit]);
  100480. }
  100481. }
  100482. if (observersConfiguration.onModelLoaded) {
  100483. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  100484. }
  100485. else {
  100486. if (observersConfiguration.onModelLoaded === '' && this._configuration.observers && this._configuration.observers.onModelLoaded) {
  100487. this.onModelLoadedObservable.removeCallback(window[this._configuration.observers.onModelLoaded]);
  100488. }
  100489. }
  100490. };
  100491. /**
  100492. * Dispoe the entire viewer including the scene and the engine
  100493. */
  100494. AbstractViewer.prototype.dispose = function () {
  100495. if (this._isDisposed) {
  100496. return;
  100497. }
  100498. window.removeEventListener('resize', this._resize);
  100499. //observers
  100500. this.onEngineInitObservable.clear();
  100501. this.onInitDoneObservable.clear();
  100502. this.onLoaderInitObservable.clear();
  100503. this.onModelLoadedObservable.clear();
  100504. this.onModelLoadErrorObservable.clear();
  100505. this.onModelLoadProgressObservable.clear();
  100506. this.onSceneInitObservable.clear();
  100507. this.onFrameRenderedObservable.clear();
  100508. this.onModelAddedObservable.clear();
  100509. this.onModelRemovedObservable.clear();
  100510. if (this.sceneManager.scene && this.sceneManager.scene.activeCamera) {
  100511. this.sceneManager.scene.activeCamera.detachControl(this.canvas);
  100512. }
  100513. this._fpsTimeoutInterval && clearInterval(this._fpsTimeoutInterval);
  100514. this.sceneManager.dispose();
  100515. this.modelLoader.dispose();
  100516. if (this.engine) {
  100517. this.engine.dispose();
  100518. }
  100519. this.templateManager.dispose();
  100520. viewerManager_1.viewerManager.removeViewer(this);
  100521. this._isDisposed = true;
  100522. };
  100523. /**
  100524. * This function will execute when the HTML templates finished initializing.
  100525. * It should initialize the engine and continue execution.
  100526. *
  100527. * @returns {Promise<AbstractViewer>} The viewer object will be returned after the object was loaded.
  100528. */
  100529. AbstractViewer.prototype._onTemplatesLoaded = function () {
  100530. return Promise.resolve(this);
  100531. };
  100532. /**
  100533. * This will force the creation of an engine and a scene.
  100534. * It will also load a model if preconfigured.
  100535. * But first - it will load the extendible onTemplateLoaded()!
  100536. */
  100537. AbstractViewer.prototype._onTemplateLoaded = function () {
  100538. var _this = this;
  100539. // check if viewer was disposed right after created
  100540. if (this._isDisposed) {
  100541. return Promise.reject("viewer was disposed");
  100542. }
  100543. return this._onTemplatesLoaded().then(function () {
  100544. var autoLoad = typeof _this._configuration.model === 'string' || (_this._configuration.model && _this._configuration.model.url);
  100545. return _this._initEngine().then(function (engine) {
  100546. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  100547. }).then(function () {
  100548. _this._initTelemetryEvents();
  100549. if (autoLoad) {
  100550. return _this.loadModel(_this._configuration.model).catch(function (e) { }).then(function () { return _this.sceneManager.scene; });
  100551. }
  100552. else {
  100553. return _this.sceneManager.scene || _this.sceneManager.initScene(_this._configuration.scene);
  100554. }
  100555. }).then(function () {
  100556. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  100557. }).catch(function (e) {
  100558. babylonjs_1.Tools.Warn(e.toString());
  100559. return _this;
  100560. });
  100561. });
  100562. };
  100563. /**
  100564. * Initialize the engine. Retruns a promise in case async calls are needed.
  100565. *
  100566. * @protected
  100567. * @returns {Promise<Engine>}
  100568. * @memberof Viewer
  100569. */
  100570. AbstractViewer.prototype._initEngine = function () {
  100571. // init custom shaders
  100572. this._injectCustomShaders();
  100573. var canvasElement = this.templateManager.getCanvas();
  100574. if (!canvasElement) {
  100575. return Promise.reject('Canvas element not found!');
  100576. }
  100577. var config = this._configuration.engine || {};
  100578. // TDO enable further configuration
  100579. // check for webgl2 support, force-disable if needed.
  100580. if (globals_1.viewerGlobals.disableWebGL2Support) {
  100581. config.engineOptions = config.engineOptions || {};
  100582. config.engineOptions.disableWebGL2Support = true;
  100583. }
  100584. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  100585. // Disable manifest checking
  100586. babylonjs_1.Database.IDBStorageEnabled = false;
  100587. if (!config.disableResize) {
  100588. window.addEventListener('resize', this._resize);
  100589. }
  100590. if (this._configuration.engine && this._configuration.engine.adaptiveQuality) {
  100591. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  100592. this.engine.setHardwareScalingLevel(scale);
  100593. }
  100594. return Promise.resolve(this.engine);
  100595. };
  100596. /**
  100597. * Initialize a model loading. The returned object (a ViewerModel object) will be loaded in the background.
  100598. * The difference between this and loadModel is that loadModel will fulfill the promise when the model finished loading.
  100599. *
  100600. * @param modelConfig model configuration to use when loading the model.
  100601. * @param clearScene should the scene be cleared before loading this model
  100602. * @returns a ViewerModel object that is not yet fully loaded.
  100603. */
  100604. AbstractViewer.prototype.initModel = function (modelConfig, clearScene) {
  100605. var _this = this;
  100606. if (clearScene === void 0) { clearScene = true; }
  100607. var configuration;
  100608. if (typeof modelConfig === 'string') {
  100609. configuration = {
  100610. url: modelConfig
  100611. };
  100612. }
  100613. else if (modelConfig instanceof File) {
  100614. configuration = {
  100615. file: modelConfig,
  100616. root: "file:"
  100617. };
  100618. }
  100619. else {
  100620. configuration = modelConfig;
  100621. }
  100622. if (!configuration.url && !configuration.file) {
  100623. throw new Error("no model provided");
  100624. }
  100625. if (clearScene) {
  100626. this.sceneManager.clearScene(true, false);
  100627. }
  100628. //merge the configuration for future models:
  100629. if (this._configuration.model && typeof this._configuration.model === 'object') {
  100630. var globalConfig = deepmerge({}, this._configuration.model);
  100631. configuration = deepmerge(globalConfig, configuration);
  100632. if (modelConfig instanceof File) {
  100633. configuration.file = modelConfig;
  100634. }
  100635. }
  100636. else {
  100637. this._configuration.model = configuration;
  100638. }
  100639. this._isLoading = true;
  100640. var model = this.modelLoader.load(configuration);
  100641. this.lastUsedLoader = model.loader;
  100642. model.onLoadErrorObservable.add(function (errorObject) {
  100643. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject);
  100644. });
  100645. model.onLoadProgressObservable.add(function (progressEvent) {
  100646. _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  100647. });
  100648. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  100649. model.onLoadedObservable.add(function () {
  100650. _this._isLoading = false;
  100651. });
  100652. return model;
  100653. };
  100654. /**
  100655. * load a model using the provided configuration.
  100656. * This function, as opposed to initModel, will return a promise that resolves when the model is loaded, and rejects with error.
  100657. * If you want to attach to the observables of the model, use initModle instead.
  100658. *
  100659. * @param modelConfig the model configuration or URL to load.
  100660. * @param clearScene Should the scene be cleared before loading the model
  100661. * @returns a Promise the fulfills when the model finished loading successfully.
  100662. */
  100663. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  100664. var _this = this;
  100665. if (clearScene === void 0) { clearScene = true; }
  100666. if (this._isLoading) {
  100667. // We can decide here whether or not to cancel the lst load, but the developer can do that.
  100668. return Promise.reject("another model is curently being loaded.");
  100669. }
  100670. return Promise.resolve(this.sceneManager.scene).then(function (scene) {
  100671. if (!scene)
  100672. return _this.sceneManager.initScene(_this._configuration.scene, _this._configuration.optimizer);
  100673. return scene;
  100674. }).then(function () {
  100675. var model = _this.initModel(modelConfig, clearScene);
  100676. return new Promise(function (resolve, reject) {
  100677. // at this point, configuration.model is an object, not a string
  100678. model.onLoadedObservable.add(function () {
  100679. resolve(model);
  100680. });
  100681. model.onLoadErrorObservable.add(function (error) {
  100682. reject(error);
  100683. });
  100684. });
  100685. });
  100686. };
  100687. AbstractViewer.prototype._initTelemetryEvents = function () {
  100688. var _this = this;
  100689. telemetryManager_1.telemetryManager.broadcast("Engine Capabilities", this, this.engine.getCaps());
  100690. telemetryManager_1.telemetryManager.broadcast("Platform Details", this, {
  100691. userAgent: navigator.userAgent,
  100692. platform: navigator.platform
  100693. });
  100694. telemetryManager_1.telemetryManager.flushWebGLErrors(this);
  100695. var trackFPS = function () {
  100696. telemetryManager_1.telemetryManager.broadcast("Current FPS", _this, { fps: _this.engine.getFps() });
  100697. };
  100698. trackFPS();
  100699. // Track the FPS again after 60 seconds
  100700. this._fpsTimeoutInterval = window.setInterval(trackFPS, 60 * 1000);
  100701. };
  100702. /**
  100703. * Injects all the spectre shader in the babylon shader store
  100704. */
  100705. AbstractViewer.prototype._injectCustomShaders = function () {
  100706. var customShaders = this._configuration.customShaders;
  100707. // Inject all the spectre shader in the babylon shader store.
  100708. if (!customShaders) {
  100709. return;
  100710. }
  100711. if (customShaders.shaders) {
  100712. Object.keys(customShaders.shaders).forEach(function (key) {
  100713. // typescript considers a callback "unsafe", so... '!'
  100714. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  100715. });
  100716. }
  100717. if (customShaders.includes) {
  100718. Object.keys(customShaders.includes).forEach(function (key) {
  100719. // typescript considers a callback "unsafe", so... '!'
  100720. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  100721. });
  100722. }
  100723. };
  100724. return AbstractViewer;
  100725. }());
  100726. exports.AbstractViewer = AbstractViewer;
  100727. /***/ }),
  100728. /* 11 */
  100729. /***/ (function(module, exports, __webpack_require__) {
  100730. "use strict";
  100731. Object.defineProperty(exports, "__esModule", { value: true });
  100732. function getConfigurationKey(key, configObject) {
  100733. var splits = key.split('.');
  100734. if (splits.length === 0 || !configObject)
  100735. return;
  100736. else if (splits.length === 1) {
  100737. if (configObject[key] !== undefined) {
  100738. return configObject[key];
  100739. }
  100740. }
  100741. else {
  100742. var firstKey = splits.shift();
  100743. return getConfigurationKey(splits.join("."), configObject[firstKey]);
  100744. }
  100745. }
  100746. exports.getConfigurationKey = getConfigurationKey;
  100747. /***/ }),
  100748. /* 12 */
  100749. /***/ (function(module, exports, __webpack_require__) {
  100750. "use strict";
  100751. Object.defineProperty(exports, "__esModule", { value: true });
  100752. /**
  100753. * WebGL Pixel Formats
  100754. */
  100755. var PixelFormat;
  100756. (function (PixelFormat) {
  100757. PixelFormat[PixelFormat["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT";
  100758. PixelFormat[PixelFormat["ALPHA"] = 6406] = "ALPHA";
  100759. PixelFormat[PixelFormat["RGB"] = 6407] = "RGB";
  100760. PixelFormat[PixelFormat["RGBA"] = 6408] = "RGBA";
  100761. PixelFormat[PixelFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  100762. PixelFormat[PixelFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  100763. })(PixelFormat = exports.PixelFormat || (exports.PixelFormat = {}));
  100764. /**
  100765. * WebGL Pixel Types
  100766. */
  100767. var PixelType;
  100768. (function (PixelType) {
  100769. PixelType[PixelType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  100770. PixelType[PixelType["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4";
  100771. PixelType[PixelType["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1";
  100772. PixelType[PixelType["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5";
  100773. })(PixelType = exports.PixelType || (exports.PixelType = {}));
  100774. /**
  100775. * WebGL Texture Magnification Filter
  100776. */
  100777. var TextureMagFilter;
  100778. (function (TextureMagFilter) {
  100779. TextureMagFilter[TextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  100780. TextureMagFilter[TextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  100781. })(TextureMagFilter = exports.TextureMagFilter || (exports.TextureMagFilter = {}));
  100782. /**
  100783. * WebGL Texture Minification Filter
  100784. */
  100785. var TextureMinFilter;
  100786. (function (TextureMinFilter) {
  100787. TextureMinFilter[TextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  100788. TextureMinFilter[TextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  100789. TextureMinFilter[TextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  100790. TextureMinFilter[TextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  100791. TextureMinFilter[TextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  100792. TextureMinFilter[TextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  100793. })(TextureMinFilter = exports.TextureMinFilter || (exports.TextureMinFilter = {}));
  100794. /**
  100795. * WebGL Texture Wrap Modes
  100796. */
  100797. var TextureWrapMode;
  100798. (function (TextureWrapMode) {
  100799. TextureWrapMode[TextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  100800. TextureWrapMode[TextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  100801. TextureWrapMode[TextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  100802. })(TextureWrapMode = exports.TextureWrapMode || (exports.TextureWrapMode = {}));
  100803. /**
  100804. * A minimal WebGL cubemap descriptor
  100805. */
  100806. var TextureCube = /** @class */ (function () {
  100807. /**
  100808. * constructor
  100809. * @param internalFormat WebGL pixel format for the texture on the GPU
  100810. * @param type WebGL pixel type of the supplied data and texture on the GPU
  100811. * @param source An array containing mipmap levels of faces, where each mipmap level is an array of faces and each face is a TextureSource object
  100812. */
  100813. function TextureCube(internalFormat, type, source) {
  100814. if (source === void 0) { source = []; }
  100815. this.internalFormat = internalFormat;
  100816. this.type = type;
  100817. this.source = source;
  100818. }
  100819. Object.defineProperty(TextureCube.prototype, "Width", {
  100820. /**
  100821. * Returns the width of a face of the texture or 0 if not available
  100822. */
  100823. get: function () {
  100824. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].width : 0;
  100825. },
  100826. enumerable: true,
  100827. configurable: true
  100828. });
  100829. Object.defineProperty(TextureCube.prototype, "Height", {
  100830. /**
  100831. * Returns the height of a face of the texture or 0 if not available
  100832. */
  100833. get: function () {
  100834. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].height : 0;
  100835. },
  100836. enumerable: true,
  100837. configurable: true
  100838. });
  100839. return TextureCube;
  100840. }());
  100841. exports.TextureCube = TextureCube;
  100842. /**
  100843. * A static class providing methods to aid working with Bablyon textures.
  100844. */
  100845. var TextureUtils = /** @class */ (function () {
  100846. function TextureUtils() {
  100847. }
  100848. /**
  100849. * Returns a BabylonCubeTexture instance from a Spectre texture cube, subject to sampling parameters.
  100850. * If such a texture has already been requested in the past, this texture will be returned, otherwise a new one will be created.
  100851. * The advantage of this is to enable working with texture objects without the need to initialize on the GPU until desired.
  100852. * @param scene A Babylon Scene instance
  100853. * @param textureCube A Spectre TextureCube object
  100854. * @param parameters WebGL texture sampling parameters
  100855. * @param automaticMipmaps Pass true to enable automatic mipmap generation where possible (requires power of images)
  100856. * @param environment Specifies that the texture will be used as an environment
  100857. * @param singleLod Specifies that the texture will be a singleLod (for environment)
  100858. * @return Babylon cube texture
  100859. */
  100860. TextureUtils.GetBabylonCubeTexture = function (scene, textureCube, automaticMipmaps, environment, singleLod) {
  100861. if (environment === void 0) { environment = false; }
  100862. if (singleLod === void 0) { singleLod = false; }
  100863. if (!textureCube)
  100864. throw new Error("no texture cube provided");
  100865. var parameters;
  100866. if (environment) {
  100867. parameters = singleLod ? TextureUtils._EnvironmentSingleMipSampling : TextureUtils._EnvironmentSampling;
  100868. }
  100869. else {
  100870. parameters = {
  100871. magFilter: 9728 /* NEAREST */,
  100872. minFilter: 9728 /* NEAREST */,
  100873. wrapS: 33071 /* CLAMP_TO_EDGE */,
  100874. wrapT: 33071 /* CLAMP_TO_EDGE */
  100875. };
  100876. }
  100877. var key = TextureUtils.BabylonTextureKeyPrefix + parameters.magFilter + '' + parameters.minFilter + '' + parameters.wrapS + '' + parameters.wrapT;
  100878. var babylonTexture = textureCube[key];
  100879. if (!babylonTexture) {
  100880. //initialize babylon texture
  100881. babylonTexture = new BABYLON.CubeTexture('', scene);
  100882. if (environment) {
  100883. babylonTexture.lodGenerationOffset = TextureUtils.EnvironmentLODOffset;
  100884. babylonTexture.lodGenerationScale = TextureUtils.EnvironmentLODScale;
  100885. }
  100886. babylonTexture.gammaSpace = false;
  100887. var internalTexture_1 = new BABYLON.InternalTexture(scene.getEngine(), BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  100888. var glTexture_1 = internalTexture_1._webGLTexture;
  100889. //babylon properties
  100890. internalTexture_1.isCube = true;
  100891. internalTexture_1.generateMipMaps = false;
  100892. babylonTexture._texture = internalTexture_1;
  100893. TextureUtils.ApplySamplingParameters(babylonTexture, parameters);
  100894. var maxMipLevel_1 = automaticMipmaps ? 0 : textureCube.source.length - 1;
  100895. var texturesUploaded_1 = 0;
  100896. var textureComplete = function () {
  100897. return texturesUploaded_1 === ((maxMipLevel_1 + 1) * 6);
  100898. };
  100899. var uploadFace = function (i, level, face) {
  100900. if (!glTexture_1)
  100901. return;
  100902. if (i === 0 && level === 0) {
  100903. internalTexture_1.width = face.width;
  100904. internalTexture_1.height = face.height;
  100905. }
  100906. var gl = (scene.getEngine())._gl;
  100907. gl.bindTexture(gl.TEXTURE_CUBE_MAP, glTexture_1);
  100908. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  100909. if (face instanceof HTMLElement || face instanceof ImageData) {
  100910. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureCube.internalFormat, textureCube.type, face);
  100911. }
  100912. else {
  100913. var textureData = face;
  100914. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureData.width, textureData.height, 0, textureData.format, textureCube.type, textureData.data);
  100915. }
  100916. texturesUploaded_1++;
  100917. if (textureComplete()) {
  100918. //generate mipmaps
  100919. if (automaticMipmaps) {
  100920. var w = face.width;
  100921. var h = face.height;
  100922. var isPot = (((w !== 0) && (w & (w - 1))) === 0) && (((h !== 0) && (h & (h - 1))) === 0);
  100923. if (isPot) {
  100924. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  100925. }
  100926. }
  100927. // Upload Separate lods in case there is no support for texture lod.
  100928. if (environment && !scene.getEngine().getCaps().textureLOD && !singleLod) {
  100929. var mipSlices = 3;
  100930. for (var i_1 = 0; i_1 < mipSlices; i_1++) {
  100931. var lodKey = TextureUtils.BabylonTextureKeyPrefix + 'lod' + i_1;
  100932. var lod = textureCube[lodKey];
  100933. //initialize lod texture if it doesn't already exist
  100934. if (lod == null && textureCube.Width) {
  100935. //compute LOD from even spacing in smoothness (matching shader calculation)
  100936. var smoothness = i_1 / (mipSlices - 1);
  100937. var roughness = 1 - smoothness;
  100938. var kMinimumVariance = 0.0005;
  100939. var alphaG = roughness * roughness + kMinimumVariance;
  100940. var microsurfaceAverageSlopeTexels = alphaG * textureCube.Width;
  100941. var environmentSpecularLOD = TextureUtils.EnvironmentLODScale * (BABYLON.Scalar.Log2(microsurfaceAverageSlopeTexels)) + TextureUtils.EnvironmentLODOffset;
  100942. var maxLODIndex = textureCube.source.length - 1;
  100943. var mipmapIndex = Math.min(Math.max(Math.round(environmentSpecularLOD), 0), maxLODIndex);
  100944. lod = TextureUtils.GetBabylonCubeTexture(scene, new TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */, [textureCube.source[mipmapIndex]]), false, true, true);
  100945. if (i_1 === 0) {
  100946. internalTexture_1._lodTextureLow = lod;
  100947. }
  100948. else if (i_1 === 1) {
  100949. internalTexture_1._lodTextureMid = lod;
  100950. }
  100951. else {
  100952. internalTexture_1._lodTextureHigh = lod;
  100953. }
  100954. textureCube[lodKey] = lod;
  100955. }
  100956. }
  100957. }
  100958. internalTexture_1.isReady = true;
  100959. }
  100960. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  100961. scene.getEngine().resetTextureCache();
  100962. };
  100963. var _loop_1 = function (i) {
  100964. var faces = textureCube.source[i];
  100965. var _loop_2 = function (j) {
  100966. var face = faces[j];
  100967. if (face instanceof HTMLImageElement && !face.complete) {
  100968. face.addEventListener('load', function () {
  100969. uploadFace(j, i, face);
  100970. }, false);
  100971. }
  100972. else {
  100973. uploadFace(j, i, face);
  100974. }
  100975. };
  100976. for (var j = 0; j < faces.length; j++) {
  100977. _loop_2(j);
  100978. }
  100979. };
  100980. for (var i = 0; i <= maxMipLevel_1; i++) {
  100981. _loop_1(i);
  100982. }
  100983. scene.getEngine().resetTextureCache();
  100984. babylonTexture.isReady = function () {
  100985. return textureComplete();
  100986. };
  100987. textureCube[key] = babylonTexture;
  100988. }
  100989. return babylonTexture;
  100990. };
  100991. /**
  100992. * Applies Spectre SamplingParameters to a Babylon texture by directly setting texture parameters on the internal WebGLTexture as well as setting Babylon fields
  100993. * @param babylonTexture Babylon texture to apply texture to (requires the Babylon texture has an initialize _texture field)
  100994. * @param parameters Spectre SamplingParameters to apply
  100995. */
  100996. TextureUtils.ApplySamplingParameters = function (babylonTexture, parameters) {
  100997. var scene = babylonTexture.getScene();
  100998. if (!scene)
  100999. return;
  101000. var gl = (scene.getEngine())._gl;
  101001. var target = babylonTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  101002. var internalTexture = babylonTexture._texture;
  101003. if (!internalTexture)
  101004. return;
  101005. var glTexture = internalTexture._webGLTexture;
  101006. gl.bindTexture(target, glTexture);
  101007. if (parameters.magFilter != null)
  101008. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, parameters.magFilter);
  101009. if (parameters.minFilter != null)
  101010. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, parameters.minFilter);
  101011. if (parameters.wrapS != null)
  101012. gl.texParameteri(target, gl.TEXTURE_WRAP_S, parameters.wrapS);
  101013. if (parameters.wrapT != null)
  101014. gl.texParameteri(target, gl.TEXTURE_WRAP_T, parameters.wrapT);
  101015. //set babylon wrap modes from sampling parameter
  101016. switch (parameters.wrapS) {
  101017. case 10497 /* REPEAT */:
  101018. babylonTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  101019. break;
  101020. case 33071 /* CLAMP_TO_EDGE */:
  101021. babylonTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101022. break;
  101023. case 33648 /* MIRRORED_REPEAT */:
  101024. babylonTexture.wrapU = BABYLON.Texture.MIRROR_ADDRESSMODE;
  101025. break;
  101026. default: babylonTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101027. }
  101028. switch (parameters.wrapT) {
  101029. case 10497 /* REPEAT */:
  101030. babylonTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  101031. break;
  101032. case 33071 /* CLAMP_TO_EDGE */:
  101033. babylonTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101034. break;
  101035. case 33648 /* MIRRORED_REPEAT */:
  101036. babylonTexture.wrapV = BABYLON.Texture.MIRROR_ADDRESSMODE;
  101037. break;
  101038. default: babylonTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101039. }
  101040. if (parameters.maxAnisotropy != null && parameters.maxAnisotropy > 1) {
  101041. var anisotropicExt = gl.getExtension('EXT_texture_filter_anisotropic');
  101042. if (anisotropicExt) {
  101043. var maxAnisotropicSamples = gl.getParameter(anisotropicExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  101044. var maxAnisotropy = Math.min(parameters.maxAnisotropy, maxAnisotropicSamples);
  101045. gl.texParameterf(target, anisotropicExt.TEXTURE_MAX_ANISOTROPY_EXT, maxAnisotropy);
  101046. babylonTexture.anisotropicFilteringLevel = maxAnisotropy;
  101047. }
  101048. }
  101049. gl.bindTexture(target, null);
  101050. scene.getEngine().resetTextureCache();
  101051. };
  101052. /**
  101053. * A prefix used when storing a babylon texture object reference on a Spectre texture object
  101054. */
  101055. TextureUtils.BabylonTextureKeyPrefix = '__babylonTexture_';
  101056. /**
  101057. * Controls anisotropic filtering for deserialized textures.
  101058. */
  101059. TextureUtils.MaxAnisotropy = 4;
  101060. TextureUtils._EnvironmentSampling = {
  101061. magFilter: 9729 /* LINEAR */,
  101062. minFilter: 9987 /* LINEAR_MIPMAP_LINEAR */,
  101063. wrapS: 33071 /* CLAMP_TO_EDGE */,
  101064. wrapT: 33071 /* CLAMP_TO_EDGE */,
  101065. maxAnisotropy: 1
  101066. };
  101067. TextureUtils._EnvironmentSingleMipSampling = {
  101068. magFilter: 9729 /* LINEAR */,
  101069. minFilter: 9729 /* LINEAR */,
  101070. wrapS: 33071 /* CLAMP_TO_EDGE */,
  101071. wrapT: 33071 /* CLAMP_TO_EDGE */,
  101072. maxAnisotropy: 1
  101073. };
  101074. //from "/Internal/Lighting.EnvironmentFilterScale" in Engine/*/Configuration.cpp
  101075. /**
  101076. * Environment preprocessing dedicated value (Internal Use or Advanced only).
  101077. */
  101078. TextureUtils.EnvironmentLODScale = 0.8;
  101079. /**
  101080. * Environment preprocessing dedicated value (Internal Use or Advanced only)..
  101081. */
  101082. TextureUtils.EnvironmentLODOffset = 1.0;
  101083. return TextureUtils;
  101084. }());
  101085. exports.TextureUtils = TextureUtils;
  101086. /***/ }),
  101087. /* 13 */
  101088. /***/ (function(module, exports) {
  101089. module.exports = "<style>@font-face{font-family:babylon;src:url({{babylonFont}}) format('woff');font-weight:400;font-style:normal}.icon{font-family:babylon}</style> {{#if fillScreen}} <style>body,html{width:100%;height:100%;margin:0;padding:0}</style> {{/if}} <fill-container></fill-container>";
  101090. /***/ }),
  101091. /* 14 */
  101092. /***/ (function(module, exports) {
  101093. module.exports = "<style>fill-container{display:flex}fill-container>*{touch-action:none}</style> {{#unless disable}} <style>fill-container{width:100%;height:100%;justify-content:flex-start;align-items:stretch;align-content:stretch}fill-container>*{flex:1 1 auto;flex-direction:row;justify-content:flex-start;align-items:stretch;align-content:stretch}</style> {{/unless}} <viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  101094. /***/ }),
  101095. /* 15 */
  101096. /***/ (function(module, exports) {
  101097. module.exports = "<style>loading-screen{position:absolute;left:0;z-index:100;opacity:1;pointer-events:none;display:flex;justify-content:center;align-items:center;-webkit-transition:opacity 1s ease;-moz-transition:opacity 1s ease;transition:opacity 1s ease}img.loading-image{-webkit-animation:spin 2s linear infinite;animation:spin 2s linear infinite}@-webkit-keyframes spin{0%{-webkit-transform:rotate(0)}100%{-webkit-transform:rotate(360deg)}}@keyframes spin{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}</style> <img class=loading-image src={{loadingImage}}>";
  101098. /***/ }),
  101099. /* 16 */
  101100. /***/ (function(module, exports) {
  101101. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAStUlEQVR42uyaA7TrShiFn23btm3btm3btm3btm372LWd9+318nSRNk2mtz3trLXX5PbmZOafPT9nxmq1VmuKFggEZs1ms0uVSqUj8vn8Q/SP5nK5lRpMjFYLh8NTZTKZhSBxi2KxeDlEPgh+BQVrhKbfwDNgZf45QZ2J0mrxeHxGtHJRCDoUQm+FpLd4joKc5aKJaDbDNzxuZT3yyLg1FqPVWPip0un0PBCxMUScD+6wtTJr+dz49hdsmh14nMiAKK0WiUSmgbjFC4XCYSz2VeB9/p2wyaxJK9EY93set+dxwhYr1QU9U7B4s4CNIfMM+pvAzyBm1VFjPl+D3cDELdacyVy4kMsdLBMrX0kf4beM1QCt9Ff7hY14nGRpWiIHBgYmU+BDwLMRi3EMJN4KpJUBa5g05OlHthORc4amIJXgZ30EPtXWyiHITFtN0JBziDz6DB6nHtYEI+i04BZQtJqwIfcAOBXM0hCEdXR0TM1k5ydV2Iv+CLTyeXbqgWeeeeY4DmnMOGjxTrw/aDVpkxtirW7Bos09xkns6+ublAlNA3Gr4S+3JCe4ksk9YOeWsdH4nkcTicTMZfLVuXjvrQYmKS54/EZaRReqaQvzz7FrZUYXBocz8BV2tWcQpEDR5eR7mPjGTmP98ssvEyra5N1CnZNZBL+Dp9mUF7A2a0W7u6dlE8/E82Ve0zVlCHz3HhFtnGAmfJWPC5Nm4pfSO6YLWIdVee/bOiFTiz1A/zL9xSpJqjLmpGHJZHJW9sDlvB/yul7gHlze4sY0Wr7UQLrwierA5fJf7eISrcaE9jHuh/TXsLk3j0aj81dbepRbUkXND40Gz7Hx1/SdaIRcz9BCxjDHh/A4nlMAxvjbKa0wZGaDKmeCO5nLAQoQOzs7fa86pVKpOfj2lSDsdc60N5Reat380uD5DfuyZ5KBwGzOc0jNiWCvet1QfONH+ushcz/M6AoqIUojapgWzgauBTEfiP6QzS+ix/E0qW6CB9MFCL7/G5Pd1DGd+uyz8SHmKB0eVPC9KAvwA3iK56Py6fTasVhseoMnVuMrs6h0seWelFnI9PqgIG+DTT2dSSsFsgw3+1z1ZpUsyyzOMrz7+QgH77+CB9gAp/HTWqFQaEqZMMOp4hKMd7hN1DcgxfMzLiLfsZFlMf7mScngA9Gfqp7w3XffuSe6WCi8Y9WufUYwsUKZY0EVVA5FoB3wR3MZNquTg3mxMNvSXw0+Bn1OrgBcid+ds9IxkHc51ljWJuNDAPsb67I/j5O5EfKaGkeyaSZ5hEktdEhxZrGs3GqMfxKL9aYCPJCtYqET4BIep6zQzI9N1L20rIA02geiO5HhYKunZ5JKdtgpNThSCzGpt+2z3YN0N8rkOaoW1K7Iicy9Gfs2HeuBrM+ytWuh3WiULvQxn2d90uh2OmUIkzpp8MZ+ayj4lcFvl6ZiznRxbRKTEe0j3JdizPkYb3fGvUim1n1FzptG4XP3rjQQ03tgWeW/oFBlPv8s8h6tG6GO1tBOKYoeKkFt4HmdhbI7V+F7Rk9P2traJlKRoZTP6x7WOeAl5tFZJyXOt3Xm/eabb47nwkWuCl4YHQf8nheh4BkgQpfWGrjxwdOAlEsNvR/sh6ldsJbXShlrXDbSyfV8tmznse/SL+ZCrnGUSvJ3X/6toUAaeowIVbXNa1rQ78IcfaCc1s+bkWj+ijKvCvjoj6Sf0Mm/5jOZbXinrc4PLdJQfbdSKzeuxkjFTSdJbs43qw2QtFNtX7mrTmr+c1+5OMIYz5VLRfj/2XnvlQa4ypMBCi6nMW7hwmFdI553VDXpB1wQHKyEYL0DZrHvLJ8LXnbjK2WmdCb9iMOF88+cK2D1d8MD96Kqm5+ZAlgHKBZ5Q8rHml3i6VRJGlfJDUI7Oo/4UAG7tdx4mPhlHSpy9Ub0oA4/qvGryrsVlOmuG/37IDniiZy4HOkPC9nsTm4miXlcrZIJ4X82gaA/2zvneNmdHoz/bNu2bdu2bdu2bdu2bdu2fbz3zfe9+eOizelMs93uns7n08uz0+48nUzwJPnFyQO2QAZi/IXNwgGTdXlTgFrfMnH4P9mRS6m18GgWFio/7xFVWiJAS59aHu5Tj7MMBQyxbIktFo1d0kS86mmMtZsmNGYOlknB6wkCTA8mWS5EtPz888+cxXc6vfkPmAqYcsAMxbFUmvZX77wzlhF82SqU4Pf++++PmjeqhBg4OS1QYCldAs4NTgvzrTzDWuxY435wwPYtMweMNXdk3NjzYd8GTHRWyhyE1xboxUzaS47JLieHwhmcvb0oYIvJz35Z0nP4o14YNxcEznenGVXKCTAi5VYCC3CnrXOS//dKJiP4j7entxCk/Bzet1rJAL463D9h42K9LSdmnUhE3yuWSNFA/f6WQsROh9HoyAHbRz1glptzh/JkKdqAqFfrjZD5RFrtZ+3glcNlvX1mCIA3GvYegQ54TM85Ltg9YsNNZu0KAXmz8uzgrtMss0/W7z8v64YdvKQHwElaL1xiK4dJFv2RvPYrURe513dynfYtgXD/8Kj7YFM5BoG6xEs2kyXvx8k6IYFzWcRxEjIKt0/5eezgqSzxqYVRahFsymc06jKHIaJLCLC94zr//XcBXno3F3I/IbOxYHkMalnk2SzfMp4t68yBSmP5lTVH6HUB9VxscXljxzGwLDXA7DjJJZ7F6znVmTRsb1/+qTwA828Z+FjbWvYrGQcDShICFPLw10C9wSHDbrchbBqArR3HZtk2cL779aOmAnJ/1gnZjSbAtv16ouWDVc7WHvIzM1iaeCsDjIYduIOvyPLl9wh4wF0Tio1NEVCt5lZxYY5arzpZcovV5Zq8rAALlfZdi9pDFC3whdktyw7ekLWPnZBzNDDm+xxi12FXjkbylizKkfLnxwZgTy5R4h18fy9YvB8yn4j0DTMFkUkBzaLN4hjxyJTAr2x5ogwxPp0sws4Q/nCypzxzmQG+1yHjxNCJjBik/PDFGWT+fV6pMMpEWNPSsDUBey2lv3xoBhHKDzAb5AS7XEaQRdPz66+/Tpp5dzwnpK/u7p7HI0QMouWDyDf6scQXpn+Nj5fCmZSl38G7eWV94meIKB3YDwf9s4HsSgC+JeYLy+e+I7nK1iZbB2Ap/radEQGbP3Dt3o4uwZvmK64JFQd6pxcgmgg+Qh8BmO87vaFg7Ro41zl5CppN2dNT+96w43wA1vn6EMDTegX6SYTLaVeS61r7KQu7Um52pifAHW1tJ7cawCiIkn4ygbGDbwqcb+nsaBrnAmJ0EHblwoaLzQNg5tu6BQH+2DERoSbYLBiUfZDmK2Yi3j7/BTRF9Ip9CWAUTfn/DwLm+o30o6BkNHKG0/KP2jq6t+Kl0cmXcwT4b1HaxuoLAFPawTEODCtmhKD0TBK7RI0/PM3b1dnZvSM7OSFNggdcIfaLy73nbH2AbaqOUpjbA+Z6MCoZTQt0pXqXNCfojATTas5IdgZn+mJ9ZAefYYRLlwt8We4MhBfwOm8bIBd4rbSzuo00CUvEOAAiZZKWazWAKfriFc4kyz9XicP+jS+6Vg34rCvAYoot0GoAW1Qd6EeBO3iXGJNop0GZGAT4iwPY4Iq1AMBSI3Mhr0C/YDVvzA6eNYngJl4tRLI5cF/KGfO9IyBjtRLAOIgsogME/ZD5BJNpggHmQykP959c0+WqGGAHrTdtOYDDqTofhSTJx1CaACiVmaEPMJU3wPo2Ht/qAFvsR0zQkNojYFGXGpY8BEEIb4ApJ9jqAFtUHanDOXkIN7ynq+uaaIDxtvTyJn6QlqcrovYOLwcA+a5yr7+bGWCtoUU9MbrQLO4U6AeDs/Ls4LMy3OBjkrttdmY+gHGZQnZvNoAV1E9kjc6jQFyGemI4OZYOtIHXjQZYPnxQxrfoLbp9ebQKAGBb5JcZYC3P39PzBlWFtIDZUHVusbBEIQRxrVc1Ql8EWIn8b9IEC8J+niq6pO6EBGfylGTCVFoy8IvejPqfI4aL0X53MwDM4mrVm508a1ozp3e9svBsQ/umt5LhB98oCuD29rfKCrD65R+mRieZE57Vc2uSXgvHO6CuGEfjO5izeQCGm/tv6EJop7SZPQPhnZ0d9xcNcK3/+EELr64FqJ5FVXEmAaoIeM3E8DO37OGgvVJ63hFgRP5ZRQGsvQavFY12JepcOye+TUoNbfn9BUDNGZE6x+OBHi+eymJrl94Aaz3mD4hty6Kt4pkQp1ki0xLxYS0B1ZU473DoH9mqAJMNoHlYmDPh/ly7itDMslP3o/J8LlDt9N1V/FvftQDA+NFlvnm1iq3LoPEmJSQE1MPpy1iTUTyvOmLwlmTl+cr4yuGhO+67777R/AH2HzgxKFkhgB4TkAzn1joQgmJhre+0edW4ohG+m/fhP/3008kSCAg7lwFgCIk07+LokuvdRhRW0w42l7n1GeLNzLLznn766THFszKjgPyTt+gRE2XDRgGMKEf8yqIeX8RONepmP6/tDsb27g72cpaHkMJdU+nPL8Bb5gkw/1YkwLhdaXujlerfb9BORbt/n3omBmsj/yDCgRcnABjs1o1565oJYJwPKn5P1CZa3Q3s+X8Jz2Jo975Dazz2hACjBn1XmQHWvhLzyoIeS3y7iJ1q+LZvo8oBzTfrCqZBJTkzBBit93F22QBWX/lSBN8bulO1kRat6SS3aLzi0LSTwV8KAYa+wFqQNPMQhWr9pNL2eQCmtyANl2lxC1GtwU2z3tR48cwR+tDwHX//PXNAnDmcbSkPl9iSXTTotQ0x+EwA8W6HQed4/fXXJ470iZ+tjSl/LkT82r0GLxSrZIGYeDFVeeXIO1S1+Hvr3cp8Wbk6E2K5OxsPODH+3lgfqzg/EKse3VuKtldvr0mTENI7I9Z5XMS3xp07jIp2/ucxiWehzm91EX4bDnBxncod7dXdJHth7BgRLEfJalQBxFsVsj7u7VxpsBF4Y0Q8u//vpgXYtldPoK1cjM0NKY+MQ/oRZwgTLlOUZj0KpkXom6U1JNuaHWC1Vy+CXBdjr2rA/2BAlaun0CBDgEiZEgUiVHRQQcDol7tXWQFWe/VW+eMaFKAJPdrQRQTUrRDjkY2hvyq8NT5Bcs0+vCThv4c0amKekqTZtv377/Up93m3gabNk/Qb/O6778aNad9L02iZ4344bjnTXj50BS9gRx4u5XHvShFFU6SxHeQztw36JVLm4R6PNMBePepvsTtjzlWZY0FKAnva3dQQbQjAGN7yhu+SIloBcYyUlnej0kUzC5kMznRR9iolo2JEIbxo+iLXy0OGS3WIRo201Ayp1PIeIKa0vQO48eXBv2kQwCza/+3V7nh7dXL57E4yhw/nymZ5LjZE2YZU67lHF/LWNBebiMFZ8TYVBbDaq8/J7xvHdOZGwULRkjnuqHdzavQbuQ987JU0F7iBwwBGz7VT08jaND7my9QLYOxVje0eGGOv0otJRPeisCkwkQoIRKADHGk/a4kAZtRkiEZ5jGEbbk32QIoWfUZsa3WaZckf5yD4EXGuTq89nb50az5t94G6VV6khQs3h7zSUMnAs6q7S87xRoiiBH/2UYF+YMjra8ifR40IjeLc30vmeAlxXoAn7AV6L9r9K0oOcELVnhUD51k5w1mForNtjB8YjV4WeWOZ4yG52gryhF0K30uPraYciNZT076gXFPnSWfVanxvYK/WpElHxMs3IpXlWOgi4sQ8L1IBp4laFc0/iO/WZKR84c9EJE8WCrDaqxfI2z976FlFzhWfG4B7VSvIvj5ZpNaMTbpbbda/fLknDDv09Sz2p9JsbqPYKRptRCLd1Dhj5Pe3CgL1P7ke1V5UfL/WHXiy5HrFWAyAG763EGXwfYVmhANDbd6Ogsokfaahw6k0h7hvDNEQ58KZYcQ5r7HFbbBz/wbO+YJZkavri9o3hyzAyobZwULtmyPgMR9lhWx71d0Z8Q7FauTlnVB3azWIGxux4G4KoWYNcGiX0n1ELr7CZwssRXgpzAp1vVYjodv39cYCdspILRaGjUsf/gHJaAWdrW+QG0Rv/QrFbPHSBywngFzzDeiEkB2zovybktEch90C9wcI/zQjSelhUQ3DJTkpdrCxwD+IJroCvCdPXnMAg2PLfDU6qoF/eX6TZVl8Lclzax0dsyrVqBpO4pqAQHcDecz3EvxQwkI16kGkp9m0v2ljxoU/UGfElBUCxYCMK/HKejMj5LpRriWVx1yNIgfmhyz+83U4WzFvDsAZUa1yYwfcLAh4P3kwI+S6RMybBcrHjKg8XQshTiOZESR+bS+prONUK1niITtvezTcAGYEid2zasSpGUY1ekSztpgRcpHpsK5co1er1YRDu6DelsCMOL5d6DmVo78FBgRzcRy+pgTzFeiqVq1Ki43KZo0b/wP23paVqC/D3gAAAABJRU5ErkJggg=="
  101102. /***/ }),
  101103. /* 17 */
  101104. /***/ (function(module, exports) {
  101105. module.exports = "<style>viewer{position:relative;overflow:hidden;z-index:1;justify-content:center;align-items:center;width:100%;height:100%}.babylonjs-canvas{flex:1;width:100%;height:100%;touch-action:none}</style> <canvas class=babylonjs-canvas touch-action=none> </canvas> <nav-bar></nav-bar>";
  101106. /***/ }),
  101107. /* 18 */
  101108. /***/ (function(module, exports) {
  101109. module.exports = "<style>overlay{position:absolute;z-index:99;opacity:0;display:flex;justify-content:center;align-items:center;-webkit-transition:opacity 1s ease;-moz-transition:opacity 1s ease;transition:opacity 1s ease}.overlay-item{width:100%;height:100%;display:none;align-items:center;justify-content:center;background-color:rgba(121,121,121,.3)}error.overlay-item{background-color:rgba(121,121,121,1)}div#close-button{position:absolute;top:10px;right:10px;width:30px;height:30px;cursor:pointer}div#close-button img{width:100%}</style> <div id=close-button> <img src={{closeImage}} alt={{closeText}}> </div> <help class=overlay-item></help> <error class=overlay-item></error> <share class=overlay-item></share>";
  101110. /***/ }),
  101111. /* 19 */
  101112. /***/ (function(module, exports) {
  101113. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  101114. /***/ }),
  101115. /* 20 */
  101116. /***/ (function(module, exports) {
  101117. module.exports = "Error loading the model";
  101118. /***/ }),
  101119. /* 21 */
  101120. /***/ (function(module, exports, __webpack_require__) {
  101121. "use strict";
  101122. function __export(m) {
  101123. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  101124. }
  101125. Object.defineProperty(exports, "__esModule", { value: true });
  101126. __export(__webpack_require__(11));
  101127. /***/ }),
  101128. /* 22 */
  101129. /***/ (function(module, exports, __webpack_require__) {
  101130. "use strict";
  101131. Object.defineProperty(exports, "__esModule", { value: true });
  101132. var babylonjs_1 = __webpack_require__(0);
  101133. var babylonjs_loaders_1 = __webpack_require__(23);
  101134. var viewerModel_1 = __webpack_require__(4);
  101135. var _1 = __webpack_require__(51);
  101136. /**
  101137. * An instance of the class is in charge of loading the model correctly.
  101138. * This class will continously be expended with tasks required from the specific loaders Babylon has.
  101139. *
  101140. * A Model loader is unique per (Abstract)Viewer. It is being generated by the viewer
  101141. */
  101142. var ModelLoader = /** @class */ (function () {
  101143. /**
  101144. * Create a new Model loader
  101145. * @param _viewer the viewer using this model loader
  101146. */
  101147. function ModelLoader(_viewer) {
  101148. this._viewer = _viewer;
  101149. this._disposed = false;
  101150. this._loaders = [];
  101151. this._loadId = 0;
  101152. this._plugins = [];
  101153. }
  101154. /**
  101155. * Adds a new plugin to the loader process.
  101156. *
  101157. * @param plugin the plugin name or the plugin itself
  101158. */
  101159. ModelLoader.prototype.addPlugin = function (plugin) {
  101160. var actualPlugin = {};
  101161. if (typeof plugin === 'string') {
  101162. var loadedPlugin = _1.getLoaderPluginByName(plugin);
  101163. if (loadedPlugin) {
  101164. actualPlugin = loadedPlugin;
  101165. }
  101166. }
  101167. else {
  101168. actualPlugin = plugin;
  101169. }
  101170. if (actualPlugin && this._plugins.indexOf(actualPlugin) === -1) {
  101171. this._plugins.push(actualPlugin);
  101172. }
  101173. };
  101174. /**
  101175. * Load a model using predefined configuration
  101176. * @param modelConfiguration the modelConfiguration to use to load the model
  101177. */
  101178. ModelLoader.prototype.load = function (modelConfiguration) {
  101179. var _this = this;
  101180. var model = new viewerModel_1.ViewerModel(this._viewer, modelConfiguration);
  101181. model.loadId = this._loadId++;
  101182. if (!modelConfiguration.url) {
  101183. model.state = viewerModel_1.ModelState.ERROR;
  101184. babylonjs_1.Tools.Error("No URL provided");
  101185. return model;
  101186. }
  101187. var base;
  101188. var filename;
  101189. if (modelConfiguration.file) {
  101190. base = "file:";
  101191. filename = modelConfiguration.file;
  101192. }
  101193. else {
  101194. filename = babylonjs_1.Tools.GetFilename(modelConfiguration.url) || modelConfiguration.url;
  101195. base = modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(modelConfiguration.url);
  101196. }
  101197. var plugin = modelConfiguration.loader;
  101198. model.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, this._viewer.sceneManager.scene, function (meshes, particleSystems, skeletons, animationGroups) {
  101199. meshes.forEach(function (mesh) {
  101200. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  101201. model.addMesh(mesh);
  101202. });
  101203. model.particleSystems = particleSystems;
  101204. model.skeletons = skeletons;
  101205. for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) {
  101206. var animationGroup = animationGroups_1[_i];
  101207. model.addAnimationGroup(animationGroup);
  101208. }
  101209. _this._checkAndRun("onLoaded", model);
  101210. _this._viewer.sceneManager.scene.executeWhenReady(function () {
  101211. model.onLoadedObservable.notifyObservers(model);
  101212. });
  101213. }, function (progressEvent) {
  101214. _this._checkAndRun("onProgress", progressEvent);
  101215. model.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  101216. }, function (scene, m, exception) {
  101217. model.state = viewerModel_1.ModelState.ERROR;
  101218. babylonjs_1.Tools.Error("Load Error: There was an error loading the model. " + m);
  101219. _this._checkAndRun("onError", m, exception);
  101220. model.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  101221. }, plugin);
  101222. if (model.loader.name === "gltf") {
  101223. var gltfLoader_1 = model.loader;
  101224. gltfLoader_1.animationStartMode = babylonjs_loaders_1.GLTFLoaderAnimationStartMode.NONE;
  101225. gltfLoader_1.compileMaterials = true;
  101226. if (!modelConfiguration.file) {
  101227. gltfLoader_1.rewriteRootURL = function (rootURL, responseURL) {
  101228. return modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(responseURL || modelConfiguration.url || '');
  101229. };
  101230. }
  101231. // if ground is set to "mirror":
  101232. if (this._viewer.configuration.ground && typeof this._viewer.configuration.ground === 'object' && this._viewer.configuration.ground.mirror) {
  101233. gltfLoader_1.useClipPlane = true;
  101234. }
  101235. Object.keys(gltfLoader_1).filter(function (name) { return name.indexOf('on') === 0 && name.indexOf('Observable') !== -1; }).forEach(function (functionName) {
  101236. gltfLoader_1[functionName].add(function (payload) {
  101237. _this._checkAndRun(functionName.replace("Observable", ''), payload);
  101238. });
  101239. });
  101240. gltfLoader_1.onParsedObservable.add(function (data) {
  101241. if (data && data.json && data.json['asset']) {
  101242. model.loadInfo = data.json['asset'];
  101243. }
  101244. });
  101245. gltfLoader_1.onCompleteObservable.add(function () {
  101246. model.loaderDone = true;
  101247. });
  101248. }
  101249. else {
  101250. model.loaderDone = true;
  101251. }
  101252. this._checkAndRun("onInit", model.loader, model);
  101253. this._loaders.push(model.loader);
  101254. return model;
  101255. };
  101256. ModelLoader.prototype.cancelLoad = function (model) {
  101257. var loader = model.loader || this._loaders[model.loadId];
  101258. // ATM only available in the GLTF Loader
  101259. if (loader && loader.name === "gltf") {
  101260. var gltfLoader = loader;
  101261. gltfLoader.dispose();
  101262. model.state = viewerModel_1.ModelState.CANCELED;
  101263. }
  101264. else {
  101265. babylonjs_1.Tools.Warn("This type of loader cannot cancel the request");
  101266. }
  101267. };
  101268. /**
  101269. * dispose the model loader.
  101270. * If loaders are registered and are in the middle of loading, they will be disposed and the request(s) will be cancelled.
  101271. */
  101272. ModelLoader.prototype.dispose = function () {
  101273. this._loaders.forEach(function (loader) {
  101274. if (loader.name === "gltf") {
  101275. loader.dispose();
  101276. }
  101277. });
  101278. this._loaders.length = 0;
  101279. this._disposed = true;
  101280. };
  101281. ModelLoader.prototype._checkAndRun = function (functionName) {
  101282. var _this = this;
  101283. var payload = [];
  101284. for (var _i = 1; _i < arguments.length; _i++) {
  101285. payload[_i - 1] = arguments[_i];
  101286. }
  101287. if (this._disposed)
  101288. return;
  101289. this._plugins.filter(function (p) { return p[functionName]; }).forEach(function (plugin) {
  101290. try {
  101291. plugin[functionName].apply(_this, payload);
  101292. }
  101293. catch (e) { }
  101294. });
  101295. };
  101296. return ModelLoader;
  101297. }());
  101298. exports.ModelLoader = ModelLoader;
  101299. /***/ }),
  101300. /* 23 */
  101301. /***/ (function(module, exports, __webpack_require__) {
  101302. (function universalModuleDefinition(root, factory) {
  101303. var amdDependencies = [];
  101304. var BABYLON = root.BABYLON || this.BABYLON;
  101305. if(true) {
  101306. BABYLON = BABYLON || __webpack_require__(0);
  101307. module.exports = factory(BABYLON);
  101308. } else if(typeof define === 'function' && define.amd) {
  101309. amdDependencies.push("babylonjs");
  101310. define("babylonjs-loaders", amdDependencies, factory);
  101311. } else if(typeof exports === 'object') {
  101312. BABYLON = BABYLON || require("babylonjs");
  101313. exports["babylonjs-loaders"] = factory(BABYLON);
  101314. } else {
  101315. root["BABYLON"] = factory(BABYLON);
  101316. }
  101317. })(this, function(BABYLON) {
  101318. BABYLON = BABYLON || this.BABYLON;
  101319. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  101320. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  101321. var BABYLON;
  101322. (function (BABYLON) {
  101323. var STLFileLoader = /** @class */ (function () {
  101324. function STLFileLoader() {
  101325. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  101326. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  101327. this.normalPattern = /normal[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g;
  101328. this.vertexPattern = /vertex[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g;
  101329. this.name = "stl";
  101330. // force data to come in as an ArrayBuffer
  101331. // we'll convert to string if it looks like it's an ASCII .stl
  101332. this.extensions = {
  101333. ".stl": { isBinary: true },
  101334. };
  101335. }
  101336. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  101337. var matches;
  101338. if (this.isBinary(data)) {
  101339. // binary .stl
  101340. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  101341. this.parseBinary(babylonMesh, data);
  101342. if (meshes) {
  101343. meshes.push(babylonMesh);
  101344. }
  101345. return true;
  101346. }
  101347. // ASCII .stl
  101348. // convert to string
  101349. var array_buffer = new Uint8Array(data);
  101350. var str = '';
  101351. for (var i = 0; i < data.byteLength; i++) {
  101352. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  101353. }
  101354. data = str;
  101355. while (matches = this.solidPattern.exec(data)) {
  101356. var meshName = matches[1];
  101357. var meshNameFromEnd = matches[3];
  101358. if (meshName != meshNameFromEnd) {
  101359. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  101360. return false;
  101361. }
  101362. // check meshesNames
  101363. if (meshesNames && meshName) {
  101364. if (meshesNames instanceof Array) {
  101365. if (!meshesNames.indexOf(meshName)) {
  101366. continue;
  101367. }
  101368. }
  101369. else {
  101370. if (meshName !== meshesNames) {
  101371. continue;
  101372. }
  101373. }
  101374. }
  101375. // stl mesh name can be empty as well
  101376. meshName = meshName || "stlmesh";
  101377. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  101378. this.parseASCII(babylonMesh, matches[2]);
  101379. if (meshes) {
  101380. meshes.push(babylonMesh);
  101381. }
  101382. }
  101383. return true;
  101384. };
  101385. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  101386. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  101387. if (result) {
  101388. scene.createDefaultCameraOrLight();
  101389. }
  101390. return result;
  101391. };
  101392. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  101393. var container = new BABYLON.AssetContainer(scene);
  101394. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  101395. container.removeAllFromScene();
  101396. return container;
  101397. };
  101398. STLFileLoader.prototype.isBinary = function (data) {
  101399. // check if file size is correct for binary stl
  101400. var faceSize, nFaces, reader;
  101401. reader = new DataView(data);
  101402. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  101403. nFaces = reader.getUint32(80, true);
  101404. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  101405. return true;
  101406. }
  101407. // check characters higher than ASCII to confirm binary
  101408. var fileLength = reader.byteLength;
  101409. for (var index = 0; index < fileLength; index++) {
  101410. if (reader.getUint8(index) > 127) {
  101411. return true;
  101412. }
  101413. }
  101414. return false;
  101415. };
  101416. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  101417. var reader = new DataView(data);
  101418. var faces = reader.getUint32(80, true);
  101419. var dataOffset = 84;
  101420. var faceLength = 12 * 4 + 2;
  101421. var offset = 0;
  101422. var positions = new Float32Array(faces * 3 * 3);
  101423. var normals = new Float32Array(faces * 3 * 3);
  101424. var indices = new Uint32Array(faces * 3);
  101425. var indicesCount = 0;
  101426. for (var face = 0; face < faces; face++) {
  101427. var start = dataOffset + face * faceLength;
  101428. var normalX = reader.getFloat32(start, true);
  101429. var normalY = reader.getFloat32(start + 4, true);
  101430. var normalZ = reader.getFloat32(start + 8, true);
  101431. for (var i = 1; i <= 3; i++) {
  101432. var vertexstart = start + i * 12;
  101433. // ordering is intentional to match ascii import
  101434. positions[offset] = reader.getFloat32(vertexstart, true);
  101435. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  101436. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  101437. normals[offset] = normalX;
  101438. normals[offset + 2] = normalY;
  101439. normals[offset + 1] = normalZ;
  101440. offset += 3;
  101441. }
  101442. indices[indicesCount] = indicesCount++;
  101443. indices[indicesCount] = indicesCount++;
  101444. indices[indicesCount] = indicesCount++;
  101445. }
  101446. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  101447. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  101448. mesh.setIndices(indices);
  101449. mesh.computeWorldMatrix(true);
  101450. };
  101451. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  101452. var positions = [];
  101453. var normals = [];
  101454. var indices = [];
  101455. var indicesCount = 0;
  101456. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  101457. var matches;
  101458. while (matches = this.facetsPattern.exec(solidData)) {
  101459. var facet = matches[1];
  101460. //one normal per face
  101461. var normalMatches = this.normalPattern.exec(facet);
  101462. this.normalPattern.lastIndex = 0;
  101463. if (!normalMatches) {
  101464. continue;
  101465. }
  101466. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  101467. var vertexMatch;
  101468. while (vertexMatch = this.vertexPattern.exec(facet)) {
  101469. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  101470. normals.push(normal[0], normal[1], normal[2]);
  101471. }
  101472. indices.push(indicesCount++, indicesCount++, indicesCount++);
  101473. this.vertexPattern.lastIndex = 0;
  101474. }
  101475. this.facetsPattern.lastIndex = 0;
  101476. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  101477. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  101478. mesh.setIndices(indices);
  101479. mesh.computeWorldMatrix(true);
  101480. };
  101481. return STLFileLoader;
  101482. }());
  101483. BABYLON.STLFileLoader = STLFileLoader;
  101484. if (BABYLON.SceneLoader) {
  101485. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  101486. }
  101487. })(BABYLON || (BABYLON = {}));
  101488. //# sourceMappingURL=babylon.stlFileLoader.js.map
  101489. var BABYLON;
  101490. (function (BABYLON) {
  101491. /**
  101492. * Class reading and parsing the MTL file bundled with the obj file.
  101493. */
  101494. var MTLFileLoader = /** @class */ (function () {
  101495. function MTLFileLoader() {
  101496. // All material loaded from the mtl will be set here
  101497. this.materials = [];
  101498. }
  101499. /**
  101500. * This function will read the mtl file and create each material described inside
  101501. * This function could be improve by adding :
  101502. * -some component missing (Ni, Tf...)
  101503. * -including the specific options available
  101504. *
  101505. * @param scene
  101506. * @param data
  101507. * @param rootUrl
  101508. */
  101509. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  101510. if (data instanceof ArrayBuffer) {
  101511. return;
  101512. }
  101513. //Split the lines from the file
  101514. var lines = data.split('\n');
  101515. //Space char
  101516. var delimiter_pattern = /\s+/;
  101517. //Array with RGB colors
  101518. var color;
  101519. //New material
  101520. var material = null;
  101521. //Look at each line
  101522. for (var i = 0; i < lines.length; i++) {
  101523. var line = lines[i].trim();
  101524. // Blank line or comment
  101525. if (line.length === 0 || line.charAt(0) === '#') {
  101526. continue;
  101527. }
  101528. //Get the first parameter (keyword)
  101529. var pos = line.indexOf(' ');
  101530. var key = (pos >= 0) ? line.substring(0, pos) : line;
  101531. key = key.toLowerCase();
  101532. //Get the data following the key
  101533. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  101534. //This mtl keyword will create the new material
  101535. if (key === "newmtl") {
  101536. //Check if it is the first material.
  101537. // Materials specifications are described after this keyword.
  101538. if (material) {
  101539. //Add the previous material in the material array.
  101540. this.materials.push(material);
  101541. }
  101542. //Create a new material.
  101543. // value is the name of the material read in the mtl file
  101544. material = new BABYLON.StandardMaterial(value, scene);
  101545. }
  101546. else if (key === "kd" && material) {
  101547. // Diffuse color (color under white light) using RGB values
  101548. //value = "r g b"
  101549. color = value.split(delimiter_pattern, 3).map(parseFloat);
  101550. //color = [r,g,b]
  101551. //Set tghe color into the material
  101552. material.diffuseColor = BABYLON.Color3.FromArray(color);
  101553. }
  101554. else if (key === "ka" && material) {
  101555. // Ambient color (color under shadow) using RGB values
  101556. //value = "r g b"
  101557. color = value.split(delimiter_pattern, 3).map(parseFloat);
  101558. //color = [r,g,b]
  101559. //Set tghe color into the material
  101560. material.ambientColor = BABYLON.Color3.FromArray(color);
  101561. }
  101562. else if (key === "ks" && material) {
  101563. // Specular color (color when light is reflected from shiny surface) using RGB values
  101564. //value = "r g b"
  101565. color = value.split(delimiter_pattern, 3).map(parseFloat);
  101566. //color = [r,g,b]
  101567. //Set the color into the material
  101568. material.specularColor = BABYLON.Color3.FromArray(color);
  101569. }
  101570. else if (key === "ke" && material) {
  101571. // Emissive color using RGB values
  101572. color = value.split(delimiter_pattern, 3).map(parseFloat);
  101573. material.emissiveColor = BABYLON.Color3.FromArray(color);
  101574. }
  101575. else if (key === "ns" && material) {
  101576. //value = "Integer"
  101577. material.specularPower = parseFloat(value);
  101578. }
  101579. else if (key === "d" && material) {
  101580. //d is dissolve for current material. It mean alpha for BABYLON
  101581. material.alpha = parseFloat(value);
  101582. //Texture
  101583. //This part can be improved by adding the possible options of texture
  101584. }
  101585. else if (key === "map_ka" && material) {
  101586. // ambient texture map with a loaded image
  101587. //We must first get the folder of the image
  101588. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  101589. }
  101590. else if (key === "map_kd" && material) {
  101591. // Diffuse texture map with a loaded image
  101592. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  101593. }
  101594. else if (key === "map_ks" && material) {
  101595. // Specular texture map with a loaded image
  101596. //We must first get the folder of the image
  101597. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  101598. }
  101599. else if (key === "map_ns") {
  101600. //Specular
  101601. //Specular highlight component
  101602. //We must first get the folder of the image
  101603. //
  101604. //Not supported by BABYLON
  101605. //
  101606. // continue;
  101607. }
  101608. else if (key === "map_bump" && material) {
  101609. //The bump texture
  101610. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  101611. }
  101612. else if (key === "map_d" && material) {
  101613. // The dissolve of the material
  101614. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  101615. //Options for illumination
  101616. }
  101617. else if (key === "illum") {
  101618. //Illumination
  101619. if (value === "0") {
  101620. //That mean Kd == Kd
  101621. }
  101622. else if (value === "1") {
  101623. //Color on and Ambient on
  101624. }
  101625. else if (value === "2") {
  101626. //Highlight on
  101627. }
  101628. else if (value === "3") {
  101629. //Reflection on and Ray trace on
  101630. }
  101631. else if (value === "4") {
  101632. //Transparency: Glass on, Reflection: Ray trace on
  101633. }
  101634. else if (value === "5") {
  101635. //Reflection: Fresnel on and Ray trace on
  101636. }
  101637. else if (value === "6") {
  101638. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  101639. }
  101640. else if (value === "7") {
  101641. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  101642. }
  101643. else if (value === "8") {
  101644. //Reflection on and Ray trace off
  101645. }
  101646. else if (value === "9") {
  101647. //Transparency: Glass on, Reflection: Ray trace off
  101648. }
  101649. else if (value === "10") {
  101650. //Casts shadows onto invisible surfaces
  101651. }
  101652. }
  101653. else {
  101654. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  101655. }
  101656. }
  101657. //At the end of the file, add the last material
  101658. if (material) {
  101659. this.materials.push(material);
  101660. }
  101661. };
  101662. /**
  101663. * Gets the texture for the material.
  101664. *
  101665. * If the material is imported from input file,
  101666. * We sanitize the url to ensure it takes the textre from aside the material.
  101667. *
  101668. * @param rootUrl The root url to load from
  101669. * @param value The value stored in the mtl
  101670. * @return The Texture
  101671. */
  101672. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  101673. if (!value) {
  101674. return null;
  101675. }
  101676. var url = rootUrl;
  101677. // Load from input file.
  101678. if (rootUrl === "file:") {
  101679. var lastDelimiter = value.lastIndexOf("\\");
  101680. if (lastDelimiter === -1) {
  101681. lastDelimiter = value.lastIndexOf("/");
  101682. }
  101683. if (lastDelimiter > -1) {
  101684. url += value.substr(lastDelimiter + 1);
  101685. }
  101686. else {
  101687. url += value;
  101688. }
  101689. }
  101690. // Not from input file.
  101691. else {
  101692. url += value;
  101693. }
  101694. return new BABYLON.Texture(url, scene);
  101695. };
  101696. return MTLFileLoader;
  101697. }());
  101698. BABYLON.MTLFileLoader = MTLFileLoader;
  101699. var OBJFileLoader = /** @class */ (function () {
  101700. function OBJFileLoader() {
  101701. this.name = "obj";
  101702. this.extensions = ".obj";
  101703. this.obj = /^o/;
  101704. this.group = /^g/;
  101705. this.mtllib = /^mtllib /;
  101706. this.usemtl = /^usemtl /;
  101707. this.smooth = /^s /;
  101708. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  101709. // vn float float float
  101710. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  101711. // vt float float
  101712. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  101713. // f vertex vertex vertex ...
  101714. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  101715. // f vertex/uvs vertex/uvs vertex/uvs ...
  101716. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  101717. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  101718. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  101719. // f vertex//normal vertex//normal vertex//normal ...
  101720. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  101721. }
  101722. /**
  101723. * Calls synchronously the MTL file attached to this obj.
  101724. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  101725. * Without this function materials are not displayed in the first frame (but displayed after).
  101726. * In consequence it is impossible to get material information in your HTML file
  101727. *
  101728. * @param url The URL of the MTL file
  101729. * @param rootUrl
  101730. * @param onSuccess Callback function to be called when the MTL file is loaded
  101731. * @private
  101732. */
  101733. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  101734. //The complete path to the mtl file
  101735. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  101736. // Loads through the babylon tools to allow fileInput search.
  101737. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  101738. };
  101739. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  101740. //get the meshes from OBJ file
  101741. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  101742. //Push meshes from OBJ file into the variable mesh of this function
  101743. if (meshes) {
  101744. loadedMeshes.forEach(function (mesh) {
  101745. meshes.push(mesh);
  101746. });
  101747. }
  101748. return true;
  101749. };
  101750. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  101751. //Get the 3D model
  101752. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  101753. };
  101754. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  101755. var container = new BABYLON.AssetContainer(scene);
  101756. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  101757. container.removeAllFromScene();
  101758. return container;
  101759. };
  101760. /**
  101761. * Read the OBJ file and create an Array of meshes.
  101762. * Each mesh contains all information given by the OBJ and the MTL file.
  101763. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  101764. *
  101765. * @param meshesNames
  101766. * @param scene BABYLON.Scene The scene where are displayed the data
  101767. * @param data String The content of the obj file
  101768. * @param rootUrl String The path to the folder
  101769. * @returns Array<AbstractMesh>
  101770. * @private
  101771. */
  101772. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  101773. var positions = []; //values for the positions of vertices
  101774. var normals = []; //Values for the normals
  101775. var uvs = []; //Values for the textures
  101776. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  101777. var handledMesh; //The current mesh of meshes array
  101778. var indicesForBabylon = []; //The list of indices for VertexData
  101779. var wrappedPositionForBabylon = []; //The list of position in vectors
  101780. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  101781. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  101782. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  101783. var curPositionInIndices = 0;
  101784. var hasMeshes = false; //Meshes are defined in the file
  101785. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  101786. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  101787. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  101788. var triangles = []; //Indices from new triangles coming from polygons
  101789. var materialNameFromObj = ""; //The name of the current material
  101790. var fileToLoad = ""; //The name of the mtlFile to load
  101791. var materialsFromMTLFile = new MTLFileLoader();
  101792. var objMeshName = ""; //The name of the current obj mesh
  101793. var increment = 1; //Id for meshes created by the multimaterial
  101794. var isFirstMaterial = true;
  101795. /**
  101796. * Search for obj in the given array.
  101797. * This function is called to check if a couple of data already exists in an array.
  101798. *
  101799. * If found, returns the index of the founded tuple index. Returns -1 if not found
  101800. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  101801. * @param obj Array<number>
  101802. * @returns {boolean}
  101803. */
  101804. var isInArray = function (arr, obj) {
  101805. if (!arr[obj[0]])
  101806. arr[obj[0]] = { normals: [], idx: [] };
  101807. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  101808. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  101809. };
  101810. var isInArrayUV = function (arr, obj) {
  101811. if (!arr[obj[0]])
  101812. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  101813. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  101814. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  101815. return arr[obj[0]].idx[idx];
  101816. }
  101817. return -1;
  101818. };
  101819. /**
  101820. * This function set the data for each triangle.
  101821. * Data are position, normals and uvs
  101822. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  101823. * If the tuple already exist, add only their indice
  101824. *
  101825. * @param indicePositionFromObj Integer The index in positions array
  101826. * @param indiceUvsFromObj Integer The index in uvs array
  101827. * @param indiceNormalFromObj Integer The index in normals array
  101828. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  101829. * @param textureVectorFromOBJ Vector3 The value of uvs
  101830. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  101831. */
  101832. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  101833. //Check if this tuple already exists in the list of tuples
  101834. var _index;
  101835. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  101836. _index = isInArrayUV(tuplePosNorm, [
  101837. indicePositionFromObj,
  101838. indiceNormalFromObj,
  101839. indiceUvsFromObj
  101840. ]);
  101841. }
  101842. else {
  101843. _index = isInArray(tuplePosNorm, [
  101844. indicePositionFromObj,
  101845. indiceNormalFromObj
  101846. ]);
  101847. }
  101848. //If it not exists
  101849. if (_index == -1) {
  101850. //Add an new indice.
  101851. //The array of indices is only an array with his length equal to the number of triangles - 1.
  101852. //We add vertices data in this order
  101853. indicesForBabylon.push(wrappedPositionForBabylon.length);
  101854. //Push the position of vertice for Babylon
  101855. //Each element is a BABYLON.Vector3(x,y,z)
  101856. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  101857. //Push the uvs for Babylon
  101858. //Each element is a BABYLON.Vector3(u,v)
  101859. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  101860. //Push the normals for Babylon
  101861. //Each element is a BABYLON.Vector3(x,y,z)
  101862. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  101863. //Add the tuple in the comparison list
  101864. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  101865. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  101866. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  101867. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  101868. }
  101869. else {
  101870. //The tuple already exists
  101871. //Add the index of the already existing tuple
  101872. //At this index we can get the value of position, normal and uvs of vertex
  101873. indicesForBabylon.push(_index);
  101874. }
  101875. };
  101876. /**
  101877. * Transform BABYLON.Vector() object onto 3 digits in an array
  101878. */
  101879. var unwrapData = function () {
  101880. //Every array has the same length
  101881. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  101882. //Push the x, y, z values of each element in the unwrapped array
  101883. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  101884. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  101885. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  101886. }
  101887. // Reset arrays for the next new meshes
  101888. wrappedPositionForBabylon = [];
  101889. wrappedNormalsForBabylon = [];
  101890. wrappedUvsForBabylon = [];
  101891. tuplePosNorm = [];
  101892. curPositionInIndices = 0;
  101893. };
  101894. /**
  101895. * Create triangles from polygons by recursion
  101896. * The best to understand how it works is to draw it in the same time you get the recursion.
  101897. * It is important to notice that a triangle is a polygon
  101898. * We get 4 patterns of face defined in OBJ File :
  101899. * facePattern1 = ["1","2","3","4","5","6"]
  101900. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  101901. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  101902. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  101903. * Each pattern is divided by the same method
  101904. * @param face Array[String] The indices of elements
  101905. * @param v Integer The variable to increment
  101906. */
  101907. var getTriangles = function (face, v) {
  101908. //Work for each element of the array
  101909. if (v + 1 < face.length) {
  101910. //Add on the triangle variable the indexes to obtain triangles
  101911. triangles.push(face[0], face[v], face[v + 1]);
  101912. //Incrementation for recursion
  101913. v += 1;
  101914. //Recursion
  101915. getTriangles(face, v);
  101916. }
  101917. //Result obtained after 2 iterations:
  101918. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  101919. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  101920. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  101921. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  101922. };
  101923. /**
  101924. * Create triangles and push the data for each polygon for the pattern 1
  101925. * In this pattern we get vertice positions
  101926. * @param face
  101927. * @param v
  101928. */
  101929. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  101930. //Get the indices of triangles for each polygon
  101931. getTriangles(face, v);
  101932. //For each element in the triangles array.
  101933. //This var could contains 1 to an infinity of triangles
  101934. for (var k = 0; k < triangles.length; k++) {
  101935. // Set position indice
  101936. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  101937. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  101938. positions[indicePositionFromObj], //Get the vectors data
  101939. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  101940. );
  101941. }
  101942. //Reset variable for the next line
  101943. triangles = [];
  101944. };
  101945. /**
  101946. * Create triangles and push the data for each polygon for the pattern 2
  101947. * In this pattern we get vertice positions and uvsu
  101948. * @param face
  101949. * @param v
  101950. */
  101951. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  101952. //Get the indices of triangles for each polygon
  101953. getTriangles(face, v);
  101954. for (var k = 0; k < triangles.length; k++) {
  101955. //triangle[k] = "1/1"
  101956. //Split the data for getting position and uv
  101957. var point = triangles[k].split("/"); // ["1", "1"]
  101958. //Set position indice
  101959. var indicePositionFromObj = parseInt(point[0]) - 1;
  101960. //Set uv indice
  101961. var indiceUvsFromObj = parseInt(point[1]) - 1;
  101962. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  101963. positions[indicePositionFromObj], //Get the values for each element
  101964. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  101965. );
  101966. }
  101967. //Reset variable for the next line
  101968. triangles = [];
  101969. };
  101970. /**
  101971. * Create triangles and push the data for each polygon for the pattern 3
  101972. * In this pattern we get vertice positions, uvs and normals
  101973. * @param face
  101974. * @param v
  101975. */
  101976. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  101977. //Get the indices of triangles for each polygon
  101978. getTriangles(face, v);
  101979. for (var k = 0; k < triangles.length; k++) {
  101980. //triangle[k] = "1/1/1"
  101981. //Split the data for getting position, uv, and normals
  101982. var point = triangles[k].split("/"); // ["1", "1", "1"]
  101983. // Set position indice
  101984. var indicePositionFromObj = parseInt(point[0]) - 1;
  101985. // Set uv indice
  101986. var indiceUvsFromObj = parseInt(point[1]) - 1;
  101987. // Set normal indice
  101988. var indiceNormalFromObj = parseInt(point[2]) - 1;
  101989. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  101990. );
  101991. }
  101992. //Reset variable for the next line
  101993. triangles = [];
  101994. };
  101995. /**
  101996. * Create triangles and push the data for each polygon for the pattern 4
  101997. * In this pattern we get vertice positions and normals
  101998. * @param face
  101999. * @param v
  102000. */
  102001. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  102002. getTriangles(face, v);
  102003. for (var k = 0; k < triangles.length; k++) {
  102004. //triangle[k] = "1//1"
  102005. //Split the data for getting position and normals
  102006. var point = triangles[k].split("//"); // ["1", "1"]
  102007. // We check indices, and normals
  102008. var indicePositionFromObj = parseInt(point[0]) - 1;
  102009. var indiceNormalFromObj = parseInt(point[1]) - 1;
  102010. setData(indicePositionFromObj, 1, //Default value for uv
  102011. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  102012. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  102013. }
  102014. //Reset variable for the next line
  102015. triangles = [];
  102016. };
  102017. var addPreviousObjMesh = function () {
  102018. //Check if it is not the first mesh. Otherwise we don't have data.
  102019. if (meshesFromObj.length > 0) {
  102020. //Get the previous mesh for applying the data about the faces
  102021. //=> in obj file, faces definition append after the name of the mesh
  102022. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  102023. //Set the data into Array for the mesh
  102024. unwrapData();
  102025. // Reverse tab. Otherwise face are displayed in the wrong sens
  102026. indicesForBabylon.reverse();
  102027. //Set the information for the mesh
  102028. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  102029. handledMesh.indices = indicesForBabylon.slice();
  102030. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  102031. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  102032. handledMesh.uvs = unwrappedUVForBabylon.slice();
  102033. //Reset the array for the next mesh
  102034. indicesForBabylon = [];
  102035. unwrappedPositionsForBabylon = [];
  102036. unwrappedNormalsForBabylon = [];
  102037. unwrappedUVForBabylon = [];
  102038. }
  102039. };
  102040. //Main function
  102041. //Split the file into lines
  102042. var lines = data.split('\n');
  102043. //Look at each line
  102044. for (var i = 0; i < lines.length; i++) {
  102045. var line = lines[i].trim();
  102046. var result;
  102047. //Comment or newLine
  102048. if (line.length === 0 || line.charAt(0) === '#') {
  102049. continue;
  102050. //Get information about one position possible for the vertices
  102051. }
  102052. else if ((result = this.vertexPattern.exec(line)) !== null) {
  102053. //Create a Vector3 with the position x, y, z
  102054. //Value of result:
  102055. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  102056. //Add the Vector in the list of positions
  102057. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  102058. }
  102059. else if ((result = this.normalPattern.exec(line)) !== null) {
  102060. //Create a Vector3 with the normals x, y, z
  102061. //Value of result
  102062. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  102063. //Add the Vector in the list of normals
  102064. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  102065. }
  102066. else if ((result = this.uvPattern.exec(line)) !== null) {
  102067. //Create a Vector2 with the normals u, v
  102068. //Value of result
  102069. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  102070. //Add the Vector in the list of uvs
  102071. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  102072. //Identify patterns of faces
  102073. //Face could be defined in different type of pattern
  102074. }
  102075. else if ((result = this.facePattern3.exec(line)) !== null) {
  102076. //Value of result:
  102077. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  102078. //Set the data for this face
  102079. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  102080. 1);
  102081. }
  102082. else if ((result = this.facePattern4.exec(line)) !== null) {
  102083. //Value of result:
  102084. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  102085. //Set the data for this face
  102086. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  102087. 1);
  102088. }
  102089. else if ((result = this.facePattern2.exec(line)) !== null) {
  102090. //Value of result:
  102091. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  102092. //Set the data for this face
  102093. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  102094. 1);
  102095. }
  102096. else if ((result = this.facePattern1.exec(line)) !== null) {
  102097. //Value of result
  102098. //["f 1 2 3", "1 2 3"...]
  102099. //Set the data for this face
  102100. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  102101. 1);
  102102. //Define a mesh or an object
  102103. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  102104. }
  102105. else if (this.group.test(line) || this.obj.test(line)) {
  102106. //Create a new mesh corresponding to the name of the group.
  102107. //Definition of the mesh
  102108. var objMesh =
  102109. //Set the name of the current obj mesh
  102110. {
  102111. name: line.substring(2).trim(),
  102112. indices: undefined,
  102113. positions: undefined,
  102114. normals: undefined,
  102115. uvs: undefined,
  102116. materialName: ""
  102117. };
  102118. addPreviousObjMesh();
  102119. //Push the last mesh created with only the name
  102120. meshesFromObj.push(objMesh);
  102121. //Set this variable to indicate that now meshesFromObj has objects defined inside
  102122. hasMeshes = true;
  102123. isFirstMaterial = true;
  102124. increment = 1;
  102125. //Keyword for applying a material
  102126. }
  102127. else if (this.usemtl.test(line)) {
  102128. //Get the name of the material
  102129. materialNameFromObj = line.substring(7).trim();
  102130. //If this new material is in the same mesh
  102131. if (!isFirstMaterial) {
  102132. //Set the data for the previous mesh
  102133. addPreviousObjMesh();
  102134. //Create a new mesh
  102135. var objMesh =
  102136. //Set the name of the current obj mesh
  102137. {
  102138. name: objMeshName + "_mm" + increment.toString(),
  102139. indices: undefined,
  102140. positions: undefined,
  102141. normals: undefined,
  102142. uvs: undefined,
  102143. materialName: materialNameFromObj
  102144. };
  102145. increment++;
  102146. //If meshes are already defined
  102147. meshesFromObj.push(objMesh);
  102148. }
  102149. //Set the material name if the previous line define a mesh
  102150. if (hasMeshes && isFirstMaterial) {
  102151. //Set the material name to the previous mesh (1 material per mesh)
  102152. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  102153. isFirstMaterial = false;
  102154. }
  102155. //Keyword for loading the mtl file
  102156. }
  102157. else if (this.mtllib.test(line)) {
  102158. //Get the name of mtl file
  102159. fileToLoad = line.substring(7).trim();
  102160. //Apply smoothing
  102161. }
  102162. else if (this.smooth.test(line)) {
  102163. // smooth shading => apply smoothing
  102164. //Toda y I don't know it work with babylon and with obj.
  102165. //With the obj file an integer is set
  102166. }
  102167. else {
  102168. //If there is another possibility
  102169. console.log("Unhandled expression at line : " + line);
  102170. }
  102171. }
  102172. //At the end of the file, add the last mesh into the meshesFromObj array
  102173. if (hasMeshes) {
  102174. //Set the data for the last mesh
  102175. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  102176. //Reverse indices for displaying faces in the good sens
  102177. indicesForBabylon.reverse();
  102178. //Get the good array
  102179. unwrapData();
  102180. //Set array
  102181. handledMesh.indices = indicesForBabylon;
  102182. handledMesh.positions = unwrappedPositionsForBabylon;
  102183. handledMesh.normals = unwrappedNormalsForBabylon;
  102184. handledMesh.uvs = unwrappedUVForBabylon;
  102185. }
  102186. //If any o or g keyword found, create a mesj with a random id
  102187. if (!hasMeshes) {
  102188. // reverse tab of indices
  102189. indicesForBabylon.reverse();
  102190. //Get positions normals uvs
  102191. unwrapData();
  102192. //Set data for one mesh
  102193. meshesFromObj.push({
  102194. name: BABYLON.Geometry.RandomId(),
  102195. indices: indicesForBabylon,
  102196. positions: unwrappedPositionsForBabylon,
  102197. normals: unwrappedNormalsForBabylon,
  102198. uvs: unwrappedUVForBabylon,
  102199. materialName: materialNameFromObj
  102200. });
  102201. }
  102202. //Create a BABYLON.Mesh list
  102203. var babylonMeshesArray = []; //The mesh for babylon
  102204. var materialToUse = new Array();
  102205. //Set data for each mesh
  102206. for (var j = 0; j < meshesFromObj.length; j++) {
  102207. //check meshesNames (stlFileLoader)
  102208. if (meshesNames && meshesFromObj[j].name) {
  102209. if (meshesNames instanceof Array) {
  102210. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  102211. continue;
  102212. }
  102213. }
  102214. else {
  102215. if (meshesFromObj[j].name !== meshesNames) {
  102216. continue;
  102217. }
  102218. }
  102219. }
  102220. //Get the current mesh
  102221. //Set the data with VertexBuffer for each mesh
  102222. handledMesh = meshesFromObj[j];
  102223. //Create a BABYLON.Mesh with the name of the obj mesh
  102224. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  102225. //Push the name of the material to an array
  102226. //This is indispensable for the importMesh function
  102227. materialToUse.push(meshesFromObj[j].materialName);
  102228. var vertexData = new BABYLON.VertexData(); //The container for the values
  102229. //Set the data for the babylonMesh
  102230. vertexData.positions = handledMesh.positions;
  102231. vertexData.normals = handledMesh.normals;
  102232. vertexData.uvs = handledMesh.uvs;
  102233. vertexData.indices = handledMesh.indices;
  102234. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  102235. vertexData.applyToMesh(babylonMesh);
  102236. if (OBJFileLoader.INVERT_Y) {
  102237. babylonMesh.scaling.y *= -1;
  102238. }
  102239. //Push the mesh into an array
  102240. babylonMeshesArray.push(babylonMesh);
  102241. }
  102242. //load the materials
  102243. //Check if we have a file to load
  102244. if (fileToLoad !== "") {
  102245. //Load the file synchronously
  102246. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  102247. //Create materials thanks MTLLoader function
  102248. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  102249. //Look at each material loaded in the mtl file
  102250. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  102251. //Three variables to get all meshes with the same material
  102252. var startIndex = 0;
  102253. var _indices = [];
  102254. var _index;
  102255. //The material from MTL file is used in the meshes loaded
  102256. //Push the indice in an array
  102257. //Check if the material is not used for another mesh
  102258. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  102259. _indices.push(_index);
  102260. startIndex = _index + 1;
  102261. }
  102262. //If the material is not used dispose it
  102263. if (_index == -1 && _indices.length == 0) {
  102264. //If the material is not needed, remove it
  102265. materialsFromMTLFile.materials[n].dispose();
  102266. }
  102267. else {
  102268. for (var o = 0; o < _indices.length; o++) {
  102269. //Apply the material to the BABYLON.Mesh for each mesh with the material
  102270. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  102271. }
  102272. }
  102273. }
  102274. });
  102275. }
  102276. //Return an array with all BABYLON.Mesh
  102277. return babylonMeshesArray;
  102278. };
  102279. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  102280. OBJFileLoader.INVERT_Y = false;
  102281. return OBJFileLoader;
  102282. }());
  102283. BABYLON.OBJFileLoader = OBJFileLoader;
  102284. if (BABYLON.SceneLoader) {
  102285. //Add this loader into the register plugin
  102286. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  102287. }
  102288. })(BABYLON || (BABYLON = {}));
  102289. //# sourceMappingURL=babylon.objFileLoader.js.map
  102290. var BABYLON;
  102291. (function (BABYLON) {
  102292. /**
  102293. * Mode that determines the coordinate system to use.
  102294. */
  102295. var GLTFLoaderCoordinateSystemMode;
  102296. (function (GLTFLoaderCoordinateSystemMode) {
  102297. /**
  102298. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  102299. */
  102300. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  102301. /**
  102302. * Sets the useRightHandedSystem flag on the scene.
  102303. */
  102304. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  102305. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  102306. /**
  102307. * Mode that determines what animations will start.
  102308. */
  102309. var GLTFLoaderAnimationStartMode;
  102310. (function (GLTFLoaderAnimationStartMode) {
  102311. /**
  102312. * No animation will start.
  102313. */
  102314. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  102315. /**
  102316. * The first animation will start.
  102317. */
  102318. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  102319. /**
  102320. * All animations will start.
  102321. */
  102322. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  102323. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  102324. /**
  102325. * Loader state.
  102326. */
  102327. var GLTFLoaderState;
  102328. (function (GLTFLoaderState) {
  102329. /**
  102330. * The asset is loading.
  102331. */
  102332. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  102333. /**
  102334. * The asset is ready for rendering.
  102335. */
  102336. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  102337. /**
  102338. * The asset is completely loaded.
  102339. */
  102340. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  102341. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  102342. /**
  102343. * File loader for loading glTF files into a scene.
  102344. */
  102345. var GLTFFileLoader = /** @class */ (function () {
  102346. function GLTFFileLoader() {
  102347. // #region Common options
  102348. /**
  102349. * Raised when the asset has been parsed
  102350. */
  102351. this.onParsedObservable = new BABYLON.Observable();
  102352. // #endregion
  102353. // #region V2 options
  102354. /**
  102355. * The coordinate system mode. Defaults to AUTO.
  102356. */
  102357. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  102358. /**
  102359. * The animation start mode. Defaults to FIRST.
  102360. */
  102361. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  102362. /**
  102363. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  102364. */
  102365. this.compileMaterials = false;
  102366. /**
  102367. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  102368. */
  102369. this.useClipPlane = false;
  102370. /**
  102371. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  102372. */
  102373. this.compileShadowGenerators = false;
  102374. /**
  102375. * Defines if the Alpha blended materials are only applied as coverage.
  102376. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  102377. * If true, no extra effects are applied to transparent pixels.
  102378. */
  102379. this.transparencyAsCoverage = false;
  102380. /** @hidden */
  102381. this._normalizeAnimationGroupsToBeginAtZero = true;
  102382. /**
  102383. * Function called before loading a url referenced by the asset.
  102384. */
  102385. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  102386. /**
  102387. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  102388. */
  102389. this.onMeshLoadedObservable = new BABYLON.Observable();
  102390. /**
  102391. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  102392. */
  102393. this.onTextureLoadedObservable = new BABYLON.Observable();
  102394. /**
  102395. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  102396. */
  102397. this.onMaterialLoadedObservable = new BABYLON.Observable();
  102398. /**
  102399. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  102400. */
  102401. this.onCameraLoadedObservable = new BABYLON.Observable();
  102402. /**
  102403. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  102404. * For assets with LODs, raised when all of the LODs are complete.
  102405. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  102406. */
  102407. this.onCompleteObservable = new BABYLON.Observable();
  102408. /**
  102409. * Observable raised after the loader is disposed.
  102410. */
  102411. this.onDisposeObservable = new BABYLON.Observable();
  102412. /**
  102413. * Observable raised after a loader extension is created.
  102414. * Set additional options for a loader extension in this event.
  102415. */
  102416. this.onExtensionLoadedObservable = new BABYLON.Observable();
  102417. // #endregion
  102418. this._loader = null;
  102419. /**
  102420. * Name of the loader ("gltf")
  102421. */
  102422. this.name = "gltf";
  102423. /**
  102424. * Supported file extensions of the loader (.gltf, .glb)
  102425. */
  102426. this.extensions = {
  102427. ".gltf": { isBinary: false },
  102428. ".glb": { isBinary: true }
  102429. };
  102430. }
  102431. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  102432. /**
  102433. * Raised when the asset has been parsed
  102434. */
  102435. set: function (callback) {
  102436. if (this._onParsedObserver) {
  102437. this.onParsedObservable.remove(this._onParsedObserver);
  102438. }
  102439. this._onParsedObserver = this.onParsedObservable.add(callback);
  102440. },
  102441. enumerable: true,
  102442. configurable: true
  102443. });
  102444. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  102445. /**
  102446. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  102447. */
  102448. set: function (callback) {
  102449. if (this._onMeshLoadedObserver) {
  102450. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  102451. }
  102452. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  102453. },
  102454. enumerable: true,
  102455. configurable: true
  102456. });
  102457. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  102458. /**
  102459. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  102460. */
  102461. set: function (callback) {
  102462. if (this._onTextureLoadedObserver) {
  102463. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  102464. }
  102465. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  102466. },
  102467. enumerable: true,
  102468. configurable: true
  102469. });
  102470. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  102471. /**
  102472. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  102473. */
  102474. set: function (callback) {
  102475. if (this._onMaterialLoadedObserver) {
  102476. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  102477. }
  102478. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  102479. },
  102480. enumerable: true,
  102481. configurable: true
  102482. });
  102483. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  102484. /**
  102485. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  102486. */
  102487. set: function (callback) {
  102488. if (this._onCameraLoadedObserver) {
  102489. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  102490. }
  102491. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  102492. },
  102493. enumerable: true,
  102494. configurable: true
  102495. });
  102496. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  102497. /**
  102498. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  102499. */
  102500. set: function (callback) {
  102501. if (this._onCompleteObserver) {
  102502. this.onCompleteObservable.remove(this._onCompleteObserver);
  102503. }
  102504. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  102505. },
  102506. enumerable: true,
  102507. configurable: true
  102508. });
  102509. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  102510. /**
  102511. * Callback raised after the loader is disposed.
  102512. */
  102513. set: function (callback) {
  102514. if (this._onDisposeObserver) {
  102515. this.onDisposeObservable.remove(this._onDisposeObserver);
  102516. }
  102517. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  102518. },
  102519. enumerable: true,
  102520. configurable: true
  102521. });
  102522. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  102523. /**
  102524. * Callback raised after a loader extension is created.
  102525. */
  102526. set: function (callback) {
  102527. if (this._onExtensionLoadedObserver) {
  102528. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  102529. }
  102530. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  102531. },
  102532. enumerable: true,
  102533. configurable: true
  102534. });
  102535. /**
  102536. * Returns a promise that resolves when the asset is completely loaded.
  102537. * @returns a promise that resolves when the asset is completely loaded.
  102538. */
  102539. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  102540. var _this = this;
  102541. return new Promise(function (resolve) {
  102542. _this.onCompleteObservable.addOnce(function () {
  102543. resolve();
  102544. });
  102545. });
  102546. };
  102547. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  102548. /**
  102549. * The loader state or null if the loader is not active.
  102550. */
  102551. get: function () {
  102552. return this._loader ? this._loader.state : null;
  102553. },
  102554. enumerable: true,
  102555. configurable: true
  102556. });
  102557. /**
  102558. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  102559. */
  102560. GLTFFileLoader.prototype.dispose = function () {
  102561. if (this._loader) {
  102562. this._loader.dispose();
  102563. this._loader = null;
  102564. }
  102565. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  102566. this.onMeshLoadedObservable.clear();
  102567. this.onTextureLoadedObservable.clear();
  102568. this.onMaterialLoadedObservable.clear();
  102569. this.onCameraLoadedObservable.clear();
  102570. this.onCompleteObservable.clear();
  102571. this.onExtensionLoadedObservable.clear();
  102572. this.onDisposeObservable.notifyObservers(this);
  102573. this.onDisposeObservable.clear();
  102574. };
  102575. /**
  102576. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  102577. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  102578. * @param scene the scene the meshes should be added to
  102579. * @param data the glTF data to load
  102580. * @param rootUrl root url to load from
  102581. * @param onProgress event that fires when loading progress has occured
  102582. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  102583. */
  102584. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  102585. var _this = this;
  102586. return Promise.resolve().then(function () {
  102587. var loaderData = _this._parse(data);
  102588. _this._loader = _this._getLoader(loaderData);
  102589. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  102590. });
  102591. };
  102592. /**
  102593. * Imports all objects from the loaded glTF data and adds them to the scene
  102594. * @param scene the scene the objects should be added to
  102595. * @param data the glTF data to load
  102596. * @param rootUrl root url to load from
  102597. * @param onProgress event that fires when loading progress has occured
  102598. * @returns a promise which completes when objects have been loaded to the scene
  102599. */
  102600. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  102601. var _this = this;
  102602. return Promise.resolve().then(function () {
  102603. var loaderData = _this._parse(data);
  102604. _this._loader = _this._getLoader(loaderData);
  102605. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  102606. });
  102607. };
  102608. /**
  102609. * Load into an asset container.
  102610. * @param scene The scene to load into
  102611. * @param data The data to import
  102612. * @param rootUrl The root url for scene and resources
  102613. * @param onProgress The callback when the load progresses
  102614. * @returns The loaded asset container
  102615. */
  102616. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  102617. var _this = this;
  102618. return Promise.resolve().then(function () {
  102619. var loaderData = _this._parse(data);
  102620. _this._loader = _this._getLoader(loaderData);
  102621. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  102622. var container = new BABYLON.AssetContainer(scene);
  102623. Array.prototype.push.apply(container.meshes, result.meshes);
  102624. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  102625. Array.prototype.push.apply(container.skeletons, result.skeletons);
  102626. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  102627. container.removeAllFromScene();
  102628. return container;
  102629. });
  102630. });
  102631. };
  102632. /**
  102633. * If the data string can be loaded directly.
  102634. * @param data string contianing the file data
  102635. * @returns if the data can be loaded directly
  102636. */
  102637. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  102638. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  102639. };
  102640. /**
  102641. * Instantiates a glTF file loader plugin.
  102642. * @returns the created plugin
  102643. */
  102644. GLTFFileLoader.prototype.createPlugin = function () {
  102645. return new GLTFFileLoader();
  102646. };
  102647. GLTFFileLoader.prototype._parse = function (data) {
  102648. var parsedData;
  102649. if (data instanceof ArrayBuffer) {
  102650. parsedData = GLTFFileLoader._parseBinary(data);
  102651. }
  102652. else {
  102653. parsedData = {
  102654. json: JSON.parse(data),
  102655. bin: null
  102656. };
  102657. }
  102658. this.onParsedObservable.notifyObservers(parsedData);
  102659. this.onParsedObservable.clear();
  102660. return parsedData;
  102661. };
  102662. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  102663. var _this = this;
  102664. var loaderVersion = { major: 2, minor: 0 };
  102665. var asset = loaderData.json.asset || {};
  102666. var version = GLTFFileLoader._parseVersion(asset.version);
  102667. if (!version) {
  102668. throw new Error("Invalid version: " + asset.version);
  102669. }
  102670. if (asset.minVersion !== undefined) {
  102671. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  102672. if (!minVersion) {
  102673. throw new Error("Invalid minimum version: " + asset.minVersion);
  102674. }
  102675. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  102676. throw new Error("Incompatible minimum version: " + asset.minVersion);
  102677. }
  102678. }
  102679. var createLoaders = {
  102680. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  102681. 2: GLTFFileLoader.CreateGLTFLoaderV2
  102682. };
  102683. var createLoader = createLoaders[version.major];
  102684. if (!createLoader) {
  102685. throw new Error("Unsupported version: " + asset.version);
  102686. }
  102687. var loader = createLoader();
  102688. loader.coordinateSystemMode = this.coordinateSystemMode;
  102689. loader.animationStartMode = this.animationStartMode;
  102690. loader.compileMaterials = this.compileMaterials;
  102691. loader.useClipPlane = this.useClipPlane;
  102692. loader.compileShadowGenerators = this.compileShadowGenerators;
  102693. loader.transparencyAsCoverage = this.transparencyAsCoverage;
  102694. loader._normalizeAnimationGroupsToBeginAtZero = this._normalizeAnimationGroupsToBeginAtZero;
  102695. loader.preprocessUrlAsync = this.preprocessUrlAsync;
  102696. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  102697. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  102698. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  102699. loader.onCameraLoadedObservable.add(function (camera) { return _this.onCameraLoadedObservable.notifyObservers(camera); });
  102700. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  102701. loader.onCompleteObservable.add(function () {
  102702. _this.onMeshLoadedObservable.clear();
  102703. _this.onTextureLoadedObservable.clear();
  102704. _this.onMaterialLoadedObservable.clear();
  102705. _this.onCameraLoadedObservable.clear();
  102706. _this.onExtensionLoadedObservable.clear();
  102707. _this.onCompleteObservable.notifyObservers(_this);
  102708. _this.onCompleteObservable.clear();
  102709. });
  102710. return loader;
  102711. };
  102712. GLTFFileLoader._parseBinary = function (data) {
  102713. var Binary = {
  102714. Magic: 0x46546C67
  102715. };
  102716. var binaryReader = new BinaryReader(data);
  102717. var magic = binaryReader.readUint32();
  102718. if (magic !== Binary.Magic) {
  102719. throw new Error("Unexpected magic: " + magic);
  102720. }
  102721. var version = binaryReader.readUint32();
  102722. switch (version) {
  102723. case 1: return GLTFFileLoader._parseV1(binaryReader);
  102724. case 2: return GLTFFileLoader._parseV2(binaryReader);
  102725. }
  102726. throw new Error("Unsupported version: " + version);
  102727. };
  102728. GLTFFileLoader._parseV1 = function (binaryReader) {
  102729. var ContentFormat = {
  102730. JSON: 0
  102731. };
  102732. var length = binaryReader.readUint32();
  102733. if (length != binaryReader.getLength()) {
  102734. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  102735. }
  102736. var contentLength = binaryReader.readUint32();
  102737. var contentFormat = binaryReader.readUint32();
  102738. var content;
  102739. switch (contentFormat) {
  102740. case ContentFormat.JSON: {
  102741. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  102742. break;
  102743. }
  102744. default: {
  102745. throw new Error("Unexpected content format: " + contentFormat);
  102746. }
  102747. }
  102748. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  102749. var body = binaryReader.readUint8Array(bytesRemaining);
  102750. return {
  102751. json: content,
  102752. bin: body
  102753. };
  102754. };
  102755. GLTFFileLoader._parseV2 = function (binaryReader) {
  102756. var ChunkFormat = {
  102757. JSON: 0x4E4F534A,
  102758. BIN: 0x004E4942
  102759. };
  102760. var length = binaryReader.readUint32();
  102761. if (length !== binaryReader.getLength()) {
  102762. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  102763. }
  102764. // JSON chunk
  102765. var chunkLength = binaryReader.readUint32();
  102766. var chunkFormat = binaryReader.readUint32();
  102767. if (chunkFormat !== ChunkFormat.JSON) {
  102768. throw new Error("First chunk format is not JSON");
  102769. }
  102770. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  102771. // Look for BIN chunk
  102772. var bin = null;
  102773. while (binaryReader.getPosition() < binaryReader.getLength()) {
  102774. var chunkLength_1 = binaryReader.readUint32();
  102775. var chunkFormat_1 = binaryReader.readUint32();
  102776. switch (chunkFormat_1) {
  102777. case ChunkFormat.JSON: {
  102778. throw new Error("Unexpected JSON chunk");
  102779. }
  102780. case ChunkFormat.BIN: {
  102781. bin = binaryReader.readUint8Array(chunkLength_1);
  102782. break;
  102783. }
  102784. default: {
  102785. // ignore unrecognized chunkFormat
  102786. binaryReader.skipBytes(chunkLength_1);
  102787. break;
  102788. }
  102789. }
  102790. }
  102791. return {
  102792. json: json,
  102793. bin: bin
  102794. };
  102795. };
  102796. GLTFFileLoader._parseVersion = function (version) {
  102797. if (version === "1.0" || version === "1.0.1") {
  102798. return {
  102799. major: 1,
  102800. minor: 0
  102801. };
  102802. }
  102803. var match = (version + "").match(/^(\d+)\.(\d+)/);
  102804. if (!match) {
  102805. return null;
  102806. }
  102807. return {
  102808. major: parseInt(match[1]),
  102809. minor: parseInt(match[2])
  102810. };
  102811. };
  102812. GLTFFileLoader._compareVersion = function (a, b) {
  102813. if (a.major > b.major)
  102814. return 1;
  102815. if (a.major < b.major)
  102816. return -1;
  102817. if (a.minor > b.minor)
  102818. return 1;
  102819. if (a.minor < b.minor)
  102820. return -1;
  102821. return 0;
  102822. };
  102823. GLTFFileLoader._decodeBufferToText = function (buffer) {
  102824. var result = "";
  102825. var length = buffer.byteLength;
  102826. for (var i = 0; i < length; i++) {
  102827. result += String.fromCharCode(buffer[i]);
  102828. }
  102829. return result;
  102830. };
  102831. // #endregion
  102832. // #region V1 options
  102833. /**
  102834. * Set this property to false to disable incremental loading which delays the loader from calling the success callback until after loading the meshes and shaders.
  102835. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  102836. * Defaults to true.
  102837. */
  102838. GLTFFileLoader.IncrementalLoading = true;
  102839. /**
  102840. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  102841. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  102842. */
  102843. GLTFFileLoader.HomogeneousCoordinates = false;
  102844. return GLTFFileLoader;
  102845. }());
  102846. BABYLON.GLTFFileLoader = GLTFFileLoader;
  102847. var BinaryReader = /** @class */ (function () {
  102848. function BinaryReader(arrayBuffer) {
  102849. this._arrayBuffer = arrayBuffer;
  102850. this._dataView = new DataView(arrayBuffer);
  102851. this._byteOffset = 0;
  102852. }
  102853. BinaryReader.prototype.getPosition = function () {
  102854. return this._byteOffset;
  102855. };
  102856. BinaryReader.prototype.getLength = function () {
  102857. return this._arrayBuffer.byteLength;
  102858. };
  102859. BinaryReader.prototype.readUint32 = function () {
  102860. var value = this._dataView.getUint32(this._byteOffset, true);
  102861. this._byteOffset += 4;
  102862. return value;
  102863. };
  102864. BinaryReader.prototype.readUint8Array = function (length) {
  102865. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  102866. this._byteOffset += length;
  102867. return value;
  102868. };
  102869. BinaryReader.prototype.skipBytes = function (length) {
  102870. this._byteOffset += length;
  102871. };
  102872. return BinaryReader;
  102873. }());
  102874. if (BABYLON.SceneLoader) {
  102875. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  102876. }
  102877. })(BABYLON || (BABYLON = {}));
  102878. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  102879. var BABYLON;
  102880. (function (BABYLON) {
  102881. var GLTF1;
  102882. (function (GLTF1) {
  102883. /**
  102884. * Enums
  102885. */
  102886. var EComponentType;
  102887. (function (EComponentType) {
  102888. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  102889. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  102890. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  102891. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  102892. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  102893. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  102894. var EShaderType;
  102895. (function (EShaderType) {
  102896. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  102897. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  102898. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  102899. var EParameterType;
  102900. (function (EParameterType) {
  102901. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  102902. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  102903. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  102904. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  102905. EParameterType[EParameterType["INT"] = 5124] = "INT";
  102906. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  102907. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  102908. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  102909. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  102910. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  102911. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  102912. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  102913. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  102914. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  102915. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  102916. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  102917. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  102918. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  102919. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  102920. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  102921. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  102922. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  102923. var ETextureWrapMode;
  102924. (function (ETextureWrapMode) {
  102925. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  102926. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  102927. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  102928. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  102929. var ETextureFilterType;
  102930. (function (ETextureFilterType) {
  102931. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  102932. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  102933. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  102934. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  102935. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  102936. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  102937. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  102938. var ETextureFormat;
  102939. (function (ETextureFormat) {
  102940. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  102941. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  102942. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  102943. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  102944. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  102945. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  102946. var ECullingType;
  102947. (function (ECullingType) {
  102948. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  102949. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  102950. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  102951. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  102952. var EBlendingFunction;
  102953. (function (EBlendingFunction) {
  102954. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  102955. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  102956. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  102957. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  102958. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  102959. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  102960. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  102961. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  102962. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  102963. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  102964. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  102965. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  102966. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  102967. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  102968. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  102969. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  102970. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  102971. })(BABYLON || (BABYLON = {}));
  102972. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  102973. var BABYLON;
  102974. (function (BABYLON) {
  102975. var GLTF1;
  102976. (function (GLTF1) {
  102977. /**
  102978. * Tokenizer. Used for shaders compatibility
  102979. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  102980. */
  102981. var ETokenType;
  102982. (function (ETokenType) {
  102983. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  102984. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  102985. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  102986. })(ETokenType || (ETokenType = {}));
  102987. var Tokenizer = /** @class */ (function () {
  102988. function Tokenizer(toParse) {
  102989. this._pos = 0;
  102990. this.currentToken = ETokenType.UNKNOWN;
  102991. this.currentIdentifier = "";
  102992. this.currentString = "";
  102993. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  102994. this._toParse = toParse;
  102995. this._maxPos = toParse.length;
  102996. }
  102997. Tokenizer.prototype.getNextToken = function () {
  102998. if (this.isEnd())
  102999. return ETokenType.END_OF_INPUT;
  103000. this.currentString = this.read();
  103001. this.currentToken = ETokenType.UNKNOWN;
  103002. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  103003. this.currentToken = ETokenType.IDENTIFIER;
  103004. this.currentIdentifier = this.currentString;
  103005. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  103006. this.currentIdentifier += this.currentString;
  103007. this.forward();
  103008. }
  103009. }
  103010. return this.currentToken;
  103011. };
  103012. Tokenizer.prototype.peek = function () {
  103013. return this._toParse[this._pos];
  103014. };
  103015. Tokenizer.prototype.read = function () {
  103016. return this._toParse[this._pos++];
  103017. };
  103018. Tokenizer.prototype.forward = function () {
  103019. this._pos++;
  103020. };
  103021. Tokenizer.prototype.isEnd = function () {
  103022. return this._pos >= this._maxPos;
  103023. };
  103024. return Tokenizer;
  103025. }());
  103026. /**
  103027. * Values
  103028. */
  103029. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  103030. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  103031. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  103032. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  103033. /**
  103034. * Parse
  103035. */
  103036. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  103037. for (var buf in parsedBuffers) {
  103038. var parsedBuffer = parsedBuffers[buf];
  103039. gltfRuntime.buffers[buf] = parsedBuffer;
  103040. gltfRuntime.buffersCount++;
  103041. }
  103042. };
  103043. var parseShaders = function (parsedShaders, gltfRuntime) {
  103044. for (var sha in parsedShaders) {
  103045. var parsedShader = parsedShaders[sha];
  103046. gltfRuntime.shaders[sha] = parsedShader;
  103047. gltfRuntime.shaderscount++;
  103048. }
  103049. };
  103050. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  103051. for (var object in parsedObjects) {
  103052. var parsedObject = parsedObjects[object];
  103053. gltfRuntime[runtimeProperty][object] = parsedObject;
  103054. }
  103055. };
  103056. /**
  103057. * Utils
  103058. */
  103059. var normalizeUVs = function (buffer) {
  103060. if (!buffer) {
  103061. return;
  103062. }
  103063. for (var i = 0; i < buffer.length / 2; i++) {
  103064. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  103065. }
  103066. };
  103067. var getAttribute = function (attributeParameter) {
  103068. if (attributeParameter.semantic === "NORMAL") {
  103069. return "normal";
  103070. }
  103071. else if (attributeParameter.semantic === "POSITION") {
  103072. return "position";
  103073. }
  103074. else if (attributeParameter.semantic === "JOINT") {
  103075. return "matricesIndices";
  103076. }
  103077. else if (attributeParameter.semantic === "WEIGHT") {
  103078. return "matricesWeights";
  103079. }
  103080. else if (attributeParameter.semantic === "COLOR") {
  103081. return "color";
  103082. }
  103083. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  103084. var channel = Number(attributeParameter.semantic.split("_")[1]);
  103085. return "uv" + (channel === 0 ? "" : channel + 1);
  103086. }
  103087. return null;
  103088. };
  103089. /**
  103090. * Loads and creates animations
  103091. */
  103092. var loadAnimations = function (gltfRuntime) {
  103093. for (var anim in gltfRuntime.animations) {
  103094. var animation = gltfRuntime.animations[anim];
  103095. if (!animation.channels || !animation.samplers) {
  103096. continue;
  103097. }
  103098. var lastAnimation = null;
  103099. for (var i = 0; i < animation.channels.length; i++) {
  103100. // Get parameters and load buffers
  103101. var channel = animation.channels[i];
  103102. var sampler = animation.samplers[channel.sampler];
  103103. if (!sampler) {
  103104. continue;
  103105. }
  103106. var inputData = null;
  103107. var outputData = null;
  103108. if (animation.parameters) {
  103109. inputData = animation.parameters[sampler.input];
  103110. outputData = animation.parameters[sampler.output];
  103111. }
  103112. else {
  103113. inputData = sampler.input;
  103114. outputData = sampler.output;
  103115. }
  103116. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  103117. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  103118. var targetID = channel.target.id;
  103119. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  103120. if (targetNode === null) {
  103121. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  103122. }
  103123. if (targetNode === null) {
  103124. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  103125. continue;
  103126. }
  103127. var isBone = targetNode instanceof BABYLON.Bone;
  103128. // Get target path (position, rotation or scaling)
  103129. var targetPath = channel.target.path;
  103130. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  103131. if (targetPathIndex !== -1) {
  103132. targetPath = babylonAnimationPaths[targetPathIndex];
  103133. }
  103134. // Determine animation type
  103135. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  103136. if (!isBone) {
  103137. if (targetPath === "rotationQuaternion") {
  103138. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  103139. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  103140. }
  103141. else {
  103142. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  103143. }
  103144. }
  103145. // Create animation and key frames
  103146. var babylonAnimation = null;
  103147. var keys = [];
  103148. var arrayOffset = 0;
  103149. var modifyKey = false;
  103150. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  103151. babylonAnimation = lastAnimation;
  103152. modifyKey = true;
  103153. }
  103154. if (!modifyKey) {
  103155. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  103156. }
  103157. // For each frame
  103158. for (var j = 0; j < bufferInput.length; j++) {
  103159. var value = null;
  103160. if (targetPath === "rotationQuaternion") { // VEC4
  103161. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  103162. arrayOffset += 4;
  103163. }
  103164. else { // Position and scaling are VEC3
  103165. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  103166. arrayOffset += 3;
  103167. }
  103168. if (isBone) {
  103169. var bone = targetNode;
  103170. var translation = BABYLON.Vector3.Zero();
  103171. var rotationQuaternion = new BABYLON.Quaternion();
  103172. var scaling = BABYLON.Vector3.Zero();
  103173. // Warning on decompose
  103174. var mat = bone.getBaseMatrix();
  103175. if (modifyKey && lastAnimation) {
  103176. mat = lastAnimation.getKeys()[j].value;
  103177. }
  103178. mat.decompose(scaling, rotationQuaternion, translation);
  103179. if (targetPath === "position") {
  103180. translation = value;
  103181. }
  103182. else if (targetPath === "rotationQuaternion") {
  103183. rotationQuaternion = value;
  103184. }
  103185. else {
  103186. scaling = value;
  103187. }
  103188. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  103189. }
  103190. if (!modifyKey) {
  103191. keys.push({
  103192. frame: bufferInput[j],
  103193. value: value
  103194. });
  103195. }
  103196. else if (lastAnimation) {
  103197. lastAnimation.getKeys()[j].value = value;
  103198. }
  103199. }
  103200. // Finish
  103201. if (!modifyKey && babylonAnimation) {
  103202. babylonAnimation.setKeys(keys);
  103203. targetNode.animations.push(babylonAnimation);
  103204. }
  103205. lastAnimation = babylonAnimation;
  103206. gltfRuntime.scene.stopAnimation(targetNode);
  103207. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  103208. }
  103209. }
  103210. };
  103211. /**
  103212. * Returns the bones transformation matrix
  103213. */
  103214. var configureBoneTransformation = function (node) {
  103215. var mat = null;
  103216. if (node.translation || node.rotation || node.scale) {
  103217. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  103218. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  103219. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  103220. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  103221. }
  103222. else {
  103223. mat = BABYLON.Matrix.FromArray(node.matrix);
  103224. }
  103225. return mat;
  103226. };
  103227. /**
  103228. * Returns the parent bone
  103229. */
  103230. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  103231. // Try to find
  103232. for (var i = 0; i < newSkeleton.bones.length; i++) {
  103233. if (newSkeleton.bones[i].name === jointName) {
  103234. return newSkeleton.bones[i];
  103235. }
  103236. }
  103237. // Not found, search in gltf nodes
  103238. var nodes = gltfRuntime.nodes;
  103239. for (var nde in nodes) {
  103240. var node = nodes[nde];
  103241. if (!node.jointName) {
  103242. continue;
  103243. }
  103244. var children = node.children;
  103245. for (var i = 0; i < children.length; i++) {
  103246. var child = gltfRuntime.nodes[children[i]];
  103247. if (!child.jointName) {
  103248. continue;
  103249. }
  103250. if (child.jointName === jointName) {
  103251. var mat = configureBoneTransformation(node);
  103252. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  103253. bone.id = nde;
  103254. return bone;
  103255. }
  103256. }
  103257. }
  103258. return null;
  103259. };
  103260. /**
  103261. * Returns the appropriate root node
  103262. */
  103263. var getNodeToRoot = function (nodesToRoot, id) {
  103264. for (var i = 0; i < nodesToRoot.length; i++) {
  103265. var nodeToRoot = nodesToRoot[i];
  103266. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  103267. var child = nodeToRoot.node.children[j];
  103268. if (child === id) {
  103269. return nodeToRoot.bone;
  103270. }
  103271. }
  103272. }
  103273. return null;
  103274. };
  103275. /**
  103276. * Returns the node with the joint name
  103277. */
  103278. var getJointNode = function (gltfRuntime, jointName) {
  103279. var nodes = gltfRuntime.nodes;
  103280. var node = nodes[jointName];
  103281. if (node) {
  103282. return {
  103283. node: node,
  103284. id: jointName
  103285. };
  103286. }
  103287. for (var nde in nodes) {
  103288. node = nodes[nde];
  103289. if (node.jointName === jointName) {
  103290. return {
  103291. node: node,
  103292. id: nde
  103293. };
  103294. }
  103295. }
  103296. return null;
  103297. };
  103298. /**
  103299. * Checks if a nodes is in joints
  103300. */
  103301. var nodeIsInJoints = function (skins, id) {
  103302. for (var i = 0; i < skins.jointNames.length; i++) {
  103303. if (skins.jointNames[i] === id) {
  103304. return true;
  103305. }
  103306. }
  103307. return false;
  103308. };
  103309. /**
  103310. * Fills the nodes to root for bones and builds hierarchy
  103311. */
  103312. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  103313. // Creates nodes for root
  103314. for (var nde in gltfRuntime.nodes) {
  103315. var node = gltfRuntime.nodes[nde];
  103316. var id = nde;
  103317. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  103318. continue;
  103319. }
  103320. // Create node to root bone
  103321. var mat = configureBoneTransformation(node);
  103322. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  103323. bone.id = id;
  103324. nodesToRoot.push({ bone: bone, node: node, id: id });
  103325. }
  103326. // Parenting
  103327. for (var i = 0; i < nodesToRoot.length; i++) {
  103328. var nodeToRoot = nodesToRoot[i];
  103329. var children = nodeToRoot.node.children;
  103330. for (var j = 0; j < children.length; j++) {
  103331. var child = null;
  103332. for (var k = 0; k < nodesToRoot.length; k++) {
  103333. if (nodesToRoot[k].id === children[j]) {
  103334. child = nodesToRoot[k];
  103335. break;
  103336. }
  103337. }
  103338. if (child) {
  103339. child.bone._parent = nodeToRoot.bone;
  103340. nodeToRoot.bone.children.push(child.bone);
  103341. }
  103342. }
  103343. }
  103344. };
  103345. /**
  103346. * Imports a skeleton
  103347. */
  103348. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  103349. if (!newSkeleton) {
  103350. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  103351. }
  103352. if (!skins.babylonSkeleton) {
  103353. return newSkeleton;
  103354. }
  103355. // Find the root bones
  103356. var nodesToRoot = [];
  103357. var nodesToRootToAdd = [];
  103358. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  103359. newSkeleton.bones = [];
  103360. // Joints
  103361. for (var i = 0; i < skins.jointNames.length; i++) {
  103362. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  103363. if (!jointNode) {
  103364. continue;
  103365. }
  103366. var node = jointNode.node;
  103367. if (!node) {
  103368. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  103369. continue;
  103370. }
  103371. var id = jointNode.id;
  103372. // Optimize, if the bone already exists...
  103373. var existingBone = gltfRuntime.scene.getBoneByID(id);
  103374. if (existingBone) {
  103375. newSkeleton.bones.push(existingBone);
  103376. continue;
  103377. }
  103378. // Search for parent bone
  103379. var foundBone = false;
  103380. var parentBone = null;
  103381. for (var j = 0; j < i; j++) {
  103382. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  103383. if (!jointNode_1) {
  103384. continue;
  103385. }
  103386. var joint = jointNode_1.node;
  103387. if (!joint) {
  103388. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  103389. continue;
  103390. }
  103391. var children = joint.children;
  103392. if (!children) {
  103393. continue;
  103394. }
  103395. foundBone = false;
  103396. for (var k = 0; k < children.length; k++) {
  103397. if (children[k] === id) {
  103398. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  103399. foundBone = true;
  103400. break;
  103401. }
  103402. }
  103403. if (foundBone) {
  103404. break;
  103405. }
  103406. }
  103407. // Create bone
  103408. var mat = configureBoneTransformation(node);
  103409. if (!parentBone && nodesToRoot.length > 0) {
  103410. parentBone = getNodeToRoot(nodesToRoot, id);
  103411. if (parentBone) {
  103412. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  103413. nodesToRootToAdd.push(parentBone);
  103414. }
  103415. }
  103416. }
  103417. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  103418. bone.id = id;
  103419. }
  103420. // Polish
  103421. var bones = newSkeleton.bones;
  103422. newSkeleton.bones = [];
  103423. for (var i = 0; i < skins.jointNames.length; i++) {
  103424. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  103425. if (!jointNode) {
  103426. continue;
  103427. }
  103428. for (var j = 0; j < bones.length; j++) {
  103429. if (bones[j].id === jointNode.id) {
  103430. newSkeleton.bones.push(bones[j]);
  103431. break;
  103432. }
  103433. }
  103434. }
  103435. newSkeleton.prepare();
  103436. // Finish
  103437. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  103438. newSkeleton.bones.push(nodesToRootToAdd[i]);
  103439. }
  103440. return newSkeleton;
  103441. };
  103442. /**
  103443. * Imports a mesh and its geometries
  103444. */
  103445. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  103446. if (!newMesh) {
  103447. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  103448. newMesh.id = id;
  103449. }
  103450. if (!node.babylonNode) {
  103451. return newMesh;
  103452. }
  103453. var subMaterials = [];
  103454. var vertexData = null;
  103455. var verticesStarts = new Array();
  103456. var verticesCounts = new Array();
  103457. var indexStarts = new Array();
  103458. var indexCounts = new Array();
  103459. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  103460. var meshID = meshes[meshIndex];
  103461. var mesh = gltfRuntime.meshes[meshID];
  103462. if (!mesh) {
  103463. continue;
  103464. }
  103465. // Positions, normals and UVs
  103466. for (var i = 0; i < mesh.primitives.length; i++) {
  103467. // Temporary vertex data
  103468. var tempVertexData = new BABYLON.VertexData();
  103469. var primitive = mesh.primitives[i];
  103470. if (primitive.mode !== 4) {
  103471. // continue;
  103472. }
  103473. var attributes = primitive.attributes;
  103474. var accessor = null;
  103475. var buffer = null;
  103476. // Set positions, normal and uvs
  103477. for (var semantic in attributes) {
  103478. // Link accessor and buffer view
  103479. accessor = gltfRuntime.accessors[attributes[semantic]];
  103480. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  103481. if (semantic === "NORMAL") {
  103482. tempVertexData.normals = new Float32Array(buffer.length);
  103483. tempVertexData.normals.set(buffer);
  103484. }
  103485. else if (semantic === "POSITION") {
  103486. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  103487. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  103488. for (var j = 0; j < buffer.length; j += 4) {
  103489. tempVertexData.positions[j] = buffer[j];
  103490. tempVertexData.positions[j + 1] = buffer[j + 1];
  103491. tempVertexData.positions[j + 2] = buffer[j + 2];
  103492. }
  103493. }
  103494. else {
  103495. tempVertexData.positions = new Float32Array(buffer.length);
  103496. tempVertexData.positions.set(buffer);
  103497. }
  103498. verticesCounts.push(tempVertexData.positions.length);
  103499. }
  103500. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  103501. var channel = Number(semantic.split("_")[1]);
  103502. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  103503. var uvs = new Float32Array(buffer.length);
  103504. uvs.set(buffer);
  103505. normalizeUVs(uvs);
  103506. tempVertexData.set(uvs, uvKind);
  103507. }
  103508. else if (semantic === "JOINT") {
  103509. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  103510. tempVertexData.matricesIndices.set(buffer);
  103511. }
  103512. else if (semantic === "WEIGHT") {
  103513. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  103514. tempVertexData.matricesWeights.set(buffer);
  103515. }
  103516. else if (semantic === "COLOR") {
  103517. tempVertexData.colors = new Float32Array(buffer.length);
  103518. tempVertexData.colors.set(buffer);
  103519. }
  103520. }
  103521. // Indices
  103522. accessor = gltfRuntime.accessors[primitive.indices];
  103523. if (accessor) {
  103524. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  103525. tempVertexData.indices = new Int32Array(buffer.length);
  103526. tempVertexData.indices.set(buffer);
  103527. indexCounts.push(tempVertexData.indices.length);
  103528. }
  103529. else {
  103530. // Set indices on the fly
  103531. var indices = [];
  103532. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  103533. indices.push(j);
  103534. }
  103535. tempVertexData.indices = new Int32Array(indices);
  103536. indexCounts.push(tempVertexData.indices.length);
  103537. }
  103538. if (!vertexData) {
  103539. vertexData = tempVertexData;
  103540. }
  103541. else {
  103542. vertexData.merge(tempVertexData);
  103543. }
  103544. // Sub material
  103545. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  103546. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  103547. // Update vertices start and index start
  103548. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  103549. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  103550. }
  103551. }
  103552. var material;
  103553. if (subMaterials.length > 1) {
  103554. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  103555. material.subMaterials = subMaterials;
  103556. }
  103557. else {
  103558. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  103559. }
  103560. if (subMaterials.length === 1) {
  103561. material = subMaterials[0];
  103562. }
  103563. if (!newMesh.material) {
  103564. newMesh.material = material;
  103565. }
  103566. // Apply geometry
  103567. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  103568. newMesh.computeWorldMatrix(true);
  103569. // Apply submeshes
  103570. newMesh.subMeshes = [];
  103571. var index = 0;
  103572. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  103573. var meshID = meshes[meshIndex];
  103574. var mesh = gltfRuntime.meshes[meshID];
  103575. if (!mesh) {
  103576. continue;
  103577. }
  103578. for (var i = 0; i < mesh.primitives.length; i++) {
  103579. if (mesh.primitives[i].mode !== 4) {
  103580. //continue;
  103581. }
  103582. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  103583. index++;
  103584. }
  103585. }
  103586. // Finish
  103587. return newMesh;
  103588. };
  103589. /**
  103590. * Configure node transformation from position, rotation and scaling
  103591. */
  103592. var configureNode = function (newNode, position, rotation, scaling) {
  103593. if (newNode.position) {
  103594. newNode.position = position;
  103595. }
  103596. if (newNode.rotationQuaternion || newNode.rotation) {
  103597. newNode.rotationQuaternion = rotation;
  103598. }
  103599. if (newNode.scaling) {
  103600. newNode.scaling = scaling;
  103601. }
  103602. };
  103603. /**
  103604. * Configures node from transformation matrix
  103605. */
  103606. var configureNodeFromMatrix = function (newNode, node, parent) {
  103607. if (node.matrix) {
  103608. var position = new BABYLON.Vector3(0, 0, 0);
  103609. var rotation = new BABYLON.Quaternion();
  103610. var scaling = new BABYLON.Vector3(0, 0, 0);
  103611. var mat = BABYLON.Matrix.FromArray(node.matrix);
  103612. mat.decompose(scaling, rotation, position);
  103613. configureNode(newNode, position, rotation, scaling);
  103614. }
  103615. else if (node.translation && node.rotation && node.scale) {
  103616. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  103617. }
  103618. newNode.computeWorldMatrix(true);
  103619. };
  103620. /**
  103621. * Imports a node
  103622. */
  103623. var importNode = function (gltfRuntime, node, id, parent) {
  103624. var lastNode = null;
  103625. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  103626. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  103627. return null;
  103628. }
  103629. }
  103630. // Meshes
  103631. if (node.skin) {
  103632. if (node.meshes) {
  103633. var skin = gltfRuntime.skins[node.skin];
  103634. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  103635. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  103636. if (newMesh.skeleton === null) {
  103637. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  103638. if (!skin.babylonSkeleton) {
  103639. skin.babylonSkeleton = newMesh.skeleton;
  103640. }
  103641. }
  103642. lastNode = newMesh;
  103643. }
  103644. }
  103645. else if (node.meshes) {
  103646. /**
  103647. * Improve meshes property
  103648. */
  103649. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  103650. lastNode = newMesh;
  103651. }
  103652. // Lights
  103653. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  103654. var light = gltfRuntime.lights[node.light];
  103655. if (light) {
  103656. if (light.type === "ambient") {
  103657. var ambienLight = light[light.type];
  103658. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  103659. hemiLight.name = node.name || "";
  103660. if (ambienLight.color) {
  103661. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  103662. }
  103663. lastNode = hemiLight;
  103664. }
  103665. else if (light.type === "directional") {
  103666. var directionalLight = light[light.type];
  103667. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  103668. dirLight.name = node.name || "";
  103669. if (directionalLight.color) {
  103670. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  103671. }
  103672. lastNode = dirLight;
  103673. }
  103674. else if (light.type === "point") {
  103675. var pointLight = light[light.type];
  103676. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  103677. ptLight.name = node.name || "";
  103678. if (pointLight.color) {
  103679. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  103680. }
  103681. lastNode = ptLight;
  103682. }
  103683. else if (light.type === "spot") {
  103684. var spotLight = light[light.type];
  103685. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  103686. spLight.name = node.name || "";
  103687. if (spotLight.color) {
  103688. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  103689. }
  103690. if (spotLight.fallOfAngle) {
  103691. spLight.angle = spotLight.fallOfAngle;
  103692. }
  103693. if (spotLight.fallOffExponent) {
  103694. spLight.exponent = spotLight.fallOffExponent;
  103695. }
  103696. lastNode = spLight;
  103697. }
  103698. }
  103699. }
  103700. // Cameras
  103701. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  103702. var camera = gltfRuntime.cameras[node.camera];
  103703. if (camera) {
  103704. if (camera.type === "orthographic") {
  103705. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  103706. orthoCamera.name = node.name || "";
  103707. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  103708. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  103709. lastNode = orthoCamera;
  103710. }
  103711. else if (camera.type === "perspective") {
  103712. var perspectiveCamera = camera[camera.type];
  103713. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  103714. persCamera.name = node.name || "";
  103715. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  103716. if (!perspectiveCamera.aspectRatio) {
  103717. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  103718. }
  103719. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  103720. persCamera.maxZ = perspectiveCamera.zfar;
  103721. persCamera.minZ = perspectiveCamera.znear;
  103722. }
  103723. lastNode = persCamera;
  103724. }
  103725. }
  103726. }
  103727. // Empty node
  103728. if (!node.jointName) {
  103729. if (node.babylonNode) {
  103730. return node.babylonNode;
  103731. }
  103732. else if (lastNode === null) {
  103733. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  103734. node.babylonNode = dummy;
  103735. lastNode = dummy;
  103736. }
  103737. }
  103738. if (lastNode !== null) {
  103739. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  103740. configureNodeFromMatrix(lastNode, node, parent);
  103741. }
  103742. else {
  103743. var translation = node.translation || [0, 0, 0];
  103744. var rotation = node.rotation || [0, 0, 0, 1];
  103745. var scale = node.scale || [1, 1, 1];
  103746. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  103747. }
  103748. lastNode.updateCache(true);
  103749. node.babylonNode = lastNode;
  103750. }
  103751. return lastNode;
  103752. };
  103753. /**
  103754. * Traverses nodes and creates them
  103755. */
  103756. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  103757. if (meshIncluded === void 0) { meshIncluded = false; }
  103758. var node = gltfRuntime.nodes[id];
  103759. var newNode = null;
  103760. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  103761. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  103762. meshIncluded = true;
  103763. }
  103764. else {
  103765. meshIncluded = false;
  103766. }
  103767. }
  103768. else {
  103769. meshIncluded = true;
  103770. }
  103771. if (!node.jointName && meshIncluded) {
  103772. newNode = importNode(gltfRuntime, node, id, parent);
  103773. if (newNode !== null) {
  103774. newNode.id = id;
  103775. newNode.parent = parent;
  103776. }
  103777. }
  103778. if (node.children) {
  103779. for (var i = 0; i < node.children.length; i++) {
  103780. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  103781. }
  103782. }
  103783. };
  103784. /**
  103785. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  103786. */
  103787. var postLoad = function (gltfRuntime) {
  103788. // Nodes
  103789. var currentScene = gltfRuntime.currentScene;
  103790. if (currentScene) {
  103791. for (var i = 0; i < currentScene.nodes.length; i++) {
  103792. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  103793. }
  103794. }
  103795. else {
  103796. for (var thing in gltfRuntime.scenes) {
  103797. currentScene = gltfRuntime.scenes[thing];
  103798. for (var i = 0; i < currentScene.nodes.length; i++) {
  103799. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  103800. }
  103801. }
  103802. }
  103803. // Set animations
  103804. loadAnimations(gltfRuntime);
  103805. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  103806. var skeleton = gltfRuntime.scene.skeletons[i];
  103807. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  103808. }
  103809. };
  103810. /**
  103811. * onBind shaderrs callback to set uniforms and matrices
  103812. */
  103813. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  103814. var materialValues = material.values || technique.parameters;
  103815. for (var unif in unTreatedUniforms) {
  103816. var uniform = unTreatedUniforms[unif];
  103817. var type = uniform.type;
  103818. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  103819. if (uniform.semantic && !uniform.source && !uniform.node) {
  103820. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  103821. }
  103822. else if (uniform.semantic && (uniform.source || uniform.node)) {
  103823. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  103824. if (source === null) {
  103825. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  103826. }
  103827. if (source === null) {
  103828. continue;
  103829. }
  103830. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  103831. }
  103832. }
  103833. else {
  103834. var value = materialValues[technique.uniforms[unif]];
  103835. if (!value) {
  103836. continue;
  103837. }
  103838. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  103839. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  103840. if (texture === null || texture === undefined) {
  103841. continue;
  103842. }
  103843. shaderMaterial.getEffect().setTexture(unif, texture);
  103844. }
  103845. else {
  103846. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  103847. }
  103848. }
  103849. }
  103850. onSuccess(shaderMaterial);
  103851. };
  103852. /**
  103853. * Prepare uniforms to send the only one time
  103854. * Loads the appropriate textures
  103855. */
  103856. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  103857. var materialValues = material.values || technique.parameters;
  103858. var techniqueUniforms = technique.uniforms;
  103859. /**
  103860. * Prepare values here (not matrices)
  103861. */
  103862. for (var unif in unTreatedUniforms) {
  103863. var uniform = unTreatedUniforms[unif];
  103864. var type = uniform.type;
  103865. var value = materialValues[techniqueUniforms[unif]];
  103866. if (value === undefined) {
  103867. // In case the value is the same for all materials
  103868. value = uniform.value;
  103869. }
  103870. if (!value) {
  103871. continue;
  103872. }
  103873. var onLoadTexture = function (uniformName) {
  103874. return function (texture) {
  103875. if (uniform.value && uniformName) {
  103876. // Static uniform
  103877. shaderMaterial.setTexture(uniformName, texture);
  103878. delete unTreatedUniforms[uniformName];
  103879. }
  103880. };
  103881. };
  103882. // Texture (sampler2D)
  103883. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  103884. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  103885. }
  103886. // Others
  103887. else {
  103888. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  103889. // Static uniform
  103890. delete unTreatedUniforms[unif];
  103891. }
  103892. }
  103893. }
  103894. };
  103895. /**
  103896. * Shader compilation failed
  103897. */
  103898. var onShaderCompileError = function (program, shaderMaterial, onError) {
  103899. return function (effect, error) {
  103900. shaderMaterial.dispose(true);
  103901. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  103902. };
  103903. };
  103904. /**
  103905. * Shader compilation success
  103906. */
  103907. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  103908. return function (_) {
  103909. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  103910. shaderMaterial.onBind = function (mesh) {
  103911. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  103912. };
  103913. };
  103914. };
  103915. /**
  103916. * Returns the appropriate uniform if already handled by babylon
  103917. */
  103918. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  103919. for (var unif in technique.uniforms) {
  103920. var uniform = technique.uniforms[unif];
  103921. var uniformParameter = technique.parameters[uniform];
  103922. if (tokenizer.currentIdentifier === unif) {
  103923. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  103924. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  103925. if (transformIndex !== -1) {
  103926. delete unTreatedUniforms[unif];
  103927. return babylonTransforms[transformIndex];
  103928. }
  103929. }
  103930. }
  103931. }
  103932. return tokenizer.currentIdentifier;
  103933. };
  103934. /**
  103935. * All shaders loaded. Create materials one by one
  103936. */
  103937. var importMaterials = function (gltfRuntime) {
  103938. // Create materials
  103939. for (var mat in gltfRuntime.materials) {
  103940. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  103941. }
  103942. };
  103943. /**
  103944. * Implementation of the base glTF spec
  103945. */
  103946. var GLTFLoaderBase = /** @class */ (function () {
  103947. function GLTFLoaderBase() {
  103948. }
  103949. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  103950. var gltfRuntime = {
  103951. extensions: {},
  103952. accessors: {},
  103953. buffers: {},
  103954. bufferViews: {},
  103955. meshes: {},
  103956. lights: {},
  103957. cameras: {},
  103958. nodes: {},
  103959. images: {},
  103960. textures: {},
  103961. shaders: {},
  103962. programs: {},
  103963. samplers: {},
  103964. techniques: {},
  103965. materials: {},
  103966. animations: {},
  103967. skins: {},
  103968. extensionsUsed: [],
  103969. scenes: {},
  103970. buffersCount: 0,
  103971. shaderscount: 0,
  103972. scene: scene,
  103973. rootUrl: rootUrl,
  103974. loadedBufferCount: 0,
  103975. loadedBufferViews: {},
  103976. loadedShaderCount: 0,
  103977. importOnlyMeshes: false,
  103978. dummyNodes: []
  103979. };
  103980. // Parse
  103981. if (parsedData.extensions) {
  103982. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  103983. }
  103984. if (parsedData.extensionsUsed) {
  103985. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  103986. }
  103987. if (parsedData.buffers) {
  103988. parseBuffers(parsedData.buffers, gltfRuntime);
  103989. }
  103990. if (parsedData.bufferViews) {
  103991. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  103992. }
  103993. if (parsedData.accessors) {
  103994. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  103995. }
  103996. if (parsedData.meshes) {
  103997. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  103998. }
  103999. if (parsedData.lights) {
  104000. parseObject(parsedData.lights, "lights", gltfRuntime);
  104001. }
  104002. if (parsedData.cameras) {
  104003. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  104004. }
  104005. if (parsedData.nodes) {
  104006. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  104007. }
  104008. if (parsedData.images) {
  104009. parseObject(parsedData.images, "images", gltfRuntime);
  104010. }
  104011. if (parsedData.textures) {
  104012. parseObject(parsedData.textures, "textures", gltfRuntime);
  104013. }
  104014. if (parsedData.shaders) {
  104015. parseShaders(parsedData.shaders, gltfRuntime);
  104016. }
  104017. if (parsedData.programs) {
  104018. parseObject(parsedData.programs, "programs", gltfRuntime);
  104019. }
  104020. if (parsedData.samplers) {
  104021. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  104022. }
  104023. if (parsedData.techniques) {
  104024. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  104025. }
  104026. if (parsedData.materials) {
  104027. parseObject(parsedData.materials, "materials", gltfRuntime);
  104028. }
  104029. if (parsedData.animations) {
  104030. parseObject(parsedData.animations, "animations", gltfRuntime);
  104031. }
  104032. if (parsedData.skins) {
  104033. parseObject(parsedData.skins, "skins", gltfRuntime);
  104034. }
  104035. if (parsedData.scenes) {
  104036. gltfRuntime.scenes = parsedData.scenes;
  104037. }
  104038. if (parsedData.scene && parsedData.scenes) {
  104039. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  104040. }
  104041. return gltfRuntime;
  104042. };
  104043. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  104044. var buffer = gltfRuntime.buffers[id];
  104045. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  104046. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  104047. }
  104048. else {
  104049. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  104050. if (request) {
  104051. onError(request.status + " " + request.statusText);
  104052. }
  104053. });
  104054. }
  104055. };
  104056. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  104057. var texture = gltfRuntime.textures[id];
  104058. if (!texture || !texture.source) {
  104059. onError("");
  104060. return;
  104061. }
  104062. if (texture.babylonTexture) {
  104063. onSuccess(null);
  104064. return;
  104065. }
  104066. var source = gltfRuntime.images[texture.source];
  104067. if (BABYLON.Tools.IsBase64(source.uri)) {
  104068. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  104069. }
  104070. else {
  104071. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  104072. if (request) {
  104073. onError(request.status + " " + request.statusText);
  104074. }
  104075. });
  104076. }
  104077. };
  104078. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  104079. var texture = gltfRuntime.textures[id];
  104080. if (texture.babylonTexture) {
  104081. onSuccess(texture.babylonTexture);
  104082. return;
  104083. }
  104084. var sampler = gltfRuntime.samplers[texture.sampler];
  104085. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  104086. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  104087. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  104088. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  104089. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  104090. var blob = new Blob([buffer]);
  104091. var blobURL = URL.createObjectURL(blob);
  104092. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  104093. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  104094. if (sampler.wrapS !== undefined) {
  104095. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  104096. }
  104097. if (sampler.wrapT !== undefined) {
  104098. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  104099. }
  104100. newTexture.name = id;
  104101. texture.babylonTexture = newTexture;
  104102. onSuccess(newTexture);
  104103. };
  104104. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  104105. var shader = gltfRuntime.shaders[id];
  104106. if (BABYLON.Tools.IsBase64(shader.uri)) {
  104107. var shaderString = atob(shader.uri.split(",")[1]);
  104108. if (onSuccess) {
  104109. onSuccess(shaderString);
  104110. }
  104111. }
  104112. else {
  104113. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  104114. if (request && onError) {
  104115. onError(request.status + " " + request.statusText);
  104116. }
  104117. });
  104118. }
  104119. };
  104120. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  104121. var material = gltfRuntime.materials[id];
  104122. if (!material.technique) {
  104123. if (onError) {
  104124. onError("No technique found.");
  104125. }
  104126. return;
  104127. }
  104128. var technique = gltfRuntime.techniques[material.technique];
  104129. if (!technique) {
  104130. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  104131. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  104132. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  104133. onSuccess(defaultMaterial);
  104134. return;
  104135. }
  104136. var program = gltfRuntime.programs[technique.program];
  104137. var states = technique.states;
  104138. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  104139. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  104140. var newVertexShader = "";
  104141. var newPixelShader = "";
  104142. var vertexTokenizer = new Tokenizer(vertexShader);
  104143. var pixelTokenizer = new Tokenizer(pixelShader);
  104144. var unTreatedUniforms = {};
  104145. var uniforms = [];
  104146. var attributes = [];
  104147. var samplers = [];
  104148. // Fill uniform, sampler2D and attributes
  104149. for (var unif in technique.uniforms) {
  104150. var uniform = technique.uniforms[unif];
  104151. var uniformParameter = technique.parameters[uniform];
  104152. unTreatedUniforms[unif] = uniformParameter;
  104153. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  104154. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  104155. if (transformIndex !== -1) {
  104156. uniforms.push(babylonTransforms[transformIndex]);
  104157. delete unTreatedUniforms[unif];
  104158. }
  104159. else {
  104160. uniforms.push(unif);
  104161. }
  104162. }
  104163. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  104164. samplers.push(unif);
  104165. }
  104166. else {
  104167. uniforms.push(unif);
  104168. }
  104169. }
  104170. for (var attr in technique.attributes) {
  104171. var attribute = technique.attributes[attr];
  104172. var attributeParameter = technique.parameters[attribute];
  104173. if (attributeParameter.semantic) {
  104174. attributes.push(getAttribute(attributeParameter));
  104175. }
  104176. }
  104177. // Configure vertex shader
  104178. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  104179. var tokenType = vertexTokenizer.currentToken;
  104180. if (tokenType !== ETokenType.IDENTIFIER) {
  104181. newVertexShader += vertexTokenizer.currentString;
  104182. continue;
  104183. }
  104184. var foundAttribute = false;
  104185. for (var attr in technique.attributes) {
  104186. var attribute = technique.attributes[attr];
  104187. var attributeParameter = technique.parameters[attribute];
  104188. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  104189. newVertexShader += getAttribute(attributeParameter);
  104190. foundAttribute = true;
  104191. break;
  104192. }
  104193. }
  104194. if (foundAttribute) {
  104195. continue;
  104196. }
  104197. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  104198. }
  104199. // Configure pixel shader
  104200. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  104201. var tokenType = pixelTokenizer.currentToken;
  104202. if (tokenType !== ETokenType.IDENTIFIER) {
  104203. newPixelShader += pixelTokenizer.currentString;
  104204. continue;
  104205. }
  104206. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  104207. }
  104208. // Create shader material
  104209. var shaderPath = {
  104210. vertex: program.vertexShader + id,
  104211. fragment: program.fragmentShader + id
  104212. };
  104213. var options = {
  104214. attributes: attributes,
  104215. uniforms: uniforms,
  104216. samplers: samplers,
  104217. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  104218. };
  104219. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  104220. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  104221. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  104222. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  104223. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  104224. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  104225. if (states && states.functions) {
  104226. var functions = states.functions;
  104227. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  104228. shaderMaterial.backFaceCulling = false;
  104229. }
  104230. var blendFunc = functions.blendFuncSeparate;
  104231. if (blendFunc) {
  104232. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  104233. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  104234. }
  104235. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  104236. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  104237. }
  104238. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  104239. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  104240. }
  104241. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  104242. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  104243. }
  104244. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  104245. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  104246. }
  104247. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  104248. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  104249. }
  104250. }
  104251. }
  104252. };
  104253. return GLTFLoaderBase;
  104254. }());
  104255. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  104256. /**
  104257. * glTF V1 Loader
  104258. */
  104259. var GLTFLoader = /** @class */ (function () {
  104260. function GLTFLoader() {
  104261. // #region Stubs for IGLTFLoader interface
  104262. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  104263. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  104264. this.compileMaterials = false;
  104265. this.useClipPlane = false;
  104266. this.compileShadowGenerators = false;
  104267. this.transparencyAsCoverage = false;
  104268. this._normalizeAnimationGroupsToBeginAtZero = true;
  104269. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  104270. this.onMeshLoadedObservable = new BABYLON.Observable();
  104271. this.onTextureLoadedObservable = new BABYLON.Observable();
  104272. this.onMaterialLoadedObservable = new BABYLON.Observable();
  104273. this.onCameraLoadedObservable = new BABYLON.Observable();
  104274. this.onCompleteObservable = new BABYLON.Observable();
  104275. this.onDisposeObservable = new BABYLON.Observable();
  104276. this.onExtensionLoadedObservable = new BABYLON.Observable();
  104277. this.state = null;
  104278. }
  104279. GLTFLoader.RegisterExtension = function (extension) {
  104280. if (GLTFLoader.Extensions[extension.name]) {
  104281. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  104282. return;
  104283. }
  104284. GLTFLoader.Extensions[extension.name] = extension;
  104285. };
  104286. GLTFLoader.prototype.dispose = function () { };
  104287. // #endregion
  104288. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  104289. var _this = this;
  104290. scene.useRightHandedSystem = true;
  104291. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  104292. gltfRuntime.importOnlyMeshes = true;
  104293. if (meshesNames === "") {
  104294. gltfRuntime.importMeshesNames = [];
  104295. }
  104296. else if (typeof meshesNames === "string") {
  104297. gltfRuntime.importMeshesNames = [meshesNames];
  104298. }
  104299. else if (meshesNames && !(meshesNames instanceof Array)) {
  104300. gltfRuntime.importMeshesNames = [meshesNames];
  104301. }
  104302. else {
  104303. gltfRuntime.importMeshesNames = [];
  104304. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  104305. }
  104306. // Create nodes
  104307. _this._createNodes(gltfRuntime);
  104308. var meshes = new Array();
  104309. var skeletons = new Array();
  104310. // Fill arrays of meshes and skeletons
  104311. for (var nde in gltfRuntime.nodes) {
  104312. var node = gltfRuntime.nodes[nde];
  104313. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  104314. meshes.push(node.babylonNode);
  104315. }
  104316. }
  104317. for (var skl in gltfRuntime.skins) {
  104318. var skin = gltfRuntime.skins[skl];
  104319. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  104320. skeletons.push(skin.babylonSkeleton);
  104321. }
  104322. }
  104323. // Load buffers, shaders, materials, etc.
  104324. _this._loadBuffersAsync(gltfRuntime, function () {
  104325. _this._loadShadersAsync(gltfRuntime, function () {
  104326. importMaterials(gltfRuntime);
  104327. postLoad(gltfRuntime);
  104328. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  104329. onSuccess(meshes, skeletons);
  104330. }
  104331. });
  104332. }, onProgress);
  104333. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  104334. onSuccess(meshes, skeletons);
  104335. }
  104336. }, onError);
  104337. return true;
  104338. };
  104339. /**
  104340. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  104341. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  104342. * @param scene the scene the meshes should be added to
  104343. * @param data gltf data containing information of the meshes in a loaded file
  104344. * @param rootUrl root url to load from
  104345. * @param onProgress event that fires when loading progress has occured
  104346. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  104347. */
  104348. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  104349. var _this = this;
  104350. return new Promise(function (resolve, reject) {
  104351. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  104352. resolve({
  104353. meshes: meshes,
  104354. particleSystems: [],
  104355. skeletons: skeletons,
  104356. animationGroups: []
  104357. });
  104358. }, onProgress, function (message) {
  104359. reject(new Error(message));
  104360. });
  104361. });
  104362. };
  104363. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  104364. var _this = this;
  104365. scene.useRightHandedSystem = true;
  104366. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  104367. // Load runtime extensios
  104368. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  104369. // Create nodes
  104370. _this._createNodes(gltfRuntime);
  104371. // Load buffers, shaders, materials, etc.
  104372. _this._loadBuffersAsync(gltfRuntime, function () {
  104373. _this._loadShadersAsync(gltfRuntime, function () {
  104374. importMaterials(gltfRuntime);
  104375. postLoad(gltfRuntime);
  104376. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  104377. onSuccess();
  104378. }
  104379. });
  104380. });
  104381. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  104382. onSuccess();
  104383. }
  104384. }, onError);
  104385. }, onError);
  104386. };
  104387. /**
  104388. * Imports all objects from a loaded gltf file and adds them to the scene
  104389. * @param scene the scene the objects should be added to
  104390. * @param data gltf data containing information of the meshes in a loaded file
  104391. * @param rootUrl root url to load from
  104392. * @param onProgress event that fires when loading progress has occured
  104393. * @returns a promise which completes when objects have been loaded to the scene
  104394. */
  104395. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  104396. var _this = this;
  104397. return new Promise(function (resolve, reject) {
  104398. _this._loadAsync(scene, data, rootUrl, function () {
  104399. resolve();
  104400. }, onProgress, function (message) {
  104401. reject(new Error(message));
  104402. });
  104403. });
  104404. };
  104405. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  104406. var hasShaders = false;
  104407. var processShader = function (sha, shader) {
  104408. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  104409. if (shaderString instanceof ArrayBuffer) {
  104410. return;
  104411. }
  104412. gltfRuntime.loadedShaderCount++;
  104413. if (shaderString) {
  104414. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  104415. }
  104416. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  104417. onload();
  104418. }
  104419. }, function () {
  104420. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  104421. });
  104422. };
  104423. for (var sha in gltfRuntime.shaders) {
  104424. hasShaders = true;
  104425. var shader = gltfRuntime.shaders[sha];
  104426. if (shader) {
  104427. processShader.bind(this, sha, shader)();
  104428. }
  104429. else {
  104430. BABYLON.Tools.Error("No shader named: " + sha);
  104431. }
  104432. }
  104433. if (!hasShaders) {
  104434. onload();
  104435. }
  104436. };
  104437. ;
  104438. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  104439. var hasBuffers = false;
  104440. var processBuffer = function (buf, buffer) {
  104441. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  104442. gltfRuntime.loadedBufferCount++;
  104443. if (bufferView) {
  104444. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  104445. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  104446. }
  104447. gltfRuntime.loadedBufferViews[buf] = bufferView;
  104448. }
  104449. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  104450. onLoad();
  104451. }
  104452. }, function () {
  104453. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  104454. });
  104455. };
  104456. for (var buf in gltfRuntime.buffers) {
  104457. hasBuffers = true;
  104458. var buffer = gltfRuntime.buffers[buf];
  104459. if (buffer) {
  104460. processBuffer.bind(this, buf, buffer)();
  104461. }
  104462. else {
  104463. BABYLON.Tools.Error("No buffer named: " + buf);
  104464. }
  104465. }
  104466. if (!hasBuffers) {
  104467. onLoad();
  104468. }
  104469. };
  104470. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  104471. var currentScene = gltfRuntime.currentScene;
  104472. if (currentScene) {
  104473. // Only one scene even if multiple scenes are defined
  104474. for (var i = 0; i < currentScene.nodes.length; i++) {
  104475. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  104476. }
  104477. }
  104478. else {
  104479. // Load all scenes
  104480. for (var thing in gltfRuntime.scenes) {
  104481. currentScene = gltfRuntime.scenes[thing];
  104482. for (var i = 0; i < currentScene.nodes.length; i++) {
  104483. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  104484. }
  104485. }
  104486. }
  104487. };
  104488. GLTFLoader.Extensions = {};
  104489. return GLTFLoader;
  104490. }());
  104491. GLTF1.GLTFLoader = GLTFLoader;
  104492. ;
  104493. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  104494. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  104495. })(BABYLON || (BABYLON = {}));
  104496. //# sourceMappingURL=babylon.glTFLoader.js.map
  104497. var BABYLON;
  104498. (function (BABYLON) {
  104499. var GLTF1;
  104500. (function (GLTF1) {
  104501. /**
  104502. * Utils functions for GLTF
  104503. */
  104504. var GLTFUtils = /** @class */ (function () {
  104505. function GLTFUtils() {
  104506. }
  104507. /**
  104508. * Sets the given "parameter" matrix
  104509. * @param scene: the {BABYLON.Scene} object
  104510. * @param source: the source node where to pick the matrix
  104511. * @param parameter: the GLTF technique parameter
  104512. * @param uniformName: the name of the shader's uniform
  104513. * @param shaderMaterial: the shader material
  104514. */
  104515. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  104516. var mat = null;
  104517. if (parameter.semantic === "MODEL") {
  104518. mat = source.getWorldMatrix();
  104519. }
  104520. else if (parameter.semantic === "PROJECTION") {
  104521. mat = scene.getProjectionMatrix();
  104522. }
  104523. else if (parameter.semantic === "VIEW") {
  104524. mat = scene.getViewMatrix();
  104525. }
  104526. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  104527. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  104528. }
  104529. else if (parameter.semantic === "MODELVIEW") {
  104530. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  104531. }
  104532. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  104533. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  104534. }
  104535. else if (parameter.semantic === "MODELINVERSE") {
  104536. mat = source.getWorldMatrix().invert();
  104537. }
  104538. else if (parameter.semantic === "VIEWINVERSE") {
  104539. mat = scene.getViewMatrix().invert();
  104540. }
  104541. else if (parameter.semantic === "PROJECTIONINVERSE") {
  104542. mat = scene.getProjectionMatrix().invert();
  104543. }
  104544. else if (parameter.semantic === "MODELVIEWINVERSE") {
  104545. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  104546. }
  104547. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  104548. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  104549. }
  104550. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  104551. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  104552. }
  104553. else {
  104554. debugger;
  104555. }
  104556. if (mat) {
  104557. switch (parameter.type) {
  104558. case GLTF1.EParameterType.FLOAT_MAT2:
  104559. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  104560. break;
  104561. case GLTF1.EParameterType.FLOAT_MAT3:
  104562. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  104563. break;
  104564. case GLTF1.EParameterType.FLOAT_MAT4:
  104565. shaderMaterial.setMatrix(uniformName, mat);
  104566. break;
  104567. default: break;
  104568. }
  104569. }
  104570. };
  104571. /**
  104572. * Sets the given "parameter" matrix
  104573. * @param shaderMaterial: the shader material
  104574. * @param uniform: the name of the shader's uniform
  104575. * @param value: the value of the uniform
  104576. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  104577. */
  104578. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  104579. switch (type) {
  104580. case GLTF1.EParameterType.FLOAT:
  104581. shaderMaterial.setFloat(uniform, value);
  104582. return true;
  104583. case GLTF1.EParameterType.FLOAT_VEC2:
  104584. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  104585. return true;
  104586. case GLTF1.EParameterType.FLOAT_VEC3:
  104587. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  104588. return true;
  104589. case GLTF1.EParameterType.FLOAT_VEC4:
  104590. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  104591. return true;
  104592. default: return false;
  104593. }
  104594. };
  104595. /**
  104596. * Returns the wrap mode of the texture
  104597. * @param mode: the mode value
  104598. */
  104599. GLTFUtils.GetWrapMode = function (mode) {
  104600. switch (mode) {
  104601. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  104602. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  104603. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  104604. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  104605. }
  104606. };
  104607. /**
  104608. * Returns the byte stride giving an accessor
  104609. * @param accessor: the GLTF accessor objet
  104610. */
  104611. GLTFUtils.GetByteStrideFromType = function (accessor) {
  104612. // Needs this function since "byteStride" isn't requiered in glTF format
  104613. var type = accessor.type;
  104614. switch (type) {
  104615. case "VEC2": return 2;
  104616. case "VEC3": return 3;
  104617. case "VEC4": return 4;
  104618. case "MAT2": return 4;
  104619. case "MAT3": return 9;
  104620. case "MAT4": return 16;
  104621. default: return 1;
  104622. }
  104623. };
  104624. /**
  104625. * Returns the texture filter mode giving a mode value
  104626. * @param mode: the filter mode value
  104627. */
  104628. GLTFUtils.GetTextureFilterMode = function (mode) {
  104629. switch (mode) {
  104630. case GLTF1.ETextureFilterType.LINEAR:
  104631. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  104632. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  104633. case GLTF1.ETextureFilterType.NEAREST:
  104634. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  104635. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  104636. }
  104637. };
  104638. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  104639. var byteOffset = bufferView.byteOffset + byteOffset;
  104640. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  104641. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  104642. throw new Error("Buffer access is out of range");
  104643. }
  104644. var buffer = loadedBufferView.buffer;
  104645. byteOffset += loadedBufferView.byteOffset;
  104646. switch (componentType) {
  104647. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  104648. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  104649. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  104650. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  104651. default: return new Float32Array(buffer, byteOffset, byteLength);
  104652. }
  104653. };
  104654. /**
  104655. * Returns a buffer from its accessor
  104656. * @param gltfRuntime: the GLTF runtime
  104657. * @param accessor: the GLTF accessor
  104658. */
  104659. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  104660. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  104661. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  104662. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  104663. };
  104664. /**
  104665. * Decodes a buffer view into a string
  104666. * @param view: the buffer view
  104667. */
  104668. GLTFUtils.DecodeBufferToText = function (view) {
  104669. var result = "";
  104670. var length = view.byteLength;
  104671. for (var i = 0; i < length; ++i) {
  104672. result += String.fromCharCode(view[i]);
  104673. }
  104674. return result;
  104675. };
  104676. /**
  104677. * Returns the default material of gltf. Related to
  104678. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  104679. * @param scene: the Babylon.js scene
  104680. */
  104681. GLTFUtils.GetDefaultMaterial = function (scene) {
  104682. if (!GLTFUtils._DefaultMaterial) {
  104683. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  104684. "precision highp float;",
  104685. "",
  104686. "uniform mat4 worldView;",
  104687. "uniform mat4 projection;",
  104688. "",
  104689. "attribute vec3 position;",
  104690. "",
  104691. "void main(void)",
  104692. "{",
  104693. " gl_Position = projection * worldView * vec4(position, 1.0);",
  104694. "}"
  104695. ].join("\n");
  104696. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  104697. "precision highp float;",
  104698. "",
  104699. "uniform vec4 u_emission;",
  104700. "",
  104701. "void main(void)",
  104702. "{",
  104703. " gl_FragColor = u_emission;",
  104704. "}"
  104705. ].join("\n");
  104706. var shaderPath = {
  104707. vertex: "GLTFDefaultMaterial",
  104708. fragment: "GLTFDefaultMaterial"
  104709. };
  104710. var options = {
  104711. attributes: ["position"],
  104712. uniforms: ["worldView", "projection", "u_emission"],
  104713. samplers: new Array(),
  104714. needAlphaBlending: false
  104715. };
  104716. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  104717. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  104718. }
  104719. return GLTFUtils._DefaultMaterial;
  104720. };
  104721. // The GLTF default material
  104722. GLTFUtils._DefaultMaterial = null;
  104723. return GLTFUtils;
  104724. }());
  104725. GLTF1.GLTFUtils = GLTFUtils;
  104726. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  104727. })(BABYLON || (BABYLON = {}));
  104728. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  104729. var BABYLON;
  104730. (function (BABYLON) {
  104731. var GLTF1;
  104732. (function (GLTF1) {
  104733. var GLTFLoaderExtension = /** @class */ (function () {
  104734. function GLTFLoaderExtension(name) {
  104735. this._name = name;
  104736. }
  104737. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  104738. get: function () {
  104739. return this._name;
  104740. },
  104741. enumerable: true,
  104742. configurable: true
  104743. });
  104744. /**
  104745. * Defines an override for loading the runtime
  104746. * Return true to stop further extensions from loading the runtime
  104747. */
  104748. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  104749. return false;
  104750. };
  104751. /**
  104752. * Defines an onverride for creating gltf runtime
  104753. * Return true to stop further extensions from creating the runtime
  104754. */
  104755. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  104756. return false;
  104757. };
  104758. /**
  104759. * Defines an override for loading buffers
  104760. * Return true to stop further extensions from loading this buffer
  104761. */
  104762. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  104763. return false;
  104764. };
  104765. /**
  104766. * Defines an override for loading texture buffers
  104767. * Return true to stop further extensions from loading this texture data
  104768. */
  104769. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  104770. return false;
  104771. };
  104772. /**
  104773. * Defines an override for creating textures
  104774. * Return true to stop further extensions from loading this texture
  104775. */
  104776. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  104777. return false;
  104778. };
  104779. /**
  104780. * Defines an override for loading shader strings
  104781. * Return true to stop further extensions from loading this shader data
  104782. */
  104783. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  104784. return false;
  104785. };
  104786. /**
  104787. * Defines an override for loading materials
  104788. * Return true to stop further extensions from loading this material
  104789. */
  104790. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  104791. return false;
  104792. };
  104793. // ---------
  104794. // Utilities
  104795. // ---------
  104796. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  104797. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  104798. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  104799. }, function () {
  104800. setTimeout(function () {
  104801. if (!onSuccess) {
  104802. return;
  104803. }
  104804. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  104805. });
  104806. });
  104807. };
  104808. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  104809. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  104810. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  104811. }, function () {
  104812. setTimeout(function () {
  104813. onSuccess();
  104814. });
  104815. });
  104816. };
  104817. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  104818. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  104819. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  104820. }, function () {
  104821. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  104822. });
  104823. };
  104824. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  104825. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  104826. if (buffer) {
  104827. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  104828. }
  104829. }, onError);
  104830. };
  104831. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  104832. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  104833. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  104834. }, function () {
  104835. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  104836. });
  104837. };
  104838. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  104839. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  104840. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  104841. }, function () {
  104842. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  104843. });
  104844. };
  104845. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  104846. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  104847. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  104848. }, function () {
  104849. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  104850. });
  104851. };
  104852. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  104853. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  104854. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  104855. }, function () {
  104856. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  104857. });
  104858. };
  104859. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  104860. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  104861. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  104862. if (func(loaderExtension)) {
  104863. return;
  104864. }
  104865. }
  104866. defaultFunc();
  104867. };
  104868. return GLTFLoaderExtension;
  104869. }());
  104870. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  104871. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  104872. })(BABYLON || (BABYLON = {}));
  104873. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  104874. var BABYLON;
  104875. (function (BABYLON) {
  104876. var GLTF1;
  104877. (function (GLTF1) {
  104878. var BinaryExtensionBufferName = "binary_glTF";
  104879. ;
  104880. ;
  104881. var GLTFBinaryExtension = /** @class */ (function (_super) {
  104882. __extends(GLTFBinaryExtension, _super);
  104883. function GLTFBinaryExtension() {
  104884. return _super.call(this, "KHR_binary_glTF") || this;
  104885. }
  104886. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  104887. var extensionsUsed = data.json.extensionsUsed;
  104888. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  104889. return false;
  104890. }
  104891. this._bin = data.bin;
  104892. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  104893. return true;
  104894. };
  104895. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  104896. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  104897. return false;
  104898. }
  104899. if (id !== BinaryExtensionBufferName) {
  104900. return false;
  104901. }
  104902. onSuccess(this._bin);
  104903. return true;
  104904. };
  104905. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  104906. var texture = gltfRuntime.textures[id];
  104907. var source = gltfRuntime.images[texture.source];
  104908. if (!source.extensions || !(this.name in source.extensions)) {
  104909. return false;
  104910. }
  104911. var sourceExt = source.extensions[this.name];
  104912. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  104913. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  104914. onSuccess(buffer);
  104915. return true;
  104916. };
  104917. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  104918. var shader = gltfRuntime.shaders[id];
  104919. if (!shader.extensions || !(this.name in shader.extensions)) {
  104920. return false;
  104921. }
  104922. var binaryExtensionShader = shader.extensions[this.name];
  104923. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  104924. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  104925. setTimeout(function () {
  104926. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  104927. onSuccess(shaderString);
  104928. });
  104929. return true;
  104930. };
  104931. return GLTFBinaryExtension;
  104932. }(GLTF1.GLTFLoaderExtension));
  104933. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  104934. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  104935. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  104936. })(BABYLON || (BABYLON = {}));
  104937. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  104938. var BABYLON;
  104939. (function (BABYLON) {
  104940. var GLTF1;
  104941. (function (GLTF1) {
  104942. ;
  104943. ;
  104944. ;
  104945. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  104946. __extends(GLTFMaterialsCommonExtension, _super);
  104947. function GLTFMaterialsCommonExtension() {
  104948. return _super.call(this, "KHR_materials_common") || this;
  104949. }
  104950. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  104951. if (!gltfRuntime.extensions)
  104952. return false;
  104953. var extension = gltfRuntime.extensions[this.name];
  104954. if (!extension)
  104955. return false;
  104956. // Create lights
  104957. var lights = extension.lights;
  104958. if (lights) {
  104959. for (var thing in lights) {
  104960. var light = lights[thing];
  104961. switch (light.type) {
  104962. case "ambient":
  104963. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  104964. var ambient = light.ambient;
  104965. if (ambient) {
  104966. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  104967. }
  104968. break;
  104969. case "point":
  104970. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  104971. var point = light.point;
  104972. if (point) {
  104973. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  104974. }
  104975. break;
  104976. case "directional":
  104977. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  104978. var directional = light.directional;
  104979. if (directional) {
  104980. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  104981. }
  104982. break;
  104983. case "spot":
  104984. var spot = light.spot;
  104985. if (spot) {
  104986. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  104987. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  104988. }
  104989. break;
  104990. default:
  104991. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  104992. break;
  104993. }
  104994. }
  104995. }
  104996. return false;
  104997. };
  104998. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  104999. var material = gltfRuntime.materials[id];
  105000. if (!material || !material.extensions)
  105001. return false;
  105002. var extension = material.extensions[this.name];
  105003. if (!extension)
  105004. return false;
  105005. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  105006. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  105007. if (extension.technique === "CONSTANT") {
  105008. standardMaterial.disableLighting = true;
  105009. }
  105010. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  105011. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  105012. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  105013. // Ambient
  105014. if (typeof extension.values.ambient === "string") {
  105015. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  105016. }
  105017. else {
  105018. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  105019. }
  105020. // Diffuse
  105021. if (typeof extension.values.diffuse === "string") {
  105022. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  105023. }
  105024. else {
  105025. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  105026. }
  105027. // Emission
  105028. if (typeof extension.values.emission === "string") {
  105029. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  105030. }
  105031. else {
  105032. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  105033. }
  105034. // Specular
  105035. if (typeof extension.values.specular === "string") {
  105036. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  105037. }
  105038. else {
  105039. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  105040. }
  105041. return true;
  105042. };
  105043. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  105044. // Create buffer from texture url
  105045. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  105046. // Create texture from buffer
  105047. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  105048. }, onError);
  105049. };
  105050. return GLTFMaterialsCommonExtension;
  105051. }(GLTF1.GLTFLoaderExtension));
  105052. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  105053. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  105054. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  105055. })(BABYLON || (BABYLON = {}));
  105056. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  105057. var BABYLON;
  105058. (function (BABYLON) {
  105059. var GLTF2;
  105060. (function (GLTF2) {
  105061. /** @hidden */
  105062. var _ArrayItem = /** @class */ (function () {
  105063. function _ArrayItem() {
  105064. }
  105065. /** @hidden */
  105066. _ArrayItem.Assign = function (values) {
  105067. if (values) {
  105068. for (var index = 0; index < values.length; index++) {
  105069. values[index]._index = index;
  105070. }
  105071. }
  105072. };
  105073. return _ArrayItem;
  105074. }());
  105075. GLTF2._ArrayItem = _ArrayItem;
  105076. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105077. })(BABYLON || (BABYLON = {}));
  105078. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  105079. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  105080. /**
  105081. * Defines the module used to import/export glTF 2.0 assets
  105082. */
  105083. var BABYLON;
  105084. (function (BABYLON) {
  105085. var GLTF2;
  105086. (function (GLTF2) {
  105087. /**
  105088. * Loader for loading a glTF 2.0 asset
  105089. */
  105090. var GLTFLoader = /** @class */ (function () {
  105091. function GLTFLoader() {
  105092. /** @hidden */
  105093. this._completePromises = new Array();
  105094. /** @hidden */
  105095. this._onReadyObservable = new BABYLON.Observable();
  105096. this._disposed = false;
  105097. this._state = null;
  105098. this._extensions = {};
  105099. this._defaultSampler = {};
  105100. this._defaultBabylonMaterials = {};
  105101. this._requests = new Array();
  105102. /**
  105103. * Mode that determines the coordinate system to use.
  105104. */
  105105. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  105106. /**
  105107. * Mode that determines what animations will start.
  105108. */
  105109. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  105110. /**
  105111. * Defines if the loader should compile materials.
  105112. */
  105113. this.compileMaterials = false;
  105114. /**
  105115. * Defines if the loader should also compile materials with clip planes.
  105116. */
  105117. this.useClipPlane = false;
  105118. /**
  105119. * Defines if the loader should compile shadow generators.
  105120. */
  105121. this.compileShadowGenerators = false;
  105122. /**
  105123. * Defines if the Alpha blended materials are only applied as coverage.
  105124. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  105125. * If true, no extra effects are applied to transparent pixels.
  105126. */
  105127. this.transparencyAsCoverage = false;
  105128. /** @hidden */
  105129. this._normalizeAnimationGroupsToBeginAtZero = true;
  105130. /**
  105131. * Function called before loading a url referenced by the asset.
  105132. */
  105133. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  105134. /**
  105135. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  105136. */
  105137. this.onMeshLoadedObservable = new BABYLON.Observable();
  105138. /**
  105139. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  105140. */
  105141. this.onTextureLoadedObservable = new BABYLON.Observable();
  105142. /**
  105143. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  105144. */
  105145. this.onMaterialLoadedObservable = new BABYLON.Observable();
  105146. /**
  105147. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  105148. */
  105149. this.onCameraLoadedObservable = new BABYLON.Observable();
  105150. /**
  105151. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  105152. * For assets with LODs, raised when all of the LODs are complete.
  105153. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  105154. */
  105155. this.onCompleteObservable = new BABYLON.Observable();
  105156. /**
  105157. * Observable raised after the loader is disposed.
  105158. */
  105159. this.onDisposeObservable = new BABYLON.Observable();
  105160. /**
  105161. * Observable raised after a loader extension is created.
  105162. * Set additional options for a loader extension in this event.
  105163. */
  105164. this.onExtensionLoadedObservable = new BABYLON.Observable();
  105165. }
  105166. /** @hidden */
  105167. GLTFLoader._Register = function (name, factory) {
  105168. if (GLTFLoader._ExtensionFactories[name]) {
  105169. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  105170. return;
  105171. }
  105172. GLTFLoader._ExtensionFactories[name] = factory;
  105173. // Keep the order of registration so that extensions registered first are called first.
  105174. GLTFLoader._ExtensionNames.push(name);
  105175. };
  105176. Object.defineProperty(GLTFLoader.prototype, "state", {
  105177. /**
  105178. * Loader state or null if the loader is not active.
  105179. */
  105180. get: function () {
  105181. return this._state;
  105182. },
  105183. enumerable: true,
  105184. configurable: true
  105185. });
  105186. /**
  105187. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  105188. */
  105189. GLTFLoader.prototype.dispose = function () {
  105190. if (this._disposed) {
  105191. return;
  105192. }
  105193. this._disposed = true;
  105194. this.onDisposeObservable.notifyObservers(this);
  105195. this.onDisposeObservable.clear();
  105196. this._clear();
  105197. };
  105198. /**
  105199. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  105200. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  105201. * @param scene the scene the meshes should be added to
  105202. * @param data the glTF data to load
  105203. * @param rootUrl root url to load from
  105204. * @param onProgress event that fires when loading progress has occured
  105205. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  105206. */
  105207. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  105208. var _this = this;
  105209. return Promise.resolve().then(function () {
  105210. _this._babylonScene = scene;
  105211. _this._rootUrl = rootUrl;
  105212. _this._progressCallback = onProgress;
  105213. _this._loadData(data);
  105214. var nodes = null;
  105215. if (meshesNames) {
  105216. var nodeMap_1 = {};
  105217. if (_this._gltf.nodes) {
  105218. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  105219. var node = _a[_i];
  105220. if (node.name) {
  105221. nodeMap_1[node.name] = node;
  105222. }
  105223. }
  105224. }
  105225. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  105226. nodes = names.map(function (name) {
  105227. var node = nodeMap_1[name];
  105228. if (!node) {
  105229. throw new Error("Failed to find node '" + name + "'");
  105230. }
  105231. return node;
  105232. });
  105233. }
  105234. return _this._loadAsync(nodes).then(function () {
  105235. return {
  105236. meshes: _this._getMeshes(),
  105237. particleSystems: [],
  105238. skeletons: _this._getSkeletons(),
  105239. animationGroups: _this._getAnimationGroups()
  105240. };
  105241. });
  105242. });
  105243. };
  105244. /**
  105245. * Imports all objects from the loaded glTF data and adds them to the scene
  105246. * @param scene the scene the objects should be added to
  105247. * @param data the glTF data to load
  105248. * @param rootUrl root url to load from
  105249. * @param onProgress event that fires when loading progress has occured
  105250. * @returns a promise which completes when objects have been loaded to the scene
  105251. */
  105252. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  105253. var _this = this;
  105254. return Promise.resolve().then(function () {
  105255. _this._babylonScene = scene;
  105256. _this._rootUrl = rootUrl;
  105257. _this._progressCallback = onProgress;
  105258. _this._loadData(data);
  105259. return _this._loadAsync(null);
  105260. });
  105261. };
  105262. GLTFLoader.prototype._loadAsync = function (nodes) {
  105263. var _this = this;
  105264. return Promise.resolve().then(function () {
  105265. _this._state = BABYLON.GLTFLoaderState.LOADING;
  105266. _this._loadExtensions();
  105267. _this._checkExtensions();
  105268. var promises = new Array();
  105269. if (nodes) {
  105270. promises.push(_this._loadNodesAsync(nodes));
  105271. }
  105272. else {
  105273. var scene = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  105274. promises.push(_this._loadSceneAsync("#/scenes/" + scene._index, scene));
  105275. }
  105276. if (_this.compileMaterials) {
  105277. promises.push(_this._compileMaterialsAsync());
  105278. }
  105279. if (_this.compileShadowGenerators) {
  105280. promises.push(_this._compileShadowGeneratorsAsync());
  105281. }
  105282. var resultPromise = Promise.all(promises).then(function () {
  105283. _this._state = BABYLON.GLTFLoaderState.READY;
  105284. _this._onReadyObservable.notifyObservers(_this);
  105285. _this._startAnimations();
  105286. });
  105287. resultPromise.then(function () {
  105288. if (_this._rootBabylonMesh) {
  105289. _this._rootBabylonMesh.setEnabled(true);
  105290. }
  105291. BABYLON.Tools.SetImmediate(function () {
  105292. if (!_this._disposed) {
  105293. Promise.all(_this._completePromises).then(function () {
  105294. _this._state = BABYLON.GLTFLoaderState.COMPLETE;
  105295. _this.onCompleteObservable.notifyObservers(_this);
  105296. _this.onCompleteObservable.clear();
  105297. _this._clear();
  105298. }).catch(function (error) {
  105299. BABYLON.Tools.Error("glTF Loader: " + error.message);
  105300. _this._clear();
  105301. });
  105302. }
  105303. });
  105304. });
  105305. return resultPromise;
  105306. }).catch(function (error) {
  105307. if (!_this._disposed) {
  105308. BABYLON.Tools.Error("glTF Loader: " + error.message);
  105309. _this._clear();
  105310. throw error;
  105311. }
  105312. });
  105313. };
  105314. GLTFLoader.prototype._loadData = function (data) {
  105315. this._gltf = data.json;
  105316. this._setupData();
  105317. if (data.bin) {
  105318. var buffers = this._gltf.buffers;
  105319. if (buffers && buffers[0] && !buffers[0].uri) {
  105320. var binaryBuffer = buffers[0];
  105321. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  105322. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  105323. }
  105324. binaryBuffer._data = Promise.resolve(data.bin);
  105325. }
  105326. else {
  105327. BABYLON.Tools.Warn("Unexpected BIN chunk");
  105328. }
  105329. }
  105330. };
  105331. GLTFLoader.prototype._setupData = function () {
  105332. GLTF2._ArrayItem.Assign(this._gltf.accessors);
  105333. GLTF2._ArrayItem.Assign(this._gltf.animations);
  105334. GLTF2._ArrayItem.Assign(this._gltf.buffers);
  105335. GLTF2._ArrayItem.Assign(this._gltf.bufferViews);
  105336. GLTF2._ArrayItem.Assign(this._gltf.cameras);
  105337. GLTF2._ArrayItem.Assign(this._gltf.images);
  105338. GLTF2._ArrayItem.Assign(this._gltf.materials);
  105339. GLTF2._ArrayItem.Assign(this._gltf.meshes);
  105340. GLTF2._ArrayItem.Assign(this._gltf.nodes);
  105341. GLTF2._ArrayItem.Assign(this._gltf.samplers);
  105342. GLTF2._ArrayItem.Assign(this._gltf.scenes);
  105343. GLTF2._ArrayItem.Assign(this._gltf.skins);
  105344. GLTF2._ArrayItem.Assign(this._gltf.textures);
  105345. if (this._gltf.nodes) {
  105346. var nodeParents = {};
  105347. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  105348. var node = _a[_i];
  105349. if (node.children) {
  105350. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  105351. var index = _c[_b];
  105352. nodeParents[index] = node._index;
  105353. }
  105354. }
  105355. }
  105356. var rootNode = this._createRootNode();
  105357. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  105358. var node = _e[_d];
  105359. var parentIndex = nodeParents[node._index];
  105360. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  105361. }
  105362. }
  105363. };
  105364. GLTFLoader.prototype._loadExtensions = function () {
  105365. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  105366. var name_1 = _a[_i];
  105367. var extension = GLTFLoader._ExtensionFactories[name_1](this);
  105368. this._extensions[name_1] = extension;
  105369. this.onExtensionLoadedObservable.notifyObservers(extension);
  105370. }
  105371. this.onExtensionLoadedObservable.clear();
  105372. };
  105373. GLTFLoader.prototype._checkExtensions = function () {
  105374. if (this._gltf.extensionsRequired) {
  105375. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  105376. var name_2 = _a[_i];
  105377. var extension = this._extensions[name_2];
  105378. if (!extension || !extension.enabled) {
  105379. throw new Error("Require extension " + name_2 + " is not available");
  105380. }
  105381. }
  105382. }
  105383. };
  105384. GLTFLoader.prototype._createRootNode = function () {
  105385. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  105386. this._rootBabylonMesh.setEnabled(false);
  105387. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  105388. switch (this.coordinateSystemMode) {
  105389. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  105390. if (!this._babylonScene.useRightHandedSystem) {
  105391. rootNode.rotation = [0, 1, 0, 0];
  105392. rootNode.scale = [1, 1, -1];
  105393. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  105394. }
  105395. break;
  105396. }
  105397. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  105398. this._babylonScene.useRightHandedSystem = true;
  105399. break;
  105400. }
  105401. default: {
  105402. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  105403. }
  105404. }
  105405. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  105406. return rootNode;
  105407. };
  105408. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  105409. var promises = new Array();
  105410. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  105411. var node = nodes_1[_i];
  105412. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  105413. }
  105414. promises.push(this._loadAnimationsAsync());
  105415. return Promise.all(promises).then(function () { });
  105416. };
  105417. /** @hidden */
  105418. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  105419. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  105420. if (promise) {
  105421. return promise;
  105422. }
  105423. var promises = new Array();
  105424. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  105425. var index = _a[_i];
  105426. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  105427. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  105428. }
  105429. promises.push(this._loadAnimationsAsync());
  105430. return Promise.all(promises).then(function () { });
  105431. };
  105432. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  105433. if (node._primitiveBabylonMeshes) {
  105434. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  105435. var babylonMesh = _a[_i];
  105436. callback(babylonMesh);
  105437. }
  105438. }
  105439. else {
  105440. callback(node._babylonMesh);
  105441. }
  105442. };
  105443. GLTFLoader.prototype._getMeshes = function () {
  105444. var meshes = new Array();
  105445. // Root mesh is always first.
  105446. meshes.push(this._rootBabylonMesh);
  105447. var nodes = this._gltf.nodes;
  105448. if (nodes) {
  105449. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  105450. var node = nodes_2[_i];
  105451. if (node._babylonMesh) {
  105452. meshes.push(node._babylonMesh);
  105453. }
  105454. if (node._primitiveBabylonMeshes) {
  105455. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  105456. var babylonMesh = _b[_a];
  105457. meshes.push(babylonMesh);
  105458. }
  105459. }
  105460. }
  105461. }
  105462. return meshes;
  105463. };
  105464. GLTFLoader.prototype._getSkeletons = function () {
  105465. var skeletons = new Array();
  105466. var skins = this._gltf.skins;
  105467. if (skins) {
  105468. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  105469. var skin = skins_1[_i];
  105470. if (skin._babylonSkeleton) {
  105471. skeletons.push(skin._babylonSkeleton);
  105472. }
  105473. }
  105474. }
  105475. return skeletons;
  105476. };
  105477. GLTFLoader.prototype._getAnimationGroups = function () {
  105478. var animationGroups = new Array();
  105479. var animations = this._gltf.animations;
  105480. if (animations) {
  105481. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  105482. var animation = animations_1[_i];
  105483. if (animation._babylonAnimationGroup) {
  105484. animationGroups.push(animation._babylonAnimationGroup);
  105485. }
  105486. }
  105487. }
  105488. return animationGroups;
  105489. };
  105490. GLTFLoader.prototype._startAnimations = function () {
  105491. switch (this.animationStartMode) {
  105492. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  105493. // do nothing
  105494. break;
  105495. }
  105496. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  105497. var babylonAnimationGroups = this._getAnimationGroups();
  105498. if (babylonAnimationGroups.length !== 0) {
  105499. babylonAnimationGroups[0].start(true);
  105500. }
  105501. break;
  105502. }
  105503. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  105504. var babylonAnimationGroups = this._getAnimationGroups();
  105505. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  105506. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  105507. babylonAnimationGroup.start(true);
  105508. }
  105509. break;
  105510. }
  105511. default: {
  105512. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  105513. return;
  105514. }
  105515. }
  105516. };
  105517. /** @hidden */
  105518. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  105519. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  105520. if (promise) {
  105521. return promise;
  105522. }
  105523. if (node._babylonMesh) {
  105524. throw new Error(context + ": Invalid recursive node hierarchy");
  105525. }
  105526. var promises = new Array();
  105527. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  105528. node._babylonMesh = babylonMesh;
  105529. GLTFLoader._LoadTransform(node, babylonMesh);
  105530. if (node.mesh != undefined) {
  105531. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  105532. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  105533. }
  105534. if (node.camera != undefined) {
  105535. var camera = GLTFLoader._GetProperty(context + "/camera", this._gltf.cameras, node.camera);
  105536. this._loadCamera("#/cameras/" + camera._index, camera, babylonMesh);
  105537. }
  105538. if (node.children) {
  105539. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  105540. var index = _a[_i];
  105541. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  105542. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  105543. }
  105544. }
  105545. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  105546. return Promise.all(promises).then(function () { });
  105547. };
  105548. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  105549. var _this = this;
  105550. var promises = new Array();
  105551. var primitives = mesh.primitives;
  105552. if (!primitives || primitives.length === 0) {
  105553. throw new Error(context + ": Primitives are missing");
  105554. }
  105555. GLTF2._ArrayItem.Assign(primitives);
  105556. if (primitives.length === 1) {
  105557. var primitive = primitives[0];
  105558. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  105559. }
  105560. else {
  105561. node._primitiveBabylonMeshes = [];
  105562. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  105563. var primitive = primitives_1[_i];
  105564. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  105565. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  105566. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  105567. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  105568. }
  105569. }
  105570. if (node.skin != undefined) {
  105571. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  105572. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  105573. }
  105574. return Promise.all(promises).then(function () {
  105575. _this._forEachPrimitive(node, function (babylonMesh) {
  105576. babylonMesh._refreshBoundingInfo(true);
  105577. });
  105578. });
  105579. };
  105580. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  105581. var _this = this;
  105582. var promises = new Array();
  105583. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  105584. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  105585. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  105586. babylonGeometry.applyToMesh(babylonMesh);
  105587. });
  105588. }));
  105589. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  105590. if (primitive.material == undefined) {
  105591. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  105592. }
  105593. else {
  105594. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  105595. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  105596. babylonMesh.material = babylonMaterial;
  105597. }));
  105598. }
  105599. return Promise.all(promises).then(function () { });
  105600. };
  105601. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  105602. var _this = this;
  105603. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  105604. if (promise) {
  105605. return promise;
  105606. }
  105607. var attributes = primitive.attributes;
  105608. if (!attributes) {
  105609. throw new Error(context + ": Attributes are missing");
  105610. }
  105611. var promises = new Array();
  105612. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);
  105613. if (primitive.indices == undefined) {
  105614. babylonMesh.isUnIndexed = true;
  105615. }
  105616. else {
  105617. var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  105618. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  105619. babylonGeometry.setIndices(data);
  105620. }));
  105621. }
  105622. var loadAttribute = function (attribute, kind, callback) {
  105623. if (attributes[attribute] == undefined) {
  105624. return;
  105625. }
  105626. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  105627. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  105628. babylonMesh._delayInfo.push(kind);
  105629. }
  105630. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  105631. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {
  105632. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  105633. }));
  105634. if (callback) {
  105635. callback(accessor);
  105636. }
  105637. };
  105638. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  105639. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  105640. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  105641. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  105642. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  105643. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  105644. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  105645. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  105646. if (accessor.type === "VEC4" /* VEC4 */) {
  105647. babylonMesh.hasVertexAlpha = true;
  105648. }
  105649. });
  105650. return Promise.all(promises).then(function () {
  105651. return babylonGeometry;
  105652. });
  105653. };
  105654. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  105655. if (!primitive.targets) {
  105656. return;
  105657. }
  105658. if (node._numMorphTargets == undefined) {
  105659. node._numMorphTargets = primitive.targets.length;
  105660. }
  105661. else if (primitive.targets.length !== node._numMorphTargets) {
  105662. throw new Error(context + ": Primitives do not have the same number of targets");
  105663. }
  105664. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  105665. for (var index = 0; index < primitive.targets.length; index++) {
  105666. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  105667. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  105668. // TODO: tell the target whether it has positions, normals, tangents
  105669. }
  105670. };
  105671. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  105672. if (!primitive.targets) {
  105673. return Promise.resolve();
  105674. }
  105675. var promises = new Array();
  105676. var morphTargetManager = babylonMesh.morphTargetManager;
  105677. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  105678. var babylonMorphTarget = morphTargetManager.getTarget(index);
  105679. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  105680. }
  105681. return Promise.all(promises).then(function () { });
  105682. };
  105683. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  105684. var _this = this;
  105685. var promises = new Array();
  105686. var loadAttribute = function (attribute, kind, setData) {
  105687. if (attributes[attribute] == undefined) {
  105688. return;
  105689. }
  105690. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  105691. if (!babylonVertexBuffer) {
  105692. return;
  105693. }
  105694. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  105695. promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  105696. setData(babylonVertexBuffer, data);
  105697. }));
  105698. };
  105699. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  105700. babylonVertexBuffer.forEach(data.length, function (value, index) {
  105701. data[index] += value;
  105702. });
  105703. babylonMorphTarget.setPositions(data);
  105704. });
  105705. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  105706. babylonVertexBuffer.forEach(data.length, function (value, index) {
  105707. data[index] += value;
  105708. });
  105709. babylonMorphTarget.setNormals(data);
  105710. });
  105711. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  105712. var dataIndex = 0;
  105713. babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
  105714. // Tangent data for morph targets is stored as xyz delta.
  105715. // The vertexData.tangent is stored as xyzw.
  105716. // So we need to skip every fourth vertexData.tangent.
  105717. if (((index + 1) % 4) !== 0) {
  105718. data[dataIndex++] += value;
  105719. }
  105720. });
  105721. babylonMorphTarget.setTangents(data);
  105722. });
  105723. return Promise.all(promises).then(function () { });
  105724. };
  105725. GLTFLoader._LoadTransform = function (node, babylonNode) {
  105726. var position = BABYLON.Vector3.Zero();
  105727. var rotation = BABYLON.Quaternion.Identity();
  105728. var scaling = BABYLON.Vector3.One();
  105729. if (node.matrix) {
  105730. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  105731. matrix.decompose(scaling, rotation, position);
  105732. }
  105733. else {
  105734. if (node.translation)
  105735. position = BABYLON.Vector3.FromArray(node.translation);
  105736. if (node.rotation)
  105737. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  105738. if (node.scale)
  105739. scaling = BABYLON.Vector3.FromArray(node.scale);
  105740. }
  105741. babylonNode.position = position;
  105742. babylonNode.rotationQuaternion = rotation;
  105743. babylonNode.scaling = scaling;
  105744. };
  105745. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  105746. var _this = this;
  105747. var assignSkeleton = function (skeleton) {
  105748. _this._forEachPrimitive(node, function (babylonMesh) {
  105749. babylonMesh.skeleton = skeleton;
  105750. });
  105751. // Ignore the TRS of skinned nodes.
  105752. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  105753. node._babylonMesh.parent = _this._rootBabylonMesh;
  105754. node._babylonMesh.position = BABYLON.Vector3.Zero();
  105755. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  105756. node._babylonMesh.scaling = BABYLON.Vector3.One();
  105757. };
  105758. if (skin._loaded) {
  105759. return skin._loaded.then(function () {
  105760. assignSkeleton(skin._babylonSkeleton);
  105761. });
  105762. }
  105763. var skeletonId = "skeleton" + skin._index;
  105764. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  105765. skin._babylonSkeleton = babylonSkeleton;
  105766. this._loadBones(context, skin);
  105767. assignSkeleton(babylonSkeleton);
  105768. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  105769. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  105770. }));
  105771. };
  105772. GLTFLoader.prototype._loadBones = function (context, skin) {
  105773. var babylonBones = {};
  105774. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  105775. var index = _a[_i];
  105776. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  105777. this._loadBone(node, skin, babylonBones);
  105778. }
  105779. };
  105780. GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {
  105781. var babylonBone = babylonBones[node._index];
  105782. if (babylonBone) {
  105783. return babylonBone;
  105784. }
  105785. var babylonParentBone = null;
  105786. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  105787. babylonParentBone = this._loadBone(node._parent, skin, babylonBones);
  105788. }
  105789. var boneIndex = skin.joints.indexOf(node._index);
  105790. babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  105791. babylonBones[node._index] = babylonBone;
  105792. node._babylonBones = node._babylonBones || [];
  105793. node._babylonBones.push(babylonBone);
  105794. return babylonBone;
  105795. };
  105796. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  105797. if (skin.inverseBindMatrices == undefined) {
  105798. return Promise.resolve(null);
  105799. }
  105800. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  105801. return this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor);
  105802. };
  105803. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  105804. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  105805. var babylonBone = _a[_i];
  105806. var baseMatrix = BABYLON.Matrix.Identity();
  105807. var boneIndex = babylonBone._index;
  105808. if (inverseBindMatricesData && boneIndex !== -1) {
  105809. BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  105810. baseMatrix.invertToRef(baseMatrix);
  105811. }
  105812. var babylonParentBone = babylonBone.getParent();
  105813. if (babylonParentBone) {
  105814. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  105815. }
  105816. babylonBone.updateMatrix(baseMatrix, false, false);
  105817. babylonBone._updateDifferenceMatrix(undefined, false);
  105818. }
  105819. };
  105820. GLTFLoader.prototype._getNodeMatrix = function (node) {
  105821. return node.matrix ?
  105822. BABYLON.Matrix.FromArray(node.matrix) :
  105823. BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
  105824. };
  105825. GLTFLoader.prototype._loadCamera = function (context, camera, babylonMesh) {
  105826. var babylonCamera = new BABYLON.FreeCamera(camera.name || "camera" + camera._index, BABYLON.Vector3.Zero(), this._babylonScene, false);
  105827. babylonCamera.parent = babylonMesh;
  105828. babylonCamera.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  105829. switch (camera.type) {
  105830. case "perspective" /* PERSPECTIVE */: {
  105831. var perspective = camera.perspective;
  105832. if (!perspective) {
  105833. throw new Error(context + ": Camera perspective properties are missing");
  105834. }
  105835. babylonCamera.fov = perspective.yfov;
  105836. babylonCamera.minZ = perspective.znear;
  105837. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  105838. break;
  105839. }
  105840. case "orthographic" /* ORTHOGRAPHIC */: {
  105841. if (!camera.orthographic) {
  105842. throw new Error(context + ": Camera orthographic properties are missing");
  105843. }
  105844. babylonCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  105845. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  105846. babylonCamera.orthoRight = camera.orthographic.xmag;
  105847. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  105848. babylonCamera.orthoTop = camera.orthographic.ymag;
  105849. babylonCamera.minZ = camera.orthographic.znear;
  105850. babylonCamera.maxZ = camera.orthographic.zfar;
  105851. break;
  105852. }
  105853. default: {
  105854. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  105855. }
  105856. }
  105857. this.onCameraLoadedObservable.notifyObservers(babylonCamera);
  105858. };
  105859. GLTFLoader.prototype._loadAnimationsAsync = function () {
  105860. var animations = this._gltf.animations;
  105861. if (!animations) {
  105862. return Promise.resolve();
  105863. }
  105864. var promises = new Array();
  105865. for (var index = 0; index < animations.length; index++) {
  105866. var animation = animations[index];
  105867. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  105868. }
  105869. return Promise.all(promises).then(function () { });
  105870. };
  105871. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  105872. var _this = this;
  105873. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  105874. animation._babylonAnimationGroup = babylonAnimationGroup;
  105875. var promises = new Array();
  105876. GLTF2._ArrayItem.Assign(animation.channels);
  105877. GLTF2._ArrayItem.Assign(animation.samplers);
  105878. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  105879. var channel = _a[_i];
  105880. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  105881. }
  105882. return Promise.all(promises).then(function () {
  105883. babylonAnimationGroup.normalize(_this._normalizeAnimationGroupsToBeginAtZero ? 0 : null);
  105884. });
  105885. };
  105886. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  105887. var _this = this;
  105888. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  105889. // Ignore animations that have no animation targets.
  105890. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  105891. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonMesh)) {
  105892. return Promise.resolve();
  105893. }
  105894. // Ignore animations targeting TRS of skinned nodes.
  105895. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  105896. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  105897. return Promise.resolve();
  105898. }
  105899. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  105900. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  105901. var targetPath;
  105902. var animationType;
  105903. switch (channel.target.path) {
  105904. case "translation" /* TRANSLATION */: {
  105905. targetPath = "position";
  105906. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  105907. break;
  105908. }
  105909. case "rotation" /* ROTATION */: {
  105910. targetPath = "rotationQuaternion";
  105911. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  105912. break;
  105913. }
  105914. case "scale" /* SCALE */: {
  105915. targetPath = "scaling";
  105916. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  105917. break;
  105918. }
  105919. case "weights" /* WEIGHTS */: {
  105920. targetPath = "influence";
  105921. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  105922. break;
  105923. }
  105924. default: {
  105925. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  105926. }
  105927. }
  105928. var outputBufferOffset = 0;
  105929. var getNextOutputValue;
  105930. switch (targetPath) {
  105931. case "position": {
  105932. getNextOutputValue = function () {
  105933. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  105934. outputBufferOffset += 3;
  105935. return value;
  105936. };
  105937. break;
  105938. }
  105939. case "rotationQuaternion": {
  105940. getNextOutputValue = function () {
  105941. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  105942. outputBufferOffset += 4;
  105943. return value;
  105944. };
  105945. break;
  105946. }
  105947. case "scaling": {
  105948. getNextOutputValue = function () {
  105949. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  105950. outputBufferOffset += 3;
  105951. return value;
  105952. };
  105953. break;
  105954. }
  105955. case "influence": {
  105956. getNextOutputValue = function () {
  105957. var value = new Array(targetNode._numMorphTargets);
  105958. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  105959. value[i] = data.output[outputBufferOffset++];
  105960. }
  105961. return value;
  105962. };
  105963. break;
  105964. }
  105965. }
  105966. var getNextKey;
  105967. switch (data.interpolation) {
  105968. case "STEP" /* STEP */: {
  105969. getNextKey = function (frameIndex) { return ({
  105970. frame: data.input[frameIndex],
  105971. value: getNextOutputValue(),
  105972. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  105973. }); };
  105974. break;
  105975. }
  105976. case "LINEAR" /* LINEAR */: {
  105977. getNextKey = function (frameIndex) { return ({
  105978. frame: data.input[frameIndex],
  105979. value: getNextOutputValue()
  105980. }); };
  105981. break;
  105982. }
  105983. case "CUBICSPLINE" /* CUBICSPLINE */: {
  105984. getNextKey = function (frameIndex) { return ({
  105985. frame: data.input[frameIndex],
  105986. inTangent: getNextOutputValue(),
  105987. value: getNextOutputValue(),
  105988. outTangent: getNextOutputValue()
  105989. }); };
  105990. break;
  105991. }
  105992. }
  105993. var keys = new Array(data.input.length);
  105994. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  105995. keys[frameIndex] = getNextKey(frameIndex);
  105996. }
  105997. if (targetPath === "influence") {
  105998. var _loop_1 = function (targetIndex) {
  105999. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  106000. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  106001. babylonAnimation.setKeys(keys.map(function (key) { return ({
  106002. frame: key.frame,
  106003. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  106004. value: key.value[targetIndex],
  106005. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  106006. }); }));
  106007. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  106008. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  106009. var babylonAnimationClone = babylonAnimation.clone();
  106010. morphTarget.animations.push(babylonAnimationClone);
  106011. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  106012. });
  106013. };
  106014. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  106015. _loop_1(targetIndex);
  106016. }
  106017. }
  106018. else {
  106019. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  106020. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  106021. babylonAnimation.setKeys(keys);
  106022. if (targetNode._babylonBones) {
  106023. var babylonAnimationTargets = [targetNode._babylonMesh].concat(targetNode._babylonBones);
  106024. for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {
  106025. var babylonAnimationTarget = babylonAnimationTargets_1[_i];
  106026. babylonAnimationTarget.animations.push(babylonAnimation);
  106027. }
  106028. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);
  106029. }
  106030. else {
  106031. targetNode._babylonMesh.animations.push(babylonAnimation);
  106032. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh);
  106033. }
  106034. }
  106035. });
  106036. };
  106037. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  106038. if (sampler._data) {
  106039. return sampler._data;
  106040. }
  106041. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  106042. switch (interpolation) {
  106043. case "STEP" /* STEP */:
  106044. case "LINEAR" /* LINEAR */:
  106045. case "CUBICSPLINE" /* CUBICSPLINE */: {
  106046. break;
  106047. }
  106048. default: {
  106049. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  106050. }
  106051. }
  106052. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  106053. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  106054. sampler._data = Promise.all([
  106055. this._loadFloatAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor),
  106056. this._loadFloatAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor)
  106057. ]).then(function (_a) {
  106058. var inputData = _a[0], outputData = _a[1];
  106059. return {
  106060. input: inputData,
  106061. interpolation: interpolation,
  106062. output: outputData,
  106063. };
  106064. });
  106065. return sampler._data;
  106066. };
  106067. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  106068. if (buffer._data) {
  106069. return buffer._data;
  106070. }
  106071. if (!buffer.uri) {
  106072. throw new Error(context + ": Uri is missing");
  106073. }
  106074. buffer._data = this._loadUriAsync(context, buffer.uri);
  106075. return buffer._data;
  106076. };
  106077. /** @hidden */
  106078. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  106079. if (bufferView._data) {
  106080. return bufferView._data;
  106081. }
  106082. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  106083. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) {
  106084. try {
  106085. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  106086. }
  106087. catch (e) {
  106088. throw new Error(context + ": " + e.message);
  106089. }
  106090. });
  106091. return bufferView._data;
  106092. };
  106093. GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  106094. if (accessor.type !== "SCALAR" /* SCALAR */) {
  106095. throw new Error(context + ": Invalid type " + accessor.type);
  106096. }
  106097. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  106098. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  106099. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  106100. throw new Error(context + ": Invalid component type " + accessor.componentType);
  106101. }
  106102. if (accessor._data) {
  106103. return accessor._data;
  106104. }
  106105. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  106106. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  106107. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  106108. });
  106109. return accessor._data;
  106110. };
  106111. GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {
  106112. // TODO: support normalized and stride
  106113. var _this = this;
  106114. if (accessor.componentType !== 5126 /* FLOAT */) {
  106115. throw new Error("Invalid component type " + accessor.componentType);
  106116. }
  106117. if (accessor._data) {
  106118. return accessor._data;
  106119. }
  106120. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  106121. var length = numComponents * accessor.count;
  106122. if (accessor.bufferView == undefined) {
  106123. accessor._data = Promise.resolve(new Float32Array(length));
  106124. }
  106125. else {
  106126. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  106127. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  106128. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  106129. });
  106130. }
  106131. if (accessor.sparse) {
  106132. var sparse_1 = accessor.sparse;
  106133. accessor._data = accessor._data.then(function (data) {
  106134. var indicesBufferView = GLTFLoader._GetProperty(context + "/sparse/indices/bufferView", _this._gltf.bufferViews, sparse_1.indices.bufferView);
  106135. var valuesBufferView = GLTFLoader._GetProperty(context + "/sparse/values/bufferView", _this._gltf.bufferViews, sparse_1.values.bufferView);
  106136. return Promise.all([
  106137. _this._loadBufferViewAsync("#/bufferViews/" + indicesBufferView._index, indicesBufferView),
  106138. _this._loadBufferViewAsync("#/bufferViews/" + valuesBufferView._index, valuesBufferView)
  106139. ]).then(function (_a) {
  106140. var indicesData = _a[0], valuesData = _a[1];
  106141. var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  106142. var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  106143. var valuesIndex = 0;
  106144. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  106145. var dataIndex = indices[indicesIndex] * numComponents;
  106146. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  106147. data[dataIndex++] = values[valuesIndex++];
  106148. }
  106149. }
  106150. return data;
  106151. });
  106152. });
  106153. }
  106154. return accessor._data;
  106155. };
  106156. /** @hidden */
  106157. GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {
  106158. var _this = this;
  106159. if (bufferView._babylonBuffer) {
  106160. return bufferView._babylonBuffer;
  106161. }
  106162. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {
  106163. return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);
  106164. });
  106165. return bufferView._babylonBuffer;
  106166. };
  106167. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  106168. var _this = this;
  106169. if (accessor._babylonVertexBuffer) {
  106170. return accessor._babylonVertexBuffer;
  106171. }
  106172. if (accessor.sparse) {
  106173. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(context, accessor).then(function (data) {
  106174. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), data, kind, false);
  106175. });
  106176. }
  106177. else {
  106178. var bufferView_1 = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  106179. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView_1._index, bufferView_1, kind).then(function (buffer) {
  106180. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  106181. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  106182. });
  106183. }
  106184. return accessor._babylonVertexBuffer;
  106185. };
  106186. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  106187. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  106188. if (!babylonMaterial) {
  106189. babylonMaterial = this._createMaterial("__gltf_default", drawMode);
  106190. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  106191. babylonMaterial.metallic = 1;
  106192. babylonMaterial.roughness = 1;
  106193. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  106194. }
  106195. return babylonMaterial;
  106196. };
  106197. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  106198. var promises = new Array();
  106199. // Ensure metallic workflow
  106200. babylonMaterial.metallic = 1;
  106201. babylonMaterial.roughness = 1;
  106202. var properties = material.pbrMetallicRoughness;
  106203. if (properties) {
  106204. if (properties.baseColorFactor) {
  106205. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  106206. babylonMaterial.alpha = properties.baseColorFactor[3];
  106207. }
  106208. else {
  106209. babylonMaterial.albedoColor = BABYLON.Color3.White();
  106210. }
  106211. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  106212. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  106213. if (properties.baseColorTexture) {
  106214. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  106215. babylonMaterial.albedoTexture = texture;
  106216. }));
  106217. }
  106218. if (properties.metallicRoughnessTexture) {
  106219. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  106220. babylonMaterial.metallicTexture = texture;
  106221. }));
  106222. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  106223. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  106224. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  106225. }
  106226. }
  106227. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  106228. return Promise.all(promises).then(function () { });
  106229. };
  106230. /** @hidden */
  106231. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  106232. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, babylonDrawMode, assign);
  106233. if (promise) {
  106234. return promise;
  106235. }
  106236. material._babylonData = material._babylonData || {};
  106237. var babylonData = material._babylonData[babylonDrawMode];
  106238. if (!babylonData) {
  106239. var promises = new Array();
  106240. var name_3 = material.name || "materialSG_" + material._index;
  106241. var babylonMaterial = this._createMaterial(name_3, babylonDrawMode);
  106242. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  106243. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  106244. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  106245. babylonData = {
  106246. material: babylonMaterial,
  106247. meshes: [],
  106248. loaded: Promise.all(promises).then(function () { })
  106249. };
  106250. material._babylonData[babylonDrawMode] = babylonData;
  106251. }
  106252. babylonData.meshes.push(babylonMesh);
  106253. assign(babylonData.material);
  106254. return babylonData.loaded;
  106255. };
  106256. /** @hidden */
  106257. GLTFLoader.prototype._createMaterial = function (name, drawMode) {
  106258. var babylonMaterial = new BABYLON.PBRMaterial(name, this._babylonScene);
  106259. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  106260. babylonMaterial.fillMode = drawMode;
  106261. babylonMaterial.enableSpecularAntiAliasing = true;
  106262. babylonMaterial.useRadianceOverAlpha = !this.transparencyAsCoverage;
  106263. babylonMaterial.useSpecularOverAlpha = !this.transparencyAsCoverage;
  106264. return babylonMaterial;
  106265. };
  106266. /** @hidden */
  106267. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  106268. var promises = new Array();
  106269. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  106270. if (material.doubleSided) {
  106271. babylonMaterial.backFaceCulling = false;
  106272. babylonMaterial.twoSidedLighting = true;
  106273. }
  106274. if (material.normalTexture) {
  106275. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  106276. babylonMaterial.bumpTexture = texture;
  106277. }));
  106278. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  106279. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  106280. if (material.normalTexture.scale != undefined) {
  106281. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  106282. }
  106283. }
  106284. if (material.occlusionTexture) {
  106285. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  106286. babylonMaterial.ambientTexture = texture;
  106287. }));
  106288. babylonMaterial.useAmbientInGrayScale = true;
  106289. if (material.occlusionTexture.strength != undefined) {
  106290. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  106291. }
  106292. }
  106293. if (material.emissiveTexture) {
  106294. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  106295. babylonMaterial.emissiveTexture = texture;
  106296. }));
  106297. }
  106298. return Promise.all(promises).then(function () { });
  106299. };
  106300. /** @hidden */
  106301. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  106302. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  106303. switch (alphaMode) {
  106304. case "OPAQUE" /* OPAQUE */: {
  106305. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  106306. break;
  106307. }
  106308. case "MASK" /* MASK */: {
  106309. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  106310. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  106311. if (babylonMaterial.albedoTexture) {
  106312. babylonMaterial.albedoTexture.hasAlpha = true;
  106313. }
  106314. break;
  106315. }
  106316. case "BLEND" /* BLEND */: {
  106317. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  106318. if (babylonMaterial.albedoTexture) {
  106319. babylonMaterial.albedoTexture.hasAlpha = true;
  106320. babylonMaterial.useAlphaFromAlbedoTexture = true;
  106321. }
  106322. break;
  106323. }
  106324. default: {
  106325. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  106326. }
  106327. }
  106328. };
  106329. /** @hidden */
  106330. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  106331. var _this = this;
  106332. var promise = GLTF2.GLTFLoaderExtension._LoadTextureAsync(this, context, textureInfo, assign);
  106333. if (promise) {
  106334. return promise;
  106335. }
  106336. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  106337. context = "#/textures/" + textureInfo.index;
  106338. var promises = new Array();
  106339. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  106340. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  106341. var deferred = new BABYLON.Deferred();
  106342. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  106343. if (!_this._disposed) {
  106344. deferred.resolve();
  106345. }
  106346. }, function (message, exception) {
  106347. if (!_this._disposed) {
  106348. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  106349. }
  106350. });
  106351. promises.push(deferred.promise);
  106352. babylonTexture.name = texture.name || "texture" + texture._index;
  106353. babylonTexture.wrapU = samplerData.wrapU;
  106354. babylonTexture.wrapV = samplerData.wrapV;
  106355. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  106356. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  106357. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (blob) {
  106358. var dataUrl = "data:" + _this._rootUrl + (image.uri || "image" + image._index);
  106359. babylonTexture.updateURL(dataUrl, blob);
  106360. }));
  106361. assign(babylonTexture);
  106362. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  106363. return Promise.all(promises).then(function () { });
  106364. };
  106365. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  106366. if (!sampler._data) {
  106367. sampler._data = {
  106368. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  106369. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  106370. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  106371. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  106372. };
  106373. }
  106374. ;
  106375. return sampler._data;
  106376. };
  106377. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  106378. if (image._blob) {
  106379. return image._blob;
  106380. }
  106381. var promise;
  106382. if (image.uri) {
  106383. promise = this._loadUriAsync(context, image.uri);
  106384. }
  106385. else {
  106386. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  106387. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  106388. }
  106389. image._blob = promise.then(function (data) {
  106390. return new Blob([data], { type: image.mimeType });
  106391. });
  106392. return image._blob;
  106393. };
  106394. /** @hidden */
  106395. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  106396. var _this = this;
  106397. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  106398. if (promise) {
  106399. return promise;
  106400. }
  106401. if (!GLTFLoader._ValidateUri(uri)) {
  106402. throw new Error(context + ": Uri '" + uri + "' is invalid");
  106403. }
  106404. if (BABYLON.Tools.IsBase64(uri)) {
  106405. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  106406. }
  106407. return this.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  106408. return new Promise(function (resolve, reject) {
  106409. if (!_this._disposed) {
  106410. var request_1 = BABYLON.Tools.LoadFile(url, function (data) {
  106411. if (!_this._disposed) {
  106412. resolve(new Uint8Array(data));
  106413. }
  106414. }, function (event) {
  106415. if (!_this._disposed) {
  106416. try {
  106417. if (request_1 && _this._state === BABYLON.GLTFLoaderState.LOADING) {
  106418. request_1._lengthComputable = event.lengthComputable;
  106419. request_1._loaded = event.loaded;
  106420. request_1._total = event.total;
  106421. _this._onProgress();
  106422. }
  106423. }
  106424. catch (e) {
  106425. reject(e);
  106426. }
  106427. }
  106428. }, _this._babylonScene.database, true, function (request, exception) {
  106429. if (!_this._disposed) {
  106430. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  106431. }
  106432. });
  106433. _this._requests.push(request_1);
  106434. }
  106435. });
  106436. });
  106437. };
  106438. GLTFLoader.prototype._onProgress = function () {
  106439. if (!this._progressCallback) {
  106440. return;
  106441. }
  106442. var lengthComputable = true;
  106443. var loaded = 0;
  106444. var total = 0;
  106445. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  106446. var request = _a[_i];
  106447. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  106448. return;
  106449. }
  106450. lengthComputable = lengthComputable && request._lengthComputable;
  106451. loaded += request._loaded;
  106452. total += request._total;
  106453. }
  106454. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  106455. };
  106456. /** @hidden */
  106457. GLTFLoader._GetProperty = function (context, array, index) {
  106458. if (!array || index == undefined || !array[index]) {
  106459. throw new Error(context + ": Failed to find index (" + index + ")");
  106460. }
  106461. return array[index];
  106462. };
  106463. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  106464. // Set defaults if undefined
  106465. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  106466. switch (mode) {
  106467. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  106468. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  106469. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  106470. default:
  106471. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  106472. return BABYLON.Texture.WRAP_ADDRESSMODE;
  106473. }
  106474. };
  106475. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  106476. // Set defaults if undefined
  106477. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  106478. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  106479. if (magFilter === 9729 /* LINEAR */) {
  106480. switch (minFilter) {
  106481. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  106482. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  106483. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  106484. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  106485. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  106486. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  106487. default:
  106488. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  106489. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  106490. }
  106491. }
  106492. else {
  106493. if (magFilter !== 9728 /* NEAREST */) {
  106494. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  106495. }
  106496. switch (minFilter) {
  106497. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  106498. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  106499. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  106500. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  106501. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  106502. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  106503. default:
  106504. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  106505. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  106506. }
  106507. }
  106508. };
  106509. GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  106510. var buffer = bufferView.buffer;
  106511. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  106512. try {
  106513. switch (componentType) {
  106514. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  106515. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  106516. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  106517. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  106518. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  106519. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  106520. default: throw new Error("Invalid component type " + componentType);
  106521. }
  106522. }
  106523. catch (e) {
  106524. throw new Error(context + ": " + e);
  106525. }
  106526. };
  106527. GLTFLoader._GetNumComponents = function (context, type) {
  106528. switch (type) {
  106529. case "SCALAR": return 1;
  106530. case "VEC2": return 2;
  106531. case "VEC3": return 3;
  106532. case "VEC4": return 4;
  106533. case "MAT2": return 4;
  106534. case "MAT3": return 9;
  106535. case "MAT4": return 16;
  106536. }
  106537. throw new Error(context + ": Invalid type (" + type + ")");
  106538. };
  106539. GLTFLoader._ValidateUri = function (uri) {
  106540. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  106541. };
  106542. GLTFLoader._GetDrawMode = function (context, mode) {
  106543. if (mode == undefined) {
  106544. mode = 4 /* TRIANGLES */;
  106545. }
  106546. switch (mode) {
  106547. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  106548. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  106549. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  106550. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  106551. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  106552. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  106553. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  106554. }
  106555. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  106556. };
  106557. GLTFLoader.prototype._compileMaterialsAsync = function () {
  106558. var promises = new Array();
  106559. if (this._gltf.materials) {
  106560. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  106561. var material = _a[_i];
  106562. if (material._babylonData) {
  106563. for (var babylonDrawMode in material._babylonData) {
  106564. var babylonData = material._babylonData[babylonDrawMode];
  106565. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  106566. var babylonMesh = _c[_b];
  106567. // Ensure nonUniformScaling is set if necessary.
  106568. babylonMesh.computeWorldMatrix(true);
  106569. var babylonMaterial = babylonData.material;
  106570. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  106571. if (this.useClipPlane) {
  106572. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  106573. }
  106574. }
  106575. }
  106576. }
  106577. }
  106578. }
  106579. return Promise.all(promises).then(function () { });
  106580. };
  106581. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  106582. var promises = new Array();
  106583. var lights = this._babylonScene.lights;
  106584. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  106585. var light = lights_1[_i];
  106586. var generator = light.getShadowGenerator();
  106587. if (generator) {
  106588. promises.push(generator.forceCompilationAsync());
  106589. }
  106590. }
  106591. return Promise.all(promises).then(function () { });
  106592. };
  106593. GLTFLoader.prototype._clear = function () {
  106594. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  106595. var request = _a[_i];
  106596. request.abort();
  106597. }
  106598. this._requests.length = 0;
  106599. delete this._gltf;
  106600. delete this._babylonScene;
  106601. this._completePromises.length = 0;
  106602. this._onReadyObservable.clear();
  106603. for (var name_4 in this._extensions) {
  106604. this._extensions[name_4].dispose();
  106605. }
  106606. this._extensions = {};
  106607. delete this._rootBabylonMesh;
  106608. delete this._progressCallback;
  106609. this.onMeshLoadedObservable.clear();
  106610. this.onTextureLoadedObservable.clear();
  106611. this.onMaterialLoadedObservable.clear();
  106612. this.onCameraLoadedObservable.clear();
  106613. };
  106614. /** @hidden */
  106615. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  106616. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  106617. var name_5 = _a[_i];
  106618. var extension = this._extensions[name_5];
  106619. if (extension.enabled) {
  106620. var promise = actionAsync(extension);
  106621. if (promise) {
  106622. return promise;
  106623. }
  106624. }
  106625. }
  106626. return null;
  106627. };
  106628. GLTFLoader._ExtensionNames = new Array();
  106629. GLTFLoader._ExtensionFactories = {};
  106630. return GLTFLoader;
  106631. }());
  106632. GLTF2.GLTFLoader = GLTFLoader;
  106633. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  106634. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106635. })(BABYLON || (BABYLON = {}));
  106636. //# sourceMappingURL=babylon.glTFLoader.js.map
  106637. var BABYLON;
  106638. (function (BABYLON) {
  106639. var GLTF2;
  106640. (function (GLTF2) {
  106641. /**
  106642. * Abstract class that can be implemented to extend existing glTF loader behavior.
  106643. */
  106644. var GLTFLoaderExtension = /** @class */ (function () {
  106645. function GLTFLoaderExtension(loader) {
  106646. this.enabled = true;
  106647. this._loader = loader;
  106648. }
  106649. GLTFLoaderExtension.prototype.dispose = function () {
  106650. delete this._loader;
  106651. };
  106652. // #region Overridable Methods
  106653. /** Override this method to modify the default behavior for loading scenes. */
  106654. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  106655. /** Override this method to modify the default behavior for loading nodes. */
  106656. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  106657. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  106658. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  106659. /** Override this method to modify the default behavior for loading materials. */
  106660. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) { return null; };
  106661. /** Override this method to modify the default behavior for loading textures. */
  106662. GLTFLoaderExtension.prototype._loadTextureAsync = function (context, textureInfo, assign) { return null; };
  106663. /** Override this method to modify the default behavior for loading uris. */
  106664. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  106665. // #endregion
  106666. /** Helper method called by a loader extension to load an glTF extension. */
  106667. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  106668. if (!property.extensions) {
  106669. return null;
  106670. }
  106671. var extensions = property.extensions;
  106672. var extension = extensions[this.name];
  106673. if (!extension) {
  106674. return null;
  106675. }
  106676. // Clear out the extension before executing the action to avoid recursing into the same property.
  106677. delete extensions[this.name];
  106678. try {
  106679. return actionAsync(context + "/extensions/" + this.name, extension);
  106680. }
  106681. finally {
  106682. // Restore the extension after executing the action.
  106683. extensions[this.name] = extension;
  106684. }
  106685. };
  106686. /** Helper method called by the loader to allow extensions to override loading scenes. */
  106687. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  106688. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  106689. };
  106690. /** Helper method called by the loader to allow extensions to override loading nodes. */
  106691. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  106692. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  106693. };
  106694. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  106695. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  106696. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  106697. };
  106698. /** Helper method called by the loader to allow extensions to override loading materials. */
  106699. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, babylonDrawMode, assign) {
  106700. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  106701. };
  106702. /** Helper method called by the loader to allow extensions to override loading textures. */
  106703. GLTFLoaderExtension._LoadTextureAsync = function (loader, context, textureInfo, assign) {
  106704. return loader._applyExtensions(function (extension) { return extension._loadTextureAsync(context, textureInfo, assign); });
  106705. };
  106706. /** Helper method called by the loader to allow extensions to override loading uris. */
  106707. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  106708. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  106709. };
  106710. return GLTFLoaderExtension;
  106711. }());
  106712. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  106713. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106714. })(BABYLON || (BABYLON = {}));
  106715. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  106716. var BABYLON;
  106717. (function (BABYLON) {
  106718. var GLTF2;
  106719. (function (GLTF2) {
  106720. var Extensions;
  106721. (function (Extensions) {
  106722. var NAME = "MSFT_lod";
  106723. /**
  106724. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  106725. */
  106726. var MSFT_lod = /** @class */ (function (_super) {
  106727. __extends(MSFT_lod, _super);
  106728. function MSFT_lod(loader) {
  106729. var _this = _super.call(this, loader) || this;
  106730. _this.name = NAME;
  106731. /**
  106732. * Maximum number of LODs to load, starting from the lowest LOD.
  106733. */
  106734. _this.maxLODsToLoad = Number.MAX_VALUE;
  106735. /**
  106736. * Observable raised when all node LODs of one level are loaded.
  106737. * The event data is the index of the loaded LOD starting from zero.
  106738. * Dispose the loader to cancel the loading of the next level of LODs.
  106739. */
  106740. _this.onNodeLODsLoadedObservable = new BABYLON.Observable();
  106741. /**
  106742. * Observable raised when all material LODs of one level are loaded.
  106743. * The event data is the index of the loaded LOD starting from zero.
  106744. * Dispose the loader to cancel the loading of the next level of LODs.
  106745. */
  106746. _this.onMaterialLODsLoadedObservable = new BABYLON.Observable();
  106747. _this._loadingNodeLOD = null;
  106748. _this._loadNodeSignals = {};
  106749. _this._loadNodePromises = new Array();
  106750. _this._loadingMaterialLOD = null;
  106751. _this._loadMaterialSignals = {};
  106752. _this._loadMaterialPromises = new Array();
  106753. _this._loader._onReadyObservable.addOnce(function () {
  106754. var _loop_1 = function (indexLOD) {
  106755. Promise.all(_this._loadNodePromises[indexLOD]).then(function () {
  106756. _this.onNodeLODsLoadedObservable.notifyObservers(indexLOD);
  106757. });
  106758. };
  106759. for (var indexLOD = 0; indexLOD < _this._loadNodePromises.length; indexLOD++) {
  106760. _loop_1(indexLOD);
  106761. }
  106762. var _loop_2 = function (indexLOD) {
  106763. Promise.all(_this._loadMaterialPromises[indexLOD]).then(function () {
  106764. _this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD);
  106765. });
  106766. };
  106767. for (var indexLOD = 0; indexLOD < _this._loadMaterialPromises.length; indexLOD++) {
  106768. _loop_2(indexLOD);
  106769. }
  106770. });
  106771. return _this;
  106772. }
  106773. MSFT_lod.prototype.dispose = function () {
  106774. _super.prototype.dispose.call(this);
  106775. this._loadingNodeLOD = null;
  106776. this._loadNodeSignals = {};
  106777. this._loadingMaterialLOD = null;
  106778. this._loadMaterialSignals = {};
  106779. this.onMaterialLODsLoadedObservable.clear();
  106780. this.onNodeLODsLoadedObservable.clear();
  106781. };
  106782. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  106783. var _this = this;
  106784. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  106785. var firstPromise;
  106786. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);
  106787. var _loop_3 = function (indexLOD) {
  106788. var nodeLOD = nodeLODs[indexLOD];
  106789. if (indexLOD !== 0) {
  106790. _this._loadingNodeLOD = nodeLOD;
  106791. if (!_this._loadNodeSignals[nodeLOD._index]) {
  106792. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  106793. }
  106794. }
  106795. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  106796. if (indexLOD !== 0) {
  106797. var previousNodeLOD = nodeLODs[indexLOD - 1];
  106798. if (previousNodeLOD._babylonMesh) {
  106799. previousNodeLOD._babylonMesh.dispose(false, true);
  106800. delete previousNodeLOD._babylonMesh;
  106801. }
  106802. }
  106803. if (indexLOD !== nodeLODs.length - 1) {
  106804. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  106805. if (_this._loadNodeSignals[nodeIndex]) {
  106806. _this._loadNodeSignals[nodeIndex].resolve();
  106807. delete _this._loadNodeSignals[nodeIndex];
  106808. }
  106809. }
  106810. });
  106811. if (indexLOD === 0) {
  106812. firstPromise = promise;
  106813. }
  106814. else {
  106815. _this._loader._completePromises.push(promise);
  106816. _this._loadingNodeLOD = null;
  106817. }
  106818. _this._loadNodePromises[indexLOD] = _this._loadNodePromises[indexLOD] || [];
  106819. _this._loadNodePromises[indexLOD].push(promise);
  106820. };
  106821. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  106822. _loop_3(indexLOD);
  106823. }
  106824. return firstPromise;
  106825. });
  106826. };
  106827. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  106828. var _this = this;
  106829. // Don't load material LODs if already loading a node LOD.
  106830. if (this._loadingNodeLOD) {
  106831. return null;
  106832. }
  106833. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  106834. var firstPromise;
  106835. var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);
  106836. var _loop_4 = function (indexLOD) {
  106837. var materialLOD = materialLODs[indexLOD];
  106838. if (indexLOD !== 0) {
  106839. _this._loadingMaterialLOD = materialLOD;
  106840. if (!_this._loadMaterialSignals[materialLOD._index]) {
  106841. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  106842. }
  106843. }
  106844. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  106845. if (indexLOD !== 0) {
  106846. var babylonDataLOD = materialLOD._babylonData;
  106847. assign(babylonDataLOD[babylonDrawMode].material);
  106848. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  106849. if (previousBabylonDataLOD[babylonDrawMode]) {
  106850. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  106851. delete previousBabylonDataLOD[babylonDrawMode];
  106852. }
  106853. }
  106854. if (indexLOD !== materialLODs.length - 1) {
  106855. var materialIndex = materialLODs[indexLOD + 1]._index;
  106856. if (_this._loadMaterialSignals[materialIndex]) {
  106857. _this._loadMaterialSignals[materialIndex].resolve();
  106858. delete _this._loadMaterialSignals[materialIndex];
  106859. }
  106860. }
  106861. });
  106862. if (indexLOD === 0) {
  106863. firstPromise = promise;
  106864. }
  106865. else {
  106866. _this._loader._completePromises.push(promise);
  106867. _this._loadingMaterialLOD = null;
  106868. }
  106869. _this._loadMaterialPromises[indexLOD] = _this._loadMaterialPromises[indexLOD] || [];
  106870. _this._loadMaterialPromises[indexLOD].push(promise);
  106871. };
  106872. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  106873. _loop_4(indexLOD);
  106874. }
  106875. return firstPromise;
  106876. });
  106877. };
  106878. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  106879. var _this = this;
  106880. // Defer the loading of uris if loading a material or node LOD.
  106881. if (this._loadingMaterialLOD) {
  106882. var index = this._loadingMaterialLOD._index;
  106883. return this._loadMaterialSignals[index].promise.then(function () {
  106884. return _this._loader._loadUriAsync(context, uri);
  106885. });
  106886. }
  106887. else if (this._loadingNodeLOD) {
  106888. var index = this._loadingNodeLOD._index;
  106889. return this._loadNodeSignals[index].promise.then(function () {
  106890. return _this._loader._loadUriAsync(context, uri);
  106891. });
  106892. }
  106893. return null;
  106894. };
  106895. /**
  106896. * Gets an array of LOD properties from lowest to highest.
  106897. */
  106898. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  106899. if (this.maxLODsToLoad <= 0) {
  106900. throw new Error("maxLODsToLoad must be greater than zero");
  106901. }
  106902. var properties = new Array();
  106903. for (var i = ids.length - 1; i >= 0; i--) {
  106904. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  106905. if (properties.length === this.maxLODsToLoad) {
  106906. return properties;
  106907. }
  106908. }
  106909. properties.push(property);
  106910. return properties;
  106911. };
  106912. return MSFT_lod;
  106913. }(GLTF2.GLTFLoaderExtension));
  106914. Extensions.MSFT_lod = MSFT_lod;
  106915. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  106916. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  106917. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106918. })(BABYLON || (BABYLON = {}));
  106919. //# sourceMappingURL=MSFT_lod.js.map
  106920. var BABYLON;
  106921. (function (BABYLON) {
  106922. var GLTF2;
  106923. (function (GLTF2) {
  106924. var Extensions;
  106925. (function (Extensions) {
  106926. var NAME = "MSFT_minecraftMesh";
  106927. /** @hidden */
  106928. var MSFT_minecraftMesh = /** @class */ (function (_super) {
  106929. __extends(MSFT_minecraftMesh, _super);
  106930. function MSFT_minecraftMesh(loader) {
  106931. var _this = _super.call(this, loader) || this;
  106932. _this.name = NAME;
  106933. _this._onMaterialLoaded = function (material) {
  106934. if (material.needAlphaBlending()) {
  106935. material.forceDepthWrite = true;
  106936. material.separateCullingPass = true;
  106937. }
  106938. material.backFaceCulling = material.forceDepthWrite;
  106939. material.twoSidedLighting = true;
  106940. };
  106941. var meshes = loader._gltf.meshes;
  106942. if (meshes && meshes.length) {
  106943. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  106944. var mesh = meshes_1[_i];
  106945. if (mesh && mesh.extras && mesh.extras.MSFT_minecraftMesh) {
  106946. _this._loader.onMaterialLoadedObservable.add(_this._onMaterialLoaded);
  106947. break;
  106948. }
  106949. }
  106950. }
  106951. return _this;
  106952. }
  106953. return MSFT_minecraftMesh;
  106954. }(GLTF2.GLTFLoaderExtension));
  106955. Extensions.MSFT_minecraftMesh = MSFT_minecraftMesh;
  106956. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  106957. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  106958. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106959. })(BABYLON || (BABYLON = {}));
  106960. //# sourceMappingURL=MSFT_minecraftMesh.js.map
  106961. var BABYLON;
  106962. (function (BABYLON) {
  106963. var GLTF2;
  106964. (function (GLTF2) {
  106965. var Extensions;
  106966. (function (Extensions) {
  106967. var NAME = "MSFT_sRGBFactors";
  106968. /** @hidden */
  106969. var MSFT_sRGBFactors = /** @class */ (function (_super) {
  106970. __extends(MSFT_sRGBFactors, _super);
  106971. function MSFT_sRGBFactors(loader) {
  106972. var _this = _super.call(this, loader) || this;
  106973. _this.name = NAME;
  106974. _this._onMaterialLoaded = function (material) {
  106975. if (!material.albedoTexture) {
  106976. material.albedoColor.toLinearSpaceToRef(material.albedoColor);
  106977. }
  106978. if (!material.reflectivityTexture) {
  106979. material.reflectivityColor.toLinearSpaceToRef(material.reflectivityColor);
  106980. }
  106981. };
  106982. var materials = loader._gltf.materials;
  106983. if (materials && materials.length) {
  106984. for (var _i = 0, materials_1 = materials; _i < materials_1.length; _i++) {
  106985. var material = materials_1[_i];
  106986. if (material && material.extras && material.extras.MSFT_sRGBFactors) {
  106987. _this._loader.onMaterialLoadedObservable.add(_this._onMaterialLoaded);
  106988. break;
  106989. }
  106990. }
  106991. }
  106992. return _this;
  106993. }
  106994. return MSFT_sRGBFactors;
  106995. }(GLTF2.GLTFLoaderExtension));
  106996. Extensions.MSFT_sRGBFactors = MSFT_sRGBFactors;
  106997. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  106998. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  106999. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  107000. })(BABYLON || (BABYLON = {}));
  107001. //# sourceMappingURL=MSFT_sRGBFactors.js.map
  107002. var BABYLON;
  107003. (function (BABYLON) {
  107004. var GLTF2;
  107005. (function (GLTF2) {
  107006. var Extensions;
  107007. (function (Extensions) {
  107008. var NAME = "KHR_draco_mesh_compression";
  107009. /**
  107010. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  107011. */
  107012. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  107013. __extends(KHR_draco_mesh_compression, _super);
  107014. function KHR_draco_mesh_compression(loader) {
  107015. var _this = _super.call(this, loader) || this;
  107016. _this.name = NAME;
  107017. _this._dracoCompression = null;
  107018. // Disable extension if decoder is not available.
  107019. if (!BABYLON.DracoCompression.DecoderAvailable) {
  107020. _this.enabled = false;
  107021. }
  107022. return _this;
  107023. }
  107024. KHR_draco_mesh_compression.prototype.dispose = function () {
  107025. if (this._dracoCompression) {
  107026. this._dracoCompression.dispose();
  107027. }
  107028. _super.prototype.dispose.call(this);
  107029. };
  107030. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  107031. var _this = this;
  107032. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  107033. if (primitive.mode != undefined) {
  107034. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  107035. primitive.mode !== 4 /* TRIANGLES */) {
  107036. throw new Error(context + ": Unsupported mode " + primitive.mode);
  107037. }
  107038. // TODO: handle triangle strips
  107039. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  107040. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  107041. }
  107042. }
  107043. var attributes = {};
  107044. var loadAttribute = function (name, kind) {
  107045. var uniqueId = extension.attributes[name];
  107046. if (uniqueId == undefined) {
  107047. return;
  107048. }
  107049. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  107050. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  107051. babylonMesh._delayInfo.push(kind);
  107052. }
  107053. attributes[kind] = uniqueId;
  107054. };
  107055. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  107056. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  107057. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  107058. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  107059. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  107060. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  107061. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  107062. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  107063. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  107064. if (!bufferView._dracoBabylonGeometry) {
  107065. bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  107066. if (!_this._dracoCompression) {
  107067. _this._dracoCompression = new BABYLON.DracoCompression();
  107068. }
  107069. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  107070. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);
  107071. babylonVertexData.applyToGeometry(babylonGeometry);
  107072. return babylonGeometry;
  107073. }).catch(function (error) {
  107074. throw new Error(context + ": " + error.message);
  107075. });
  107076. });
  107077. }
  107078. return bufferView._dracoBabylonGeometry;
  107079. });
  107080. };
  107081. return KHR_draco_mesh_compression;
  107082. }(GLTF2.GLTFLoaderExtension));
  107083. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  107084. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  107085. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  107086. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  107087. })(BABYLON || (BABYLON = {}));
  107088. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  107089. var BABYLON;
  107090. (function (BABYLON) {
  107091. var GLTF2;
  107092. (function (GLTF2) {
  107093. var Extensions;
  107094. (function (Extensions) {
  107095. var NAME = "KHR_materials_pbrSpecularGlossiness";
  107096. /**
  107097. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  107098. */
  107099. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  107100. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  107101. function KHR_materials_pbrSpecularGlossiness() {
  107102. var _this = _super !== null && _super.apply(this, arguments) || this;
  107103. _this.name = NAME;
  107104. return _this;
  107105. }
  107106. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  107107. var _this = this;
  107108. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  107109. material._babylonData = material._babylonData || {};
  107110. var babylonData = material._babylonData[babylonDrawMode];
  107111. if (!babylonData) {
  107112. var promises = new Array();
  107113. var name_1 = material.name || "materialSG_" + material._index;
  107114. var babylonMaterial = _this._loader._createMaterial(name_1, babylonDrawMode);
  107115. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  107116. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  107117. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  107118. babylonData = {
  107119. material: babylonMaterial,
  107120. meshes: [],
  107121. loaded: Promise.all(promises).then(function () { })
  107122. };
  107123. material._babylonData[babylonDrawMode] = babylonData;
  107124. }
  107125. babylonData.meshes.push(babylonMesh);
  107126. assign(babylonData.material);
  107127. return babylonData.loaded;
  107128. });
  107129. };
  107130. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  107131. var promises = new Array();
  107132. if (properties.diffuseFactor) {
  107133. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  107134. babylonMaterial.alpha = properties.diffuseFactor[3];
  107135. }
  107136. else {
  107137. babylonMaterial.albedoColor = BABYLON.Color3.White();
  107138. }
  107139. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  107140. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  107141. if (properties.diffuseTexture) {
  107142. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  107143. babylonMaterial.albedoTexture = texture;
  107144. }));
  107145. }
  107146. if (properties.specularGlossinessTexture) {
  107147. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  107148. babylonMaterial.reflectivityTexture = texture;
  107149. }));
  107150. babylonMaterial.reflectivityTexture.hasAlpha = true;
  107151. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  107152. }
  107153. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  107154. return Promise.all(promises).then(function () { });
  107155. };
  107156. return KHR_materials_pbrSpecularGlossiness;
  107157. }(GLTF2.GLTFLoaderExtension));
  107158. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  107159. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  107160. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  107161. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  107162. })(BABYLON || (BABYLON = {}));
  107163. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  107164. var BABYLON;
  107165. (function (BABYLON) {
  107166. var GLTF2;
  107167. (function (GLTF2) {
  107168. var Extensions;
  107169. (function (Extensions) {
  107170. var NAME = "KHR_materials_unlit";
  107171. /**
  107172. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)
  107173. */
  107174. var KHR_materials_unlit = /** @class */ (function (_super) {
  107175. __extends(KHR_materials_unlit, _super);
  107176. function KHR_materials_unlit() {
  107177. var _this = _super !== null && _super.apply(this, arguments) || this;
  107178. _this.name = NAME;
  107179. return _this;
  107180. }
  107181. KHR_materials_unlit.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  107182. var _this = this;
  107183. return this._loadExtensionAsync(context, material, function () {
  107184. material._babylonData = material._babylonData || {};
  107185. var babylonData = material._babylonData[babylonDrawMode];
  107186. if (!babylonData) {
  107187. var name_1 = material.name || "materialUnlit_" + material._index;
  107188. var babylonMaterial = _this._loader._createMaterial(name_1, babylonDrawMode);
  107189. babylonMaterial.unlit = true;
  107190. var promise = _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  107191. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  107192. babylonData = {
  107193. material: babylonMaterial,
  107194. meshes: [],
  107195. loaded: promise
  107196. };
  107197. material._babylonData[babylonDrawMode] = babylonData;
  107198. }
  107199. babylonData.meshes.push(babylonMesh);
  107200. assign(babylonData.material);
  107201. return babylonData.loaded;
  107202. });
  107203. };
  107204. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  107205. var promises = new Array();
  107206. // Ensure metallic workflow
  107207. babylonMaterial.metallic = 1;
  107208. babylonMaterial.roughness = 1;
  107209. var properties = material.pbrMetallicRoughness;
  107210. if (properties) {
  107211. if (properties.baseColorFactor) {
  107212. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  107213. babylonMaterial.alpha = properties.baseColorFactor[3];
  107214. }
  107215. else {
  107216. babylonMaterial.albedoColor = BABYLON.Color3.White();
  107217. }
  107218. if (properties.baseColorTexture) {
  107219. promises.push(this._loader._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  107220. babylonMaterial.albedoTexture = texture;
  107221. }));
  107222. }
  107223. }
  107224. if (material.doubleSided) {
  107225. babylonMaterial.backFaceCulling = false;
  107226. babylonMaterial.twoSidedLighting = true;
  107227. }
  107228. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  107229. return Promise.all(promises).then(function () { });
  107230. };
  107231. return KHR_materials_unlit;
  107232. }(GLTF2.GLTFLoaderExtension));
  107233. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  107234. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  107235. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  107236. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  107237. })(BABYLON || (BABYLON = {}));
  107238. var BABYLON;
  107239. (function (BABYLON) {
  107240. var GLTF2;
  107241. (function (GLTF2) {
  107242. var Extensions;
  107243. (function (Extensions) {
  107244. var NAME = "KHR_lights";
  107245. var LightType;
  107246. (function (LightType) {
  107247. LightType["AMBIENT"] = "ambient";
  107248. LightType["DIRECTIONAL"] = "directional";
  107249. LightType["POINT"] = "point";
  107250. LightType["SPOT"] = "spot";
  107251. })(LightType || (LightType = {}));
  107252. /**
  107253. * [Specification](https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights) (Experimental)
  107254. */
  107255. var KHR_lights = /** @class */ (function (_super) {
  107256. __extends(KHR_lights, _super);
  107257. function KHR_lights() {
  107258. var _this = _super !== null && _super.apply(this, arguments) || this;
  107259. _this.name = NAME;
  107260. return _this;
  107261. }
  107262. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  107263. var _this = this;
  107264. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  107265. var promise = _this._loader._loadSceneAsync(extensionContext, scene);
  107266. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  107267. if (light.type !== LightType.AMBIENT) {
  107268. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  107269. }
  107270. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  107271. return promise;
  107272. });
  107273. };
  107274. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  107275. var _this = this;
  107276. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  107277. var promise = _this._loader._loadNodeAsync(extensionContext, node);
  107278. var babylonLight;
  107279. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  107280. var name = node._babylonMesh.name;
  107281. switch (light.type) {
  107282. case LightType.AMBIENT: {
  107283. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  107284. }
  107285. case LightType.DIRECTIONAL: {
  107286. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  107287. break;
  107288. }
  107289. case LightType.POINT: {
  107290. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  107291. break;
  107292. }
  107293. case LightType.SPOT: {
  107294. var spotLight = light;
  107295. // TODO: support inner and outer cone angles
  107296. //const innerConeAngle = spotLight.innerConeAngle || 0;
  107297. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  107298. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  107299. break;
  107300. }
  107301. default: {
  107302. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  107303. }
  107304. }
  107305. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  107306. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  107307. babylonLight.parent = node._babylonMesh;
  107308. return promise;
  107309. });
  107310. };
  107311. Object.defineProperty(KHR_lights.prototype, "_lights", {
  107312. get: function () {
  107313. var extensions = this._loader._gltf.extensions;
  107314. if (!extensions || !extensions[this.name]) {
  107315. throw new Error("#/extensions: '" + this.name + "' not found");
  107316. }
  107317. var extension = extensions[this.name];
  107318. return extension.lights;
  107319. },
  107320. enumerable: true,
  107321. configurable: true
  107322. });
  107323. return KHR_lights;
  107324. }(GLTF2.GLTFLoaderExtension));
  107325. Extensions.KHR_lights = KHR_lights;
  107326. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  107327. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  107328. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  107329. })(BABYLON || (BABYLON = {}));
  107330. var BABYLON;
  107331. (function (BABYLON) {
  107332. var GLTF2;
  107333. (function (GLTF2) {
  107334. var Extensions;
  107335. (function (Extensions) {
  107336. var NAME = "KHR_texture_transform";
  107337. /**
  107338. * [Specification](https://github.com/AltspaceVR/glTF/blob/avr-sampler-offset-tile/extensions/2.0/Khronos/KHR_texture_transform/README.md) (Experimental)
  107339. */
  107340. var KHR_texture_transform = /** @class */ (function (_super) {
  107341. __extends(KHR_texture_transform, _super);
  107342. function KHR_texture_transform() {
  107343. var _this = _super !== null && _super.apply(this, arguments) || this;
  107344. _this.name = NAME;
  107345. return _this;
  107346. }
  107347. KHR_texture_transform.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  107348. var _this = this;
  107349. return this._loadExtensionAsync(context, textureInfo, function (extensionContext, extension) {
  107350. return _this._loader._loadTextureAsync(context, textureInfo, function (babylonTexture) {
  107351. if (extension.offset) {
  107352. babylonTexture.uOffset = extension.offset[0];
  107353. babylonTexture.vOffset = extension.offset[1];
  107354. }
  107355. // Always rotate around the origin.
  107356. babylonTexture.uRotationCenter = 0;
  107357. babylonTexture.vRotationCenter = 0;
  107358. if (extension.rotation) {
  107359. babylonTexture.wAng = -extension.rotation;
  107360. }
  107361. if (extension.scale) {
  107362. babylonTexture.uScale = extension.scale[0];
  107363. babylonTexture.vScale = extension.scale[1];
  107364. }
  107365. if (extension.texCoord != undefined) {
  107366. babylonTexture.coordinatesIndex = extension.texCoord;
  107367. }
  107368. assign(babylonTexture);
  107369. });
  107370. });
  107371. };
  107372. return KHR_texture_transform;
  107373. }(GLTF2.GLTFLoaderExtension));
  107374. Extensions.KHR_texture_transform = KHR_texture_transform;
  107375. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_texture_transform(loader); });
  107376. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  107377. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  107378. })(BABYLON || (BABYLON = {}));
  107379. return BABYLON;
  107380. });
  107381. /***/ }),
  107382. /* 24 */
  107383. /***/ (function(module, exports, __webpack_require__) {
  107384. module.exports = __webpack_require__(6);
  107385. /***/ }),
  107386. /* 25 */
  107387. /***/ (function(module, exports) {
  107388. var g;
  107389. // This works in non-strict mode
  107390. g = (function() {
  107391. return this;
  107392. })();
  107393. try {
  107394. // This works if eval is allowed (see CSP)
  107395. g = g || Function("return this")() || (1,eval)("this");
  107396. } catch(e) {
  107397. // This works if the window reference is available
  107398. if(typeof window === "object")
  107399. g = window;
  107400. }
  107401. // g can still be undefined, but nothing to do about it...
  107402. // We return undefined, instead of nothing here, so it's
  107403. // easier to handle this case. if(!global) { ...}
  107404. module.exports = g;
  107405. /***/ }),
  107406. /* 26 */
  107407. /***/ (function(module, exports) {
  107408. if(typeof CANNON === 'undefined') {var e = new Error("Cannot find module \"CANNON\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  107409. module.exports = CANNON;
  107410. /***/ }),
  107411. /* 27 */
  107412. /***/ (function(module, exports) {
  107413. if(typeof OIMO === 'undefined') {var e = new Error("Cannot find module \"OIMO\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  107414. module.exports = OIMO;
  107415. /***/ }),
  107416. /* 28 */
  107417. /***/ (function(module, exports) {
  107418. if(typeof earcut === 'undefined') {var e = new Error("Cannot find module \"earcut\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  107419. module.exports = earcut;
  107420. /***/ }),
  107421. /* 29 */
  107422. /***/ (function(module, exports, __webpack_require__) {
  107423. "use strict";
  107424. Object.defineProperty(exports, "__esModule", { value: true });
  107425. var babylonjs_1 = __webpack_require__(0);
  107426. var configuration_1 = __webpack_require__(11);
  107427. var viewerModel_1 = __webpack_require__(4);
  107428. var helper_1 = __webpack_require__(2);
  107429. var viewerLabs_1 = __webpack_require__(31);
  107430. var _1 = __webpack_require__(33);
  107431. var SceneManager = /** @class */ (function () {
  107432. function SceneManager(_viewer) {
  107433. var _this = this;
  107434. this._viewer = _viewer;
  107435. this._animationBlendingEnabled = true;
  107436. this._mainColor = babylonjs_1.Color3.White();
  107437. this._reflectionColor = babylonjs_1.Color3.White();
  107438. this._white = babylonjs_1.Color3.White();
  107439. this._processShadows = true;
  107440. this._groundEnabled = true;
  107441. this._groundMirrorEnabled = true;
  107442. this._defaultRenderingPipelineEnabled = false;
  107443. this._defaultRenderingPipelineShouldBuild = true;
  107444. // default from rendering pipeline
  107445. this._bloomEnabled = false;
  107446. // default from rendering pipeline
  107447. this._fxaaEnabled = false;
  107448. this._focusOnModel = function (model) {
  107449. var boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  107450. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  107451. var halfSizeVec = sizeVec.scale(0.5);
  107452. var center = boundingInfo.min.add(halfSizeVec);
  107453. _this.camera.setTarget(center);
  107454. _this.camera.alpha = (_this._viewer.configuration.camera && _this._viewer.configuration.camera.alpha) || _this.camera.alpha;
  107455. _this.camera.beta = (_this._viewer.configuration.camera && _this._viewer.configuration.camera.beta) || _this.camera.beta;
  107456. _this.camera.radius = (_this._viewer.configuration.camera && _this._viewer.configuration.camera.radius) || _this.camera.radius;
  107457. };
  107458. this.models = [];
  107459. this.onCameraConfiguredObservable = new babylonjs_1.Observable();
  107460. this.onLightsConfiguredObservable = new babylonjs_1.Observable();
  107461. this.onModelsConfiguredObservable = new babylonjs_1.Observable();
  107462. this.onSceneConfiguredObservable = new babylonjs_1.Observable();
  107463. this.onSceneInitObservable = new babylonjs_1.Observable();
  107464. this.onSceneOptimizerConfiguredObservable = new babylonjs_1.Observable();
  107465. this.onEnvironmentConfiguredObservable = new babylonjs_1.Observable();
  107466. this._viewer.onEngineInitObservable.add(function () {
  107467. _this._handleHardwareLimitations();
  107468. });
  107469. this.labs = new viewerLabs_1.ViewerLabs(this);
  107470. this.onSceneInitObservable.add(function (scene) {
  107471. var updateShadows = function () {
  107472. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  107473. var light = _a[_i];
  107474. var generator = light.getShadowGenerator();
  107475. if (generator) {
  107476. // Processing shadows if animates
  107477. var shadowMap = generator.getShadowMap();
  107478. if (shadowMap) {
  107479. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  107480. }
  107481. }
  107482. }
  107483. };
  107484. scene.registerBeforeRender(function () {
  107485. if (scene.animatables && scene.animatables.length > 0) {
  107486. // make sure all models are loaded
  107487. updateShadows();
  107488. }
  107489. else if (!(_this.models.every(function (model) {
  107490. if (!model.shadowsRenderedAfterLoad) {
  107491. model.shadowsRenderedAfterLoad = true;
  107492. return false;
  107493. }
  107494. return model.state === viewerModel_1.ModelState.COMPLETE && !model.currentAnimation;
  107495. }))) {
  107496. updateShadows();
  107497. }
  107498. });
  107499. return _this._viewer.onSceneInitObservable.notifyObserversWithPromise(_this.scene);
  107500. });
  107501. this._viewer.onModelLoadedObservable.add(function (model) {
  107502. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  107503. var light = _a[_i];
  107504. var generator = light.getShadowGenerator();
  107505. if (generator) {
  107506. // Processing shadows if animates
  107507. var shadowMap = generator.getShadowMap();
  107508. if (shadowMap) {
  107509. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  107510. }
  107511. }
  107512. }
  107513. _this._focusOnModel(model);
  107514. });
  107515. }
  107516. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipeline", {
  107517. get: function () {
  107518. return this._defaultRenderingPipeline;
  107519. },
  107520. enumerable: true,
  107521. configurable: true
  107522. });
  107523. Object.defineProperty(SceneManager.prototype, "isHdrSupported", {
  107524. /**
  107525. * Returns a boolean representing HDR support
  107526. */
  107527. get: function () {
  107528. return this._hdrSupport;
  107529. },
  107530. enumerable: true,
  107531. configurable: true
  107532. });
  107533. Object.defineProperty(SceneManager.prototype, "mainColor", {
  107534. /**
  107535. * Return the main color defined in the configuration.
  107536. */
  107537. get: function () {
  107538. return this._mainColor;
  107539. },
  107540. enumerable: true,
  107541. configurable: true
  107542. });
  107543. Object.defineProperty(SceneManager.prototype, "reflectionColor", {
  107544. get: function () {
  107545. return this._reflectionColor;
  107546. },
  107547. enumerable: true,
  107548. configurable: true
  107549. });
  107550. Object.defineProperty(SceneManager.prototype, "animationBlendingEnabled", {
  107551. get: function () {
  107552. return this._animationBlendingEnabled;
  107553. },
  107554. set: function (value) {
  107555. this.scene.animationPropertiesOverride = this.scene.animationPropertiesOverride || new babylonjs_1.AnimationPropertiesOverride();
  107556. this.scene.animationPropertiesOverride.enableBlending = value;
  107557. this._animationBlendingEnabled = value;
  107558. },
  107559. enumerable: true,
  107560. configurable: true
  107561. });
  107562. Object.defineProperty(SceneManager.prototype, "processShadows", {
  107563. /**
  107564. * The flag defining whether shadows are rendered constantly or once.
  107565. */
  107566. get: function () {
  107567. return this._processShadows;
  107568. },
  107569. /**
  107570. * Should shadows be rendered every frame, or only once and stop.
  107571. * This can be used to optimize a scene.
  107572. *
  107573. * Not that the shadows will NOT disapear but will remain in place.
  107574. * @param process if true shadows will be updated once every frame. if false they will stop being updated.
  107575. */
  107576. set: function (process) {
  107577. var refreshType = process ? babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME : babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  107578. for (var _i = 0, _a = this.scene.lights; _i < _a.length; _i++) {
  107579. var light = _a[_i];
  107580. var generator = light.getShadowGenerator();
  107581. if (generator) {
  107582. var shadowMap = generator.getShadowMap();
  107583. if (shadowMap) {
  107584. shadowMap.refreshRate = refreshType;
  107585. }
  107586. }
  107587. }
  107588. this._processShadows = process;
  107589. },
  107590. enumerable: true,
  107591. configurable: true
  107592. });
  107593. Object.defineProperty(SceneManager.prototype, "groundEnabled", {
  107594. get: function () {
  107595. return this._groundEnabled;
  107596. },
  107597. set: function (newValue) {
  107598. if (newValue === this._groundEnabled)
  107599. return;
  107600. this._groundEnabled = newValue;
  107601. if (this.environmentHelper && this.environmentHelper.ground) {
  107602. this.environmentHelper.ground.setEnabled(this._groundEnabled);
  107603. }
  107604. },
  107605. enumerable: true,
  107606. configurable: true
  107607. });
  107608. Object.defineProperty(SceneManager.prototype, "groundMirrorEnabled", {
  107609. /**
  107610. * gets wether the reflection is disabled.
  107611. */
  107612. get: function () {
  107613. return this._groundMirrorEnabled;
  107614. },
  107615. /**
  107616. * sets wether the reflection is disabled.
  107617. */
  107618. set: function (value) {
  107619. if (this._groundMirrorEnabled === value) {
  107620. return;
  107621. }
  107622. this._groundMirrorEnabled = value;
  107623. if (this.environmentHelper && this.environmentHelper.groundMaterial && this.environmentHelper.groundMirror) {
  107624. if (!value) {
  107625. this.environmentHelper.groundMaterial.reflectionTexture = null;
  107626. }
  107627. else {
  107628. this.environmentHelper.groundMaterial.reflectionTexture = this.environmentHelper.groundMirror;
  107629. }
  107630. }
  107631. },
  107632. enumerable: true,
  107633. configurable: true
  107634. });
  107635. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipelineEnabled", {
  107636. get: function () {
  107637. return this._defaultRenderingPipelineEnabled;
  107638. },
  107639. set: function (value) {
  107640. if (value === this._defaultRenderingPipelineEnabled) {
  107641. return;
  107642. }
  107643. this._defaultRenderingPipelineEnabled = value;
  107644. this._rebuildPostprocesses();
  107645. if (this._defaultRenderingPipeline) {
  107646. this._defaultRenderingPipelineShouldBuild = false;
  107647. this._defaultRenderingPipeline.prepare();
  107648. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  107649. }
  107650. },
  107651. enumerable: true,
  107652. configurable: true
  107653. });
  107654. /**
  107655. * Sets the engine flags to unlock all babylon features.
  107656. * Can also be configured using the scene.flags configuration object
  107657. */
  107658. SceneManager.prototype.unlockBabylonFeatures = function () {
  107659. this.scene.shadowsEnabled = true;
  107660. this.scene.particlesEnabled = true;
  107661. this.scene.postProcessesEnabled = true;
  107662. this.scene.collisionsEnabled = true;
  107663. this.scene.lightsEnabled = true;
  107664. this.scene.texturesEnabled = true;
  107665. this.scene.lensFlaresEnabled = true;
  107666. this.scene.proceduralTexturesEnabled = true;
  107667. this.scene.renderTargetsEnabled = true;
  107668. this.scene.spritesEnabled = true;
  107669. this.scene.skeletonsEnabled = true;
  107670. this.scene.audioEnabled = true;
  107671. };
  107672. /**
  107673. * initialize the scene. Calling this function again will dispose the old scene, if exists.
  107674. */
  107675. SceneManager.prototype.initScene = function (sceneConfiguration, optimizerConfiguration) {
  107676. if (sceneConfiguration === void 0) { sceneConfiguration = {}; }
  107677. // if the scen exists, dispose it.
  107678. if (this.scene) {
  107679. this.scene.dispose();
  107680. }
  107681. // create a new scene
  107682. this.scene = new babylonjs_1.Scene(this._viewer.engine);
  107683. // set a default PBR material
  107684. if (!sceneConfiguration.defaultMaterial) {
  107685. var defaultMaterial = new BABYLON.PBRMaterial('defaultMaterial', this.scene);
  107686. defaultMaterial.reflectivityColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  107687. defaultMaterial.microSurface = 0.6;
  107688. if (this.scene.defaultMaterial) {
  107689. this.scene.defaultMaterial.dispose();
  107690. }
  107691. this.scene.defaultMaterial = defaultMaterial;
  107692. }
  107693. this.scene.animationPropertiesOverride = new babylonjs_1.AnimationPropertiesOverride();
  107694. babylonjs_1.Animation.AllowMatricesInterpolation = true;
  107695. this._mainColor = babylonjs_1.Color3.White();
  107696. /*if (sceneConfiguration.glow) {
  107697. let options: Partial<IGlowLayerOptions> = {
  107698. mainTextureFixedSize: 512
  107699. };
  107700. if (typeof sceneConfiguration.glow === 'object') {
  107701. options = sceneConfiguration.glow
  107702. }
  107703. var gl = new BABYLON.GlowLayer("glow", this.scene, options);
  107704. }*/
  107705. return this.onSceneInitObservable.notifyObserversWithPromise(this.scene);
  107706. };
  107707. SceneManager.prototype.clearScene = function (clearModels, clearLights) {
  107708. if (clearModels === void 0) { clearModels = true; }
  107709. if (clearLights === void 0) { clearLights = false; }
  107710. if (clearModels) {
  107711. this.models.forEach(function (m) { return m.dispose(); });
  107712. this.models.length = 0;
  107713. }
  107714. if (clearLights) {
  107715. this.scene.lights.forEach(function (l) { return l.dispose(); });
  107716. }
  107717. };
  107718. /**
  107719. * This will update the scene's configuration, including camera, lights, environment.
  107720. * @param newConfiguration the delta that should be configured. This includes only the changes
  107721. * @param globalConfiguration The global configuration object, after the new configuration was merged into it
  107722. */
  107723. SceneManager.prototype.updateConfiguration = function (newConfiguration, globalConfiguration) {
  107724. var _this = this;
  107725. if (newConfiguration.lab) {
  107726. if (newConfiguration.lab.assetsRootURL) {
  107727. this.labs.assetsRootURL = newConfiguration.lab.assetsRootURL;
  107728. }
  107729. }
  107730. // update scene configuration
  107731. if (newConfiguration.scene) {
  107732. this._configureScene(newConfiguration.scene);
  107733. }
  107734. // optimizer
  107735. if (newConfiguration.optimizer !== undefined) {
  107736. this._configureOptimizer(newConfiguration.optimizer);
  107737. }
  107738. // configure model
  107739. /*if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  107740. this._configureModel(newConfiguration.model);
  107741. }*/
  107742. // lights
  107743. this._configureLights(newConfiguration.lights);
  107744. // environment
  107745. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  107746. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  107747. }
  107748. // camera
  107749. this._configureCamera(newConfiguration.camera);
  107750. if (newConfiguration.lab) {
  107751. if (newConfiguration.lab.environmentMap) {
  107752. var rot_1 = newConfiguration.lab.environmentMap.rotationY;
  107753. this.labs.loadEnvironment(newConfiguration.lab.environmentMap.texture, function () {
  107754. _this.labs.applyEnvironmentMapConfiguration(rot_1);
  107755. });
  107756. if (!newConfiguration.lab.environmentMap.texture && newConfiguration.lab.environmentMap.rotationY) {
  107757. this.labs.applyEnvironmentMapConfiguration(newConfiguration.lab.environmentMap.rotationY);
  107758. }
  107759. }
  107760. // rendering piplines
  107761. if (newConfiguration.lab.defaultRenderingPipelines) {
  107762. var pipelineConfig = newConfiguration.lab.defaultRenderingPipelines;
  107763. if (typeof pipelineConfig === 'boolean') {
  107764. this.defaultRenderingPipelineEnabled = pipelineConfig;
  107765. }
  107766. else {
  107767. this.defaultRenderingPipelineEnabled = true;
  107768. }
  107769. }
  107770. if (newConfiguration.lab.environmentMainColor) {
  107771. var mainColor = new babylonjs_1.Color3().copyFrom(newConfiguration.lab.environmentMainColor);
  107772. this.environmentHelper.setMainColor(mainColor);
  107773. }
  107774. }
  107775. if (this._defaultRenderingPipeline && this._defaultRenderingPipeline.imageProcessing) {
  107776. this._defaultRenderingPipeline.imageProcessing.fromLinearSpace = true;
  107777. }
  107778. if (this._defaultRenderingPipelineShouldBuild && this._defaultRenderingPipeline) {
  107779. this._defaultRenderingPipelineShouldBuild = false;
  107780. this._defaultRenderingPipeline.prepare();
  107781. }
  107782. };
  107783. SceneManager.prototype._rebuildPostprocesses = function (configuration) {
  107784. if (!this._defaultRenderingPipelineEnabled || !configuration_1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", this._viewer.configuration)) {
  107785. if (this._defaultRenderingPipeline) {
  107786. this._defaultRenderingPipeline.dispose();
  107787. this._defaultRenderingPipeline = null;
  107788. this.scene.autoClearDepthAndStencil = true;
  107789. this.scene.autoClear = true;
  107790. this.scene.imageProcessingConfiguration.applyByPostProcess = false;
  107791. }
  107792. return;
  107793. }
  107794. var pipelineConfig = configuration || (this._viewer.configuration.lab && this._viewer.configuration.lab.defaultRenderingPipelines);
  107795. if (pipelineConfig) {
  107796. if (!this._defaultRenderingPipeline) {
  107797. // Create pipeline in manual mode to avoid triggering multiple shader compilations
  107798. this._defaultRenderingPipeline = new babylonjs_1.DefaultRenderingPipeline("default rendering pipeline", this._hdrSupport, this.scene, [this.camera], false);
  107799. }
  107800. this.scene.autoClear = false;
  107801. this.scene.autoClearDepthAndStencil = false;
  107802. this._defaultRenderingPipelineShouldBuild = true;
  107803. var bloomEnabled = this._bloomEnabled;
  107804. if (typeof pipelineConfig !== 'boolean') {
  107805. helper_1.extendClassWithConfig(this._defaultRenderingPipeline, pipelineConfig);
  107806. this._bloomEnabled = !!pipelineConfig.bloomEnabled;
  107807. this._fxaaEnabled = !!pipelineConfig.fxaaEnabled;
  107808. bloomEnabled = this._bloomEnabled && pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight > 0;
  107809. this._defaultRenderingPipeline.bloomWeight = (pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight) || (this._defaultRenderingPipeline.bloomWeight);
  107810. }
  107811. this._defaultRenderingPipeline.bloomEnabled = bloomEnabled;
  107812. this._defaultRenderingPipeline.fxaaEnabled = this.fxaaEnabled;
  107813. }
  107814. };
  107815. Object.defineProperty(SceneManager.prototype, "bloomEnabled", {
  107816. get: function () {
  107817. return this._bloomEnabled;
  107818. },
  107819. set: function (value) {
  107820. if (this._bloomEnabled === value) {
  107821. return;
  107822. }
  107823. this._bloomEnabled = value;
  107824. this._rebuildPostprocesses();
  107825. if (this._defaultRenderingPipeline) {
  107826. this._defaultRenderingPipelineShouldBuild = false;
  107827. this._defaultRenderingPipeline.prepare();
  107828. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  107829. }
  107830. },
  107831. enumerable: true,
  107832. configurable: true
  107833. });
  107834. Object.defineProperty(SceneManager.prototype, "fxaaEnabled", {
  107835. get: function () {
  107836. return this._fxaaEnabled;
  107837. },
  107838. set: function (value) {
  107839. if (this._fxaaEnabled === value) {
  107840. return;
  107841. }
  107842. this._fxaaEnabled = value;
  107843. this._rebuildPostprocesses();
  107844. if (this._defaultRenderingPipeline) {
  107845. this._defaultRenderingPipelineShouldBuild = false;
  107846. this._defaultRenderingPipeline.prepare();
  107847. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  107848. }
  107849. },
  107850. enumerable: true,
  107851. configurable: true
  107852. });
  107853. /**
  107854. * internally configure the scene using the provided configuration.
  107855. * The scene will not be recreated, but just updated.
  107856. * @param sceneConfig the (new) scene configuration
  107857. */
  107858. SceneManager.prototype._configureScene = function (sceneConfig) {
  107859. // sanity check!
  107860. if (!this.scene) {
  107861. return;
  107862. }
  107863. var cc = sceneConfig.clearColor;
  107864. var oldcc = this.scene.clearColor;
  107865. if (cc) {
  107866. if (cc.r !== undefined) {
  107867. oldcc.r = cc.r;
  107868. }
  107869. if (cc.g !== undefined) {
  107870. oldcc.g = cc.g;
  107871. }
  107872. if (cc.b !== undefined) {
  107873. oldcc.b = cc.b;
  107874. }
  107875. if (cc.a !== undefined) {
  107876. oldcc.a = cc.a;
  107877. }
  107878. }
  107879. // image processing configuration - optional.
  107880. if (sceneConfig.imageProcessingConfiguration) {
  107881. helper_1.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  107882. }
  107883. //animation properties override
  107884. if (sceneConfig.animationPropertiesOverride) {
  107885. helper_1.extendClassWithConfig(this.scene.animationPropertiesOverride, sceneConfig.animationPropertiesOverride);
  107886. }
  107887. if (sceneConfig.environmentTexture) {
  107888. if (!(this.scene.environmentTexture && this.scene.environmentTexture.url === sceneConfig.environmentTexture)) {
  107889. if (this.scene.environmentTexture && this.scene.environmentTexture.dispose) {
  107890. this.scene.environmentTexture.dispose();
  107891. }
  107892. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  107893. this.scene.environmentTexture = environmentTexture;
  107894. }
  107895. }
  107896. if (sceneConfig.debug === true) {
  107897. this.scene.debugLayer.show();
  107898. }
  107899. else if (sceneConfig.debug === false) {
  107900. if (this.scene.debugLayer.isVisible()) {
  107901. this.scene.debugLayer.hide();
  107902. }
  107903. }
  107904. if (sceneConfig.disableHdr) {
  107905. this._handleHardwareLimitations(false);
  107906. }
  107907. else {
  107908. this._handleHardwareLimitations(true);
  107909. }
  107910. if (sceneConfig.renderInBackground !== undefined) {
  107911. this._viewer.renderInBackground = !!sceneConfig.renderInBackground;
  107912. }
  107913. if (this.camera && sceneConfig.disableCameraControl) {
  107914. this.camera.detachControl(this._viewer.canvas);
  107915. }
  107916. else if (this.camera && sceneConfig.disableCameraControl === false) {
  107917. this.camera.attachControl(this._viewer.canvas);
  107918. }
  107919. // process mainColor changes:
  107920. if (sceneConfig.mainColor) {
  107921. this._mainColor = this._mainColor || babylonjs_1.Color3.White();
  107922. var mc = sceneConfig.mainColor;
  107923. if (mc.r !== undefined) {
  107924. this._mainColor.r = mc.r;
  107925. }
  107926. if (mc.g !== undefined) {
  107927. this._mainColor.g = mc.g;
  107928. }
  107929. if (mc.b !== undefined) {
  107930. this._mainColor.b = mc.b;
  107931. }
  107932. this._reflectionColor.copyFrom(this.mainColor);
  107933. var environmentTint = configuration_1.getConfigurationKey("lab.environmentMap.tintLevel", this._viewer.configuration) || 0;
  107934. // reflection color
  107935. this._reflectionColor.toLinearSpaceToRef(this._reflectionColor);
  107936. this._reflectionColor.scaleToRef(1 / this.scene.imageProcessingConfiguration.exposure, this._reflectionColor);
  107937. var tmpColor3 = babylonjs_1.Color3.Lerp(this._white, this._reflectionColor, environmentTint);
  107938. this._reflectionColor.copyFrom(tmpColor3);
  107939. //update the environment, if exists
  107940. if (this.environmentHelper) {
  107941. if (this.environmentHelper.groundMaterial) {
  107942. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  107943. }
  107944. if (this.environmentHelper.skyboxMaterial) {
  107945. this.environmentHelper.skyboxMaterial._perceptualColor = this.mainColor;
  107946. }
  107947. }
  107948. }
  107949. if (sceneConfig.defaultMaterial) {
  107950. var conf = sceneConfig.defaultMaterial;
  107951. if ((conf.materialType === 'standard' && this.scene.defaultMaterial.getClassName() !== 'StandardMaterial') ||
  107952. (conf.materialType === 'pbr' && this.scene.defaultMaterial.getClassName() !== 'PBRMaterial')) {
  107953. this.scene.defaultMaterial.dispose();
  107954. if (conf.materialType === 'standard') {
  107955. this.scene.defaultMaterial = new babylonjs_1.StandardMaterial("defaultMaterial", this.scene);
  107956. }
  107957. else {
  107958. this.scene.defaultMaterial = new babylonjs_1.PBRMaterial("defaultMaterial", this.scene);
  107959. }
  107960. }
  107961. helper_1.extendClassWithConfig(this.scene.defaultMaterial, conf);
  107962. }
  107963. if (sceneConfig.flags) {
  107964. helper_1.extendClassWithConfig(this.scene, sceneConfig.flags);
  107965. }
  107966. this.onSceneConfiguredObservable.notifyObservers({
  107967. sceneManager: this,
  107968. object: this.scene,
  107969. newConfiguration: sceneConfig
  107970. });
  107971. };
  107972. /**
  107973. * Configure the scene optimizer.
  107974. * The existing scene optimizer will be disposed and a new one will be created.
  107975. * @param optimizerConfig the (new) optimizer configuration
  107976. */
  107977. SceneManager.prototype._configureOptimizer = function (optimizerConfig) {
  107978. var _this = this;
  107979. if (typeof optimizerConfig === 'boolean') {
  107980. if (this.sceneOptimizer) {
  107981. this.sceneOptimizer.stop();
  107982. this.sceneOptimizer.dispose();
  107983. delete this.sceneOptimizer;
  107984. }
  107985. if (optimizerConfig) {
  107986. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  107987. this.sceneOptimizer.start();
  107988. }
  107989. }
  107990. else {
  107991. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  107992. // check for degradation
  107993. if (optimizerConfig.degradation) {
  107994. switch (optimizerConfig.degradation) {
  107995. case "low":
  107996. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  107997. break;
  107998. case "moderate":
  107999. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  108000. break;
  108001. case "hight":
  108002. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  108003. break;
  108004. }
  108005. }
  108006. if (this.sceneOptimizer) {
  108007. this.sceneOptimizer.stop();
  108008. this.sceneOptimizer.dispose();
  108009. }
  108010. if (optimizerConfig.custom) {
  108011. var customOptimizer_1 = _1.getCustomOptimizerByName(optimizerConfig.custom, optimizerConfig.improvementMode);
  108012. if (customOptimizer_1) {
  108013. optimizerOptions.addCustomOptimization(function () {
  108014. return customOptimizer_1(_this._viewer);
  108015. }, function () {
  108016. return "Babylon Viewer " + optimizerConfig.custom + " custom optimization";
  108017. });
  108018. }
  108019. }
  108020. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  108021. this.sceneOptimizer.start();
  108022. }
  108023. this.onSceneOptimizerConfiguredObservable.notifyObservers({
  108024. sceneManager: this,
  108025. object: this.sceneOptimizer,
  108026. newConfiguration: optimizerConfig
  108027. });
  108028. };
  108029. /**
  108030. * configure all models using the configuration.
  108031. * @param modelConfiguration the configuration to use to reconfigure the models
  108032. */
  108033. /*protected _configureModel(modelConfiguration: Partial<IModelConfiguration>) {
  108034. this.models.forEach(model => {
  108035. model.updateConfiguration(modelConfiguration);
  108036. });
  108037. this.onModelsConfiguredObservable.notifyObservers({
  108038. sceneManager: this,
  108039. object: this.models,
  108040. newConfiguration: modelConfiguration
  108041. });
  108042. }*/
  108043. /**
  108044. * (Re) configure the camera. The camera will only be created once and from this point will only be reconfigured.
  108045. * @param cameraConfig the new camera configuration
  108046. * @param model optionally use the model to configure the camera.
  108047. */
  108048. SceneManager.prototype._configureCamera = function (cameraConfig) {
  108049. var _this = this;
  108050. if (cameraConfig === void 0) { cameraConfig = {}; }
  108051. if (!this.scene.activeCamera) {
  108052. var attachControl = true;
  108053. if (this._viewer.configuration.scene && this._viewer.configuration.scene.disableCameraControl) {
  108054. attachControl = false;
  108055. }
  108056. this.scene.createDefaultCamera(true, true, attachControl);
  108057. this.camera = this.scene.activeCamera;
  108058. this.camera.setTarget(babylonjs_1.Vector3.Zero());
  108059. }
  108060. if (cameraConfig.position) {
  108061. var newPosition = this.camera.position.clone();
  108062. helper_1.extendClassWithConfig(newPosition, cameraConfig.position);
  108063. this.camera.setPosition(newPosition);
  108064. }
  108065. if (cameraConfig.target) {
  108066. var newTarget = this.camera.target.clone();
  108067. helper_1.extendClassWithConfig(newTarget, cameraConfig.target);
  108068. this.camera.setTarget(newTarget);
  108069. } /*else if (this.models.length && !cameraConfig.disableAutoFocus) {
  108070. this._focusOnModel(this.models[0]);
  108071. }*/
  108072. if (cameraConfig.rotation) {
  108073. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  108074. }
  108075. if (cameraConfig.behaviors) {
  108076. for (var name_1 in cameraConfig.behaviors) {
  108077. if (cameraConfig.behaviors[name_1]) {
  108078. this._setCameraBehavior(cameraConfig.behaviors[name_1]);
  108079. }
  108080. }
  108081. }
  108082. ;
  108083. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  108084. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  108085. });
  108086. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  108087. var sceneDiagonalLenght = sceneDiagonal.length();
  108088. if (isFinite(sceneDiagonalLenght))
  108089. this.camera.upperRadiusLimit = sceneDiagonalLenght * 4;
  108090. else {
  108091. this.camera.upperRadiusLimit = 10;
  108092. }
  108093. // sanity check!
  108094. if (this.scene.imageProcessingConfiguration) {
  108095. this.scene.imageProcessingConfiguration.colorCurvesEnabled = true;
  108096. this.scene.imageProcessingConfiguration.vignetteEnabled = true;
  108097. this.scene.imageProcessingConfiguration.toneMappingEnabled = !!cameraConfig.toneMappingEnabled;
  108098. }
  108099. helper_1.extendClassWithConfig(this.camera, cameraConfig);
  108100. this.onCameraConfiguredObservable.notifyObservers({
  108101. sceneManager: this,
  108102. object: this.camera,
  108103. newConfiguration: cameraConfig
  108104. });
  108105. };
  108106. SceneManager.prototype._configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  108107. var _this = this;
  108108. if (!skyboxConifguration && !groundConfiguration) {
  108109. if (this.environmentHelper) {
  108110. this.environmentHelper.dispose();
  108111. delete this.environmentHelper;
  108112. }
  108113. ;
  108114. }
  108115. else {
  108116. var options = {
  108117. createGround: !!groundConfiguration && this._groundEnabled,
  108118. createSkybox: !!skyboxConifguration,
  108119. setupImageProcessing: false,
  108120. };
  108121. // will that cause problems with model ground configuration?
  108122. /*if (model) {
  108123. const boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  108124. const sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  108125. const halfSizeVec = sizeVec.scale(0.5);
  108126. const center = boundingInfo.min.add(halfSizeVec);
  108127. options.groundYBias = -center.y;
  108128. }*/
  108129. if (groundConfiguration) {
  108130. var groundConfig_1 = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  108131. var groundSize = groundConfig_1.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  108132. if (groundSize) {
  108133. options.groundSize = groundSize;
  108134. }
  108135. options.enableGroundShadow = groundConfig_1 === true || groundConfig_1.receiveShadows;
  108136. if (groundConfig_1.shadowLevel !== undefined) {
  108137. options.groundShadowLevel = groundConfig_1.shadowLevel;
  108138. }
  108139. options.enableGroundMirror = !!groundConfig_1.mirror && this.groundMirrorEnabled;
  108140. if (groundConfig_1.texture) {
  108141. options.groundTexture = this.labs.getAssetUrl(groundConfig_1.texture);
  108142. }
  108143. if (groundConfig_1.color) {
  108144. options.groundColor = new babylonjs_1.Color3(groundConfig_1.color.r, groundConfig_1.color.g, groundConfig_1.color.b);
  108145. }
  108146. if (groundConfig_1.opacity !== undefined) {
  108147. options.groundOpacity = groundConfig_1.opacity;
  108148. }
  108149. if (groundConfig_1.mirror) {
  108150. options.enableGroundMirror = true;
  108151. // to prevent undefines
  108152. if (typeof groundConfig_1.mirror === "object") {
  108153. if (groundConfig_1.mirror.amount !== undefined)
  108154. options.groundMirrorAmount = groundConfig_1.mirror.amount;
  108155. if (groundConfig_1.mirror.sizeRatio !== undefined)
  108156. options.groundMirrorSizeRatio = groundConfig_1.mirror.sizeRatio;
  108157. if (groundConfig_1.mirror.blurKernel !== undefined)
  108158. options.groundMirrorBlurKernel = groundConfig_1.mirror.blurKernel;
  108159. if (groundConfig_1.mirror.fresnelWeight !== undefined)
  108160. options.groundMirrorFresnelWeight = groundConfig_1.mirror.fresnelWeight;
  108161. if (groundConfig_1.mirror.fallOffDistance !== undefined)
  108162. options.groundMirrorFallOffDistance = groundConfig_1.mirror.fallOffDistance;
  108163. if (this._defaultPipelineTextureType !== undefined)
  108164. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  108165. }
  108166. }
  108167. }
  108168. var postInitSkyboxMaterial = false;
  108169. if (skyboxConifguration) {
  108170. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  108171. if (conf.material && conf.material.imageProcessingConfiguration) {
  108172. options.setupImageProcessing = false; // will be configured later manually.
  108173. }
  108174. var skyboxSize = conf.scale;
  108175. if (skyboxSize) {
  108176. options.skyboxSize = skyboxSize;
  108177. }
  108178. options.sizeAuto = !options.skyboxSize;
  108179. if (conf.color) {
  108180. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  108181. }
  108182. if (conf.cubeTexture && conf.cubeTexture.url) {
  108183. if (typeof conf.cubeTexture.url === "string") {
  108184. options.skyboxTexture = this.labs.getAssetUrl(conf.cubeTexture.url);
  108185. }
  108186. else {
  108187. // init later!
  108188. postInitSkyboxMaterial = true;
  108189. }
  108190. }
  108191. if (conf.material) {
  108192. postInitSkyboxMaterial = true;
  108193. }
  108194. }
  108195. options.setupImageProcessing = false; // TMP
  108196. if (!this.environmentHelper) {
  108197. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  108198. }
  108199. else {
  108200. // unlikely, but there might be a new scene! we need to dispose.
  108201. // get the scene used by the envHelper
  108202. var scene = this.environmentHelper.rootMesh.getScene();
  108203. // is it a different scene? Oh no!
  108204. if (scene !== this.scene) {
  108205. this.environmentHelper.dispose();
  108206. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  108207. }
  108208. else {
  108209. this.environmentHelper.updateOptions(options);
  108210. }
  108211. }
  108212. if (this.environmentHelper.rootMesh && this._viewer.configuration.scene && this._viewer.configuration.scene.environmentRotationY !== undefined) {
  108213. this.environmentHelper.rootMesh.rotation.y = this._viewer.configuration.scene.environmentRotationY;
  108214. }
  108215. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  108216. if (this.environmentHelper.groundMaterial && groundConfig) {
  108217. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  108218. if (groundConfig.material) {
  108219. helper_1.extendClassWithConfig(this.environmentHelper.groundMaterial, groundConfig.material);
  108220. }
  108221. if (this.environmentHelper.groundMirror) {
  108222. var mirrorClearColor = this.environmentHelper.groundMaterial._perceptualColor.toLinearSpace();
  108223. // TODO user camera exposure value to set the mirror clear color
  108224. var exposure = Math.pow(2.0, -this.scene.imageProcessingConfiguration.exposure) * Math.PI;
  108225. mirrorClearColor.scaleToRef(1 / exposure, mirrorClearColor);
  108226. this.environmentHelper.groundMirror.clearColor.r = babylonjs_1.Scalar.Clamp(mirrorClearColor.r);
  108227. this.environmentHelper.groundMirror.clearColor.g = babylonjs_1.Scalar.Clamp(mirrorClearColor.g);
  108228. this.environmentHelper.groundMirror.clearColor.b = babylonjs_1.Scalar.Clamp(mirrorClearColor.b);
  108229. this.environmentHelper.groundMirror.clearColor.a = 1;
  108230. if (!this.groundMirrorEnabled) {
  108231. this.environmentHelper.groundMaterial.reflectionTexture = null;
  108232. }
  108233. }
  108234. }
  108235. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  108236. if (skyboxMaterial) {
  108237. skyboxMaterial._perceptualColor = this.mainColor;
  108238. if (postInitSkyboxMaterial) {
  108239. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material) {
  108240. helper_1.extendClassWithConfig(skyboxMaterial, skyboxConifguration.material);
  108241. }
  108242. }
  108243. }
  108244. }
  108245. this._viewer.onModelLoadedObservable.add(function (model) {
  108246. _this._updateGroundMirrorRenderList(model);
  108247. });
  108248. this.onEnvironmentConfiguredObservable.notifyObservers({
  108249. sceneManager: this,
  108250. object: this.environmentHelper,
  108251. newConfiguration: {
  108252. skybox: skyboxConifguration,
  108253. ground: groundConfiguration
  108254. }
  108255. });
  108256. };
  108257. /**
  108258. * configure the lights.
  108259. *
  108260. * @param lightsConfiguration the (new) light(s) configuration
  108261. * @param model optionally use the model to configure the camera.
  108262. */
  108263. SceneManager.prototype._configureLights = function (lightsConfiguration) {
  108264. var _this = this;
  108265. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  108266. // sanity check!
  108267. if (!Object.keys(lightsConfiguration).length) {
  108268. if (!this.scene.lights.length)
  108269. this.scene.createDefaultLight(true);
  108270. }
  108271. else {
  108272. var lightsAvailable_1 = this.scene.lights.map(function (light) { return light.name; });
  108273. // compare to the global (!) configuration object and dispose unneeded:
  108274. var lightsToConfigure_1 = Object.keys(this._viewer.configuration.lights || []);
  108275. if (Object.keys(lightsToConfigure_1).length !== lightsAvailable_1.length) {
  108276. lightsAvailable_1.forEach(function (lName) {
  108277. if (lightsToConfigure_1.indexOf(lName) === -1) {
  108278. _this.scene.getLightByName(lName).dispose();
  108279. }
  108280. });
  108281. }
  108282. Object.keys(lightsConfiguration).forEach(function (name, idx) {
  108283. var lightConfig = { type: 0 };
  108284. if (typeof lightsConfiguration[name] === 'object') {
  108285. lightConfig = lightsConfiguration[name];
  108286. }
  108287. lightConfig.name = name;
  108288. var light;
  108289. // light is not already available
  108290. if (lightsAvailable_1.indexOf(name) === -1) {
  108291. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  108292. if (!constructor)
  108293. return;
  108294. light = constructor();
  108295. }
  108296. else {
  108297. // available? get it from the scene
  108298. light = _this.scene.getLightByName(name);
  108299. lightsAvailable_1 = lightsAvailable_1.filter(function (ln) { return ln !== name; });
  108300. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  108301. light.dispose();
  108302. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  108303. if (!constructor)
  108304. return;
  108305. light = constructor();
  108306. }
  108307. }
  108308. // if config set the light to false, dispose it.
  108309. if (lightsConfiguration[name] === false) {
  108310. light.dispose();
  108311. return;
  108312. }
  108313. //enabled
  108314. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  108315. light.setEnabled(enabled);
  108316. helper_1.extendClassWithConfig(light, lightConfig);
  108317. //position. Some lights don't support shadows
  108318. if (light instanceof babylonjs_1.ShadowLight) {
  108319. // set default values
  108320. light.shadowMinZ = light.shadowMinZ || 0.2;
  108321. light.shadowMaxZ = Math.min(10, light.shadowMaxZ || 10); //large far clips reduce shadow depth precision
  108322. if (lightConfig.target) {
  108323. if (light.setDirectionToTarget) {
  108324. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  108325. light.setDirectionToTarget(target);
  108326. }
  108327. }
  108328. else if (lightConfig.direction) {
  108329. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  108330. light.direction = direction;
  108331. }
  108332. var isShadowEnabled = false;
  108333. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  108334. light.shadowFrustumSize = lightConfig.shadowFrustumSize || 2;
  108335. isShadowEnabled = true;
  108336. }
  108337. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  108338. var spotLight = light;
  108339. if (lightConfig.spotAngle !== undefined) {
  108340. spotLight.angle = lightConfig.spotAngle * Math.PI / 180;
  108341. }
  108342. if (spotLight.angle && lightConfig.shadowFieldOfView) {
  108343. spotLight.shadowAngleScale = lightConfig.shadowFieldOfView / spotLight.angle;
  108344. }
  108345. isShadowEnabled = true;
  108346. }
  108347. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  108348. if (lightConfig.shadowFieldOfView) {
  108349. light.shadowAngle = lightConfig.shadowFieldOfView * Math.PI / 180;
  108350. }
  108351. isShadowEnabled = true;
  108352. }
  108353. var shadowGenerator_1 = light.getShadowGenerator();
  108354. if (isShadowEnabled && lightConfig.shadowEnabled && _this._maxShadows) {
  108355. var bufferSize = lightConfig.shadowBufferSize || 256;
  108356. if (!shadowGenerator_1) {
  108357. shadowGenerator_1 = new babylonjs_1.ShadowGenerator(bufferSize, light);
  108358. }
  108359. var blurKernel = _this.getBlurKernel(light, bufferSize);
  108360. shadowGenerator_1.bias = _this._shadowGeneratorBias;
  108361. shadowGenerator_1.blurKernel = blurKernel;
  108362. //override defaults
  108363. helper_1.extendClassWithConfig(shadowGenerator_1, lightConfig.shadowConfig || {});
  108364. // add the focues meshes to the shadow list
  108365. _this._viewer.onModelLoadedObservable.add(function (model) {
  108366. _this._updateShadowRenderList(shadowGenerator_1, model);
  108367. });
  108368. //if (model) {
  108369. _this._updateShadowRenderList(shadowGenerator_1);
  108370. //}
  108371. }
  108372. else if (shadowGenerator_1) {
  108373. shadowGenerator_1.dispose();
  108374. }
  108375. }
  108376. });
  108377. // render priority
  108378. var globalLightsConfiguration_1 = this._viewer.configuration.lights || {};
  108379. Object.keys(globalLightsConfiguration_1).sort().forEach(function (name, idx) {
  108380. var configuration = globalLightsConfiguration_1[name];
  108381. var light = _this.scene.getLightByName(name);
  108382. // sanity check
  108383. if (!light)
  108384. return;
  108385. light.renderPriority = -idx;
  108386. });
  108387. }
  108388. this.onLightsConfiguredObservable.notifyObservers({
  108389. sceneManager: this,
  108390. object: this.scene.lights,
  108391. newConfiguration: lightsConfiguration
  108392. });
  108393. };
  108394. SceneManager.prototype._updateShadowRenderList = function (shadowGenerator, model, resetList) {
  108395. var focusMeshes = model ? model.meshes : this.scene.meshes;
  108396. // add the focues meshes to the shadow list
  108397. var shadownMap = shadowGenerator.getShadowMap();
  108398. if (!shadownMap)
  108399. return;
  108400. if (resetList && shadownMap.renderList) {
  108401. shadownMap.renderList.length = 0;
  108402. }
  108403. else {
  108404. shadownMap.renderList = shadownMap.renderList || [];
  108405. }
  108406. for (var index = 0; index < focusMeshes.length; index++) {
  108407. var mesh = focusMeshes[index];
  108408. if (babylonjs_1.Tags.MatchesQuery(mesh, 'castShadow') && shadownMap.renderList.indexOf(mesh) === -1) {
  108409. shadownMap.renderList.push(mesh);
  108410. }
  108411. }
  108412. if (!this._shadowGroundPlane) {
  108413. if (shadowGenerator.useBlurCloseExponentialShadowMap) {
  108414. var shadowGroundPlane = babylonjs_1.Mesh.CreatePlane("shadowGroundPlane", 100, this.scene, false);
  108415. shadowGroundPlane.useVertexColors = false;
  108416. //material isn't ever used in rendering, just used to set back face culling
  108417. shadowGroundPlane.material = new babylonjs_1.StandardMaterial('shadowGroundPlaneMaterial', this.scene);
  108418. shadowGroundPlane.material.backFaceCulling = false;
  108419. shadowGroundPlane.rotation.x = Math.PI * 0.5;
  108420. shadowGroundPlane.freezeWorldMatrix();
  108421. this._shadowGroundPlane = shadowGroundPlane;
  108422. this.scene.removeMesh(shadowGroundPlane);
  108423. }
  108424. }
  108425. else {
  108426. if (!shadowGenerator.useBlurCloseExponentialShadowMap) {
  108427. this._shadowGroundPlane.dispose();
  108428. this._shadowGroundPlane = null;
  108429. }
  108430. }
  108431. if (this._shadowGroundPlane && shadownMap.renderList.indexOf(this._shadowGroundPlane) === -1) {
  108432. shadownMap.renderList.push(this._shadowGroundPlane);
  108433. }
  108434. };
  108435. SceneManager.prototype._updateGroundMirrorRenderList = function (model, resetList) {
  108436. if (this.environmentHelper.groundMirror && this.environmentHelper.groundMirror.renderList) {
  108437. var focusMeshes = model ? model.meshes : this.scene.meshes;
  108438. var renderList = this.environmentHelper.groundMirror.renderList;
  108439. if (resetList) {
  108440. renderList.length = 0;
  108441. }
  108442. for (var index = 0; index < focusMeshes.length; index++) {
  108443. var mesh = focusMeshes[index];
  108444. if (renderList.indexOf(mesh) === -1) {
  108445. renderList.push(mesh);
  108446. }
  108447. }
  108448. }
  108449. };
  108450. /**
  108451. * Gets the shadow map blur kernel according to the light configuration.
  108452. * @param light The light used to generate the shadows
  108453. * @param bufferSize The size of the shadow map
  108454. * @return the kernel blur size
  108455. */
  108456. SceneManager.prototype.getBlurKernel = function (light, bufferSize) {
  108457. var normalizedBlurKernel = 0.05; // TODO Should come from the config.
  108458. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  108459. normalizedBlurKernel = normalizedBlurKernel / light.shadowFrustumSize;
  108460. }
  108461. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  108462. normalizedBlurKernel = normalizedBlurKernel / light.shadowAngle;
  108463. }
  108464. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  108465. normalizedBlurKernel = normalizedBlurKernel / (light.angle * light.shadowAngleScale);
  108466. }
  108467. var minimumBlurKernel = 5 / (bufferSize / 256); //magic number that aims to keep away sawtooth shadows
  108468. var blurKernel = Math.max(bufferSize * normalizedBlurKernel, minimumBlurKernel);
  108469. return blurKernel;
  108470. };
  108471. /**
  108472. * Alters render settings to reduce features based on hardware feature limitations
  108473. * @param enableHDR Allows the viewer to run in HDR mode.
  108474. */
  108475. SceneManager.prototype._handleHardwareLimitations = function (enableHDR) {
  108476. if (enableHDR === void 0) { enableHDR = true; }
  108477. //flip rendering settings switches based on hardware support
  108478. var maxVaryingRows = this._viewer.engine.getCaps().maxVaryingVectors;
  108479. var maxFragmentSamplers = this._viewer.engine.getCaps().maxTexturesImageUnits;
  108480. //shadows are disabled if there's not enough varyings for a single shadow
  108481. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  108482. this._maxShadows = 0;
  108483. }
  108484. else {
  108485. this._maxShadows = 3;
  108486. }
  108487. //can we render to any >= 16-bit targets (required for HDR)
  108488. var caps = this._viewer.engine.getCaps();
  108489. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  108490. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  108491. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  108492. if (linearHalfFloatTargets) {
  108493. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  108494. this._shadowGeneratorBias = 0.002;
  108495. }
  108496. else if (linearFloatTargets) {
  108497. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  108498. this._shadowGeneratorBias = 0.001;
  108499. }
  108500. else {
  108501. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  108502. this._shadowGeneratorBias = 0.001;
  108503. }
  108504. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  108505. };
  108506. /**
  108507. * Dispoe the entire viewer including the scene and the engine
  108508. */
  108509. SceneManager.prototype.dispose = function () {
  108510. // this.onCameraConfiguredObservable.clear();
  108511. this.onEnvironmentConfiguredObservable.clear();
  108512. this.onLightsConfiguredObservable.clear();
  108513. this.onModelsConfiguredObservable.clear();
  108514. this.onSceneConfiguredObservable.clear();
  108515. this.onSceneInitObservable.clear();
  108516. this.onSceneOptimizerConfiguredObservable.clear();
  108517. if (this.sceneOptimizer) {
  108518. this.sceneOptimizer.stop();
  108519. this.sceneOptimizer.dispose();
  108520. }
  108521. if (this.environmentHelper) {
  108522. this.environmentHelper.dispose();
  108523. }
  108524. this.models.forEach(function (model) {
  108525. model.dispose();
  108526. });
  108527. if (this._defaultRenderingPipeline) {
  108528. this._defaultRenderingPipeline.dispose();
  108529. }
  108530. this.models.length = 0;
  108531. if (this.scene) {
  108532. this.scene.dispose();
  108533. }
  108534. };
  108535. SceneManager.prototype._setCameraBehavior = function (behaviorConfig, payload) {
  108536. var behavior;
  108537. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  108538. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  108539. // constructing behavior
  108540. switch (type) {
  108541. case 0 /* AUTOROTATION */:
  108542. this.camera.useAutoRotationBehavior = true;
  108543. behavior = this.camera.autoRotationBehavior;
  108544. break;
  108545. case 1 /* BOUNCING */:
  108546. this.camera.useBouncingBehavior = true;
  108547. behavior = this.camera.bouncingBehavior;
  108548. break;
  108549. case 2 /* FRAMING */:
  108550. this.camera.useFramingBehavior = true;
  108551. behavior = this.camera.framingBehavior;
  108552. break;
  108553. default:
  108554. behavior = null;
  108555. break;
  108556. }
  108557. if (behavior) {
  108558. if (typeof behaviorConfig === "object") {
  108559. helper_1.extendClassWithConfig(behavior, behaviorConfig);
  108560. }
  108561. }
  108562. // post attach configuration. Some functionalities require the attached camera.
  108563. switch (type) {
  108564. case 0 /* AUTOROTATION */:
  108565. break;
  108566. case 1 /* BOUNCING */:
  108567. break;
  108568. case 2 /* FRAMING */:
  108569. this._viewer.onModelLoadedObservable.add(function (model) {
  108570. if (config.zoomOnBoundingInfo) {
  108571. behavior.zoomOnMeshHierarchy(model.rootMesh);
  108572. }
  108573. });
  108574. break;
  108575. }
  108576. };
  108577. return SceneManager;
  108578. }());
  108579. exports.SceneManager = SceneManager;
  108580. /***/ }),
  108581. /* 30 */
  108582. /***/ (function(module, exports, __webpack_require__) {
  108583. "use strict";
  108584. Object.defineProperty(exports, "__esModule", { value: true });
  108585. /**
  108586. * Animation play mode enum - is the animation looping or playing once
  108587. */
  108588. var AnimationPlayMode;
  108589. (function (AnimationPlayMode) {
  108590. AnimationPlayMode[AnimationPlayMode["ONCE"] = 0] = "ONCE";
  108591. AnimationPlayMode[AnimationPlayMode["LOOP"] = 1] = "LOOP";
  108592. })(AnimationPlayMode = exports.AnimationPlayMode || (exports.AnimationPlayMode = {}));
  108593. /**
  108594. * An enum representing the current state of an animation object
  108595. */
  108596. var AnimationState;
  108597. (function (AnimationState) {
  108598. AnimationState[AnimationState["INIT"] = 0] = "INIT";
  108599. AnimationState[AnimationState["PLAYING"] = 1] = "PLAYING";
  108600. AnimationState[AnimationState["PAUSED"] = 2] = "PAUSED";
  108601. AnimationState[AnimationState["STOPPED"] = 3] = "STOPPED";
  108602. AnimationState[AnimationState["ENDED"] = 4] = "ENDED";
  108603. })(AnimationState = exports.AnimationState || (exports.AnimationState = {}));
  108604. /**
  108605. * The different type of easing functions available
  108606. */
  108607. var EasingFunction;
  108608. (function (EasingFunction) {
  108609. EasingFunction[EasingFunction["Linear"] = 0] = "Linear";
  108610. EasingFunction[EasingFunction["CircleEase"] = 1] = "CircleEase";
  108611. EasingFunction[EasingFunction["BackEase"] = 2] = "BackEase";
  108612. EasingFunction[EasingFunction["BounceEase"] = 3] = "BounceEase";
  108613. EasingFunction[EasingFunction["CubicEase"] = 4] = "CubicEase";
  108614. EasingFunction[EasingFunction["ElasticEase"] = 5] = "ElasticEase";
  108615. EasingFunction[EasingFunction["ExponentialEase"] = 6] = "ExponentialEase";
  108616. EasingFunction[EasingFunction["PowerEase"] = 7] = "PowerEase";
  108617. EasingFunction[EasingFunction["QuadraticEase"] = 8] = "QuadraticEase";
  108618. EasingFunction[EasingFunction["QuarticEase"] = 9] = "QuarticEase";
  108619. EasingFunction[EasingFunction["QuinticEase"] = 10] = "QuinticEase";
  108620. EasingFunction[EasingFunction["SineEase"] = 11] = "SineEase";
  108621. })(EasingFunction = exports.EasingFunction || (exports.EasingFunction = {}));
  108622. /**
  108623. * The GroupModelAnimation is an implementation of the IModelAnimation interface using BABYLON's
  108624. * native GroupAnimation class.
  108625. */
  108626. var GroupModelAnimation = /** @class */ (function () {
  108627. /**
  108628. * Create a new GroupModelAnimation object using an AnimationGroup object
  108629. * @param _animationGroup The aniamtion group to base the class on
  108630. */
  108631. function GroupModelAnimation(_animationGroup) {
  108632. var _this = this;
  108633. this._animationGroup = _animationGroup;
  108634. this._state = 0 /* INIT */;
  108635. this._playMode = 1 /* LOOP */;
  108636. this._animationGroup.onAnimationEndObservable.add(function () {
  108637. _this.stop();
  108638. _this._state = 4 /* ENDED */;
  108639. });
  108640. }
  108641. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  108642. /**
  108643. * Get the animation's name
  108644. */
  108645. get: function () {
  108646. return this._animationGroup.name;
  108647. },
  108648. enumerable: true,
  108649. configurable: true
  108650. });
  108651. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  108652. /**
  108653. * Get the current animation's state
  108654. */
  108655. get: function () {
  108656. return this._state;
  108657. },
  108658. enumerable: true,
  108659. configurable: true
  108660. });
  108661. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  108662. /**
  108663. * Gets the speed ratio to use for all animations
  108664. */
  108665. get: function () {
  108666. return this._animationGroup.speedRatio;
  108667. },
  108668. /**
  108669. * Sets the speed ratio to use for all animations
  108670. */
  108671. set: function (value) {
  108672. this._animationGroup.speedRatio = value;
  108673. },
  108674. enumerable: true,
  108675. configurable: true
  108676. });
  108677. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  108678. /**
  108679. * Get the max numbers of frame available in the animation group
  108680. *
  108681. * In correlation to an arry, this would be ".length"
  108682. */
  108683. get: function () {
  108684. return this._animationGroup.to - this._animationGroup.from;
  108685. },
  108686. enumerable: true,
  108687. configurable: true
  108688. });
  108689. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  108690. /**
  108691. * Get the current frame playing right now.
  108692. * This can be used to poll the frame currently playing (and, for exmaple, display a progress bar with the data)
  108693. *
  108694. * In correlation to an array, this would be the current index
  108695. */
  108696. get: function () {
  108697. if (this._animationGroup.targetedAnimations[0] && this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0]) {
  108698. return this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0].currentFrame - this._animationGroup.from;
  108699. }
  108700. else {
  108701. return 0;
  108702. }
  108703. },
  108704. enumerable: true,
  108705. configurable: true
  108706. });
  108707. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  108708. /**
  108709. * Get the FPS value of this animation
  108710. */
  108711. get: function () {
  108712. // get the first currentFrame found
  108713. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  108714. var animatable = this._animationGroup.animatables[i];
  108715. var animations = animatable.getAnimations();
  108716. if (!animations || !animations.length) {
  108717. continue;
  108718. }
  108719. for (var idx = 0; idx < animations.length; ++idx) {
  108720. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  108721. return animations[idx].animation.framePerSecond;
  108722. }
  108723. }
  108724. }
  108725. return 0;
  108726. },
  108727. enumerable: true,
  108728. configurable: true
  108729. });
  108730. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  108731. /**
  108732. * What is the animation'S play mode (looping or played once)
  108733. */
  108734. get: function () {
  108735. return this._playMode;
  108736. },
  108737. /**
  108738. * Set the play mode.
  108739. * If the animation is played, it will continue playing at least once more, depending on the new play mode set.
  108740. * If the animation is not set, the will be initialized and will wait for the user to start playing it.
  108741. */
  108742. set: function (value) {
  108743. if (value === this._playMode) {
  108744. return;
  108745. }
  108746. this._playMode = value;
  108747. if (this.state === 1 /* PLAYING */) {
  108748. this._animationGroup.play(this._playMode === 1 /* LOOP */);
  108749. }
  108750. else {
  108751. this._animationGroup.reset();
  108752. this._state = 0 /* INIT */;
  108753. }
  108754. },
  108755. enumerable: true,
  108756. configurable: true
  108757. });
  108758. /**
  108759. * Reset the animation group
  108760. */
  108761. GroupModelAnimation.prototype.reset = function () {
  108762. this._animationGroup.reset();
  108763. };
  108764. /**
  108765. * Restart the animation group
  108766. */
  108767. GroupModelAnimation.prototype.restart = function () {
  108768. if (this.state === 2 /* PAUSED */)
  108769. this._animationGroup.restart();
  108770. else
  108771. this.start();
  108772. };
  108773. /**
  108774. *
  108775. * @param frameNumber Go to a specific frame in the animation
  108776. */
  108777. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  108778. this._animationGroup.goToFrame(frameNumber + this._animationGroup.from);
  108779. };
  108780. /**
  108781. * Start playing the animation.
  108782. */
  108783. GroupModelAnimation.prototype.start = function () {
  108784. this._animationGroup.start(this.playMode === 1 /* LOOP */, this.speedRatio);
  108785. if (this._animationGroup.isStarted) {
  108786. this._state = 1 /* PLAYING */;
  108787. }
  108788. };
  108789. /**
  108790. * Pause the animation
  108791. */
  108792. GroupModelAnimation.prototype.pause = function () {
  108793. this._animationGroup.pause();
  108794. this._state = 2 /* PAUSED */;
  108795. };
  108796. /**
  108797. * Stop the animation.
  108798. * This will fail silently if the animation group is already stopped.
  108799. */
  108800. GroupModelAnimation.prototype.stop = function () {
  108801. this._animationGroup.stop();
  108802. if (!this._animationGroup.isStarted) {
  108803. this._state = 3 /* STOPPED */;
  108804. }
  108805. };
  108806. /**
  108807. * Dispose this animation object.
  108808. */
  108809. GroupModelAnimation.prototype.dispose = function () {
  108810. this._animationGroup.dispose();
  108811. };
  108812. return GroupModelAnimation;
  108813. }());
  108814. exports.GroupModelAnimation = GroupModelAnimation;
  108815. /***/ }),
  108816. /* 31 */
  108817. /***/ (function(module, exports, __webpack_require__) {
  108818. "use strict";
  108819. Object.defineProperty(exports, "__esModule", { value: true });
  108820. var environmentSerializer_1 = __webpack_require__(32);
  108821. var babylonjs_1 = __webpack_require__(0);
  108822. var texture_1 = __webpack_require__(12);
  108823. /**
  108824. * The ViewerLabs class will hold functions that are not (!) backwards compatible.
  108825. * The APIs in all labs-related classes and configuration might change.
  108826. * Once stable, lab features will be moved to the publis API and configuration object.
  108827. */
  108828. var ViewerLabs = /** @class */ (function () {
  108829. function ViewerLabs(_sceneManager) {
  108830. this._sceneManager = _sceneManager;
  108831. this.environment = {
  108832. //irradiance
  108833. irradiancePolynomialCoefficients: {
  108834. x: new BABYLON.Vector3(0, 0, 0),
  108835. y: new BABYLON.Vector3(0, 0, 0),
  108836. z: new BABYLON.Vector3(0, 0, 0),
  108837. xx: new BABYLON.Vector3(0, 0, 0),
  108838. yy: new BABYLON.Vector3(0, 0, 0),
  108839. zz: new BABYLON.Vector3(0, 0, 0),
  108840. yz: new BABYLON.Vector3(0, 0, 0),
  108841. zx: new BABYLON.Vector3(0, 0, 0),
  108842. xy: new BABYLON.Vector3(0, 0, 0)
  108843. },
  108844. textureIntensityScale: 1.0
  108845. };
  108846. }
  108847. ViewerLabs.prototype.loadEnvironment = function (data, onSuccess, onProgress, onError) {
  108848. var _this = this;
  108849. //@! todo: should loadEnvironment cancel any currently loading environments?
  108850. if (data instanceof ArrayBuffer) {
  108851. this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(data);
  108852. if (onSuccess)
  108853. onSuccess(this.environment);
  108854. }
  108855. else if (typeof data === 'string') {
  108856. var url = this.getAssetUrl(data);
  108857. this._sceneManager.scene._loadFile(url, function (arrayBuffer) {
  108858. _this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(arrayBuffer);
  108859. if (onSuccess)
  108860. onSuccess(_this.environment);
  108861. }, function (progressEvent) { if (onProgress)
  108862. onProgress(progressEvent.loaded, progressEvent.total); }, false, true, function (r, e) {
  108863. if (onError) {
  108864. onError(e);
  108865. }
  108866. });
  108867. }
  108868. else {
  108869. //data assumed to be PBREnvironment object
  108870. this.environment = data;
  108871. if (onSuccess)
  108872. onSuccess(data);
  108873. }
  108874. };
  108875. /**
  108876. * Applies an `EnvironmentMapConfiguration` to the scene
  108877. * @param environmentMapConfiguration Environment map configuration to apply
  108878. */
  108879. ViewerLabs.prototype.applyEnvironmentMapConfiguration = function (rotationY) {
  108880. if (!this.environment)
  108881. return;
  108882. //set orientation
  108883. var rotatquatRotationionY = babylonjs_1.Quaternion.RotationAxis(BABYLON.Axis.Y, rotationY || 0);
  108884. // Add env texture to the scene.
  108885. if (this.environment.specularTexture) {
  108886. // IE crashes when disposing the old texture and setting a new one
  108887. if (!this._sceneManager.scene.environmentTexture) {
  108888. this._sceneManager.scene.environmentTexture = texture_1.TextureUtils.GetBabylonCubeTexture(this._sceneManager.scene, this.environment.specularTexture, false, true);
  108889. }
  108890. if (this._sceneManager.scene.environmentTexture) {
  108891. this._sceneManager.scene.environmentTexture.level = this.environment.textureIntensityScale;
  108892. this._sceneManager.scene.environmentTexture.invertZ = true;
  108893. this._sceneManager.scene.environmentTexture.lodLevelInAlpha = true;
  108894. var poly = this._sceneManager.scene.environmentTexture.sphericalPolynomial || new BABYLON.SphericalPolynomial();
  108895. poly.x = this.environment.irradiancePolynomialCoefficients.x;
  108896. poly.y = this.environment.irradiancePolynomialCoefficients.y;
  108897. poly.z = this.environment.irradiancePolynomialCoefficients.z;
  108898. poly.xx = this.environment.irradiancePolynomialCoefficients.xx;
  108899. poly.xy = this.environment.irradiancePolynomialCoefficients.xy;
  108900. poly.yy = this.environment.irradiancePolynomialCoefficients.yy;
  108901. poly.yz = this.environment.irradiancePolynomialCoefficients.yz;
  108902. poly.zx = this.environment.irradiancePolynomialCoefficients.zx;
  108903. poly.zz = this.environment.irradiancePolynomialCoefficients.zz;
  108904. this._sceneManager.scene.environmentTexture.sphericalPolynomial = poly;
  108905. //set orientation
  108906. BABYLON.Matrix.FromQuaternionToRef(rotatquatRotationionY, this._sceneManager.scene.environmentTexture.getReflectionTextureMatrix());
  108907. }
  108908. }
  108909. };
  108910. /**
  108911. * Get an environment asset url by using the configuration if the path is not absolute.
  108912. * @param url Asset url
  108913. * @returns The Asset url using the `environmentAssetsRootURL` if the url is not an absolute path.
  108914. */
  108915. ViewerLabs.prototype.getAssetUrl = function (url) {
  108916. var returnUrl = url;
  108917. if (url && url.toLowerCase().indexOf("//") === -1) {
  108918. if (!this.assetsRootURL) {
  108919. // Tools.Warn("Please, specify the root url of your assets before loading the configuration (labs.environmentAssetsRootURL) or disable the background through the viewer options.");
  108920. return url;
  108921. }
  108922. returnUrl = this.assetsRootURL + returnUrl;
  108923. }
  108924. return returnUrl;
  108925. };
  108926. return ViewerLabs;
  108927. }());
  108928. exports.ViewerLabs = ViewerLabs;
  108929. /***/ }),
  108930. /* 32 */
  108931. /***/ (function(module, exports, __webpack_require__) {
  108932. "use strict";
  108933. Object.defineProperty(exports, "__esModule", { value: true });
  108934. var babylonjs_1 = __webpack_require__(0);
  108935. var texture_1 = __webpack_require__(12);
  108936. /**
  108937. * A static class proving methods to aid parsing Spectre environment files
  108938. */
  108939. var EnvironmentDeserializer = /** @class */ (function () {
  108940. function EnvironmentDeserializer() {
  108941. }
  108942. /**
  108943. * Parses an arraybuffer into a new PBREnvironment object
  108944. * @param arrayBuffer The arraybuffer of the Spectre environment file
  108945. * @return a PBREnvironment object
  108946. */
  108947. EnvironmentDeserializer.Parse = function (arrayBuffer) {
  108948. var environment = {
  108949. //irradiance
  108950. irradiancePolynomialCoefficients: {
  108951. x: new babylonjs_1.Vector3(0, 0, 0),
  108952. y: new babylonjs_1.Vector3(0, 0, 0),
  108953. z: new babylonjs_1.Vector3(0, 0, 0),
  108954. xx: new babylonjs_1.Vector3(0, 0, 0),
  108955. yy: new babylonjs_1.Vector3(0, 0, 0),
  108956. zz: new babylonjs_1.Vector3(0, 0, 0),
  108957. yz: new babylonjs_1.Vector3(0, 0, 0),
  108958. zx: new babylonjs_1.Vector3(0, 0, 0),
  108959. xy: new babylonjs_1.Vector3(0, 0, 0)
  108960. },
  108961. //specular
  108962. textureIntensityScale: 1.0,
  108963. };
  108964. //read .env
  108965. var littleEndian = false;
  108966. var magicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  108967. var dataView = new DataView(arrayBuffer);
  108968. var pos = 0;
  108969. for (var i = 0; i < magicBytes.length; i++) {
  108970. if (dataView.getUint8(pos++) !== magicBytes[i]) {
  108971. babylonjs_1.Tools.Error('Not a Spectre environment map');
  108972. }
  108973. }
  108974. var version = dataView.getUint16(pos, littleEndian);
  108975. pos += 2;
  108976. if (version !== 1) {
  108977. babylonjs_1.Tools.Warn('Unsupported Spectre environment map version "' + version + '"');
  108978. }
  108979. //read json descriptor - collect characters up to null terminator
  108980. var descriptorString = '';
  108981. var charCode = 0x00;
  108982. while ((charCode = dataView.getUint8(pos++))) {
  108983. descriptorString += String.fromCharCode(charCode);
  108984. }
  108985. var descriptor = JSON.parse(descriptorString);
  108986. var payloadPos = pos;
  108987. //irradiance
  108988. switch (descriptor.irradiance.type) {
  108989. case 'irradiance_sh_coefficients_9':
  108990. //irradiance
  108991. var harmonics = descriptor.irradiance;
  108992. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance(harmonics);
  108993. //harmonics now represent radiance
  108994. EnvironmentDeserializer._ConvertSHToSP(harmonics, environment.irradiancePolynomialCoefficients);
  108995. break;
  108996. default:
  108997. babylonjs_1.Tools.Error('Unhandled MapType descriptor.irradiance.type (' + descriptor.irradiance.type + ')');
  108998. }
  108999. //specular
  109000. switch (descriptor.specular.type) {
  109001. case 'cubemap_faces':
  109002. var specularDescriptor = descriptor.specular;
  109003. var specularTexture = environment.specularTexture = new texture_1.TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */);
  109004. environment.textureIntensityScale = specularDescriptor.multiplier != null ? specularDescriptor.multiplier : 1.0;
  109005. var mipmaps = specularDescriptor.mipmaps;
  109006. var imageType = specularDescriptor.imageType;
  109007. for (var l = 0; l < mipmaps.length; l++) {
  109008. var faceRanges = mipmaps[l];
  109009. specularTexture.source[l] = [];
  109010. for (var i = 0; i < 6; i++) {
  109011. var range = faceRanges[i];
  109012. var bytes = new Uint8Array(arrayBuffer, payloadPos + range.pos, range.length);
  109013. switch (imageType) {
  109014. case 'png':
  109015. //construct image element from bytes
  109016. var image = new Image();
  109017. var src = URL.createObjectURL(new Blob([bytes], { type: 'image/png' }));
  109018. image.src = src;
  109019. specularTexture.source[l][i] = image;
  109020. break;
  109021. default:
  109022. babylonjs_1.Tools.Error('Unhandled ImageType descriptor.specular.imageType (' + imageType + ')');
  109023. }
  109024. }
  109025. }
  109026. break;
  109027. default:
  109028. babylonjs_1.Tools.Error('Unhandled MapType descriptor.specular.type (' + descriptor.specular.type + ')');
  109029. }
  109030. return environment;
  109031. };
  109032. /**
  109033. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  109034. * L = (1/pi) * E * rho
  109035. *
  109036. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  109037. * @param harmonics Spherical harmonic coefficients (9)
  109038. */
  109039. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  109040. EnvironmentDeserializer._ScaleSH(harmonics, 1 / Math.PI);
  109041. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  109042. // (The pixel shader must apply albedo after texture fetches, etc).
  109043. };
  109044. /**
  109045. * Convert spherical harmonics to spherical polynomial coefficients
  109046. * @param harmonics Spherical harmonic coefficients (9)
  109047. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  109048. */
  109049. EnvironmentDeserializer._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  109050. var rPi = 1 / Math.PI;
  109051. //x
  109052. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  109053. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  109054. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  109055. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  109056. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  109057. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  109058. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  109059. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  109060. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  109061. //xx
  109062. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  109063. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  109064. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  109065. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  109066. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  109067. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  109068. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  109069. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  109070. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  109071. //yz
  109072. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  109073. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  109074. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  109075. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  109076. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  109077. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  109078. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  109079. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  109080. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  109081. };
  109082. /**
  109083. * Multiplies harmonic coefficients in place
  109084. * @param harmonics Spherical harmonic coefficients (9)
  109085. * @param scaleFactor Value to multiply by
  109086. */
  109087. EnvironmentDeserializer._ScaleSH = function (harmonics, scaleFactor) {
  109088. harmonics.l00[0] *= scaleFactor;
  109089. harmonics.l00[1] *= scaleFactor;
  109090. harmonics.l00[2] *= scaleFactor;
  109091. harmonics.l1_1[0] *= scaleFactor;
  109092. harmonics.l1_1[1] *= scaleFactor;
  109093. harmonics.l1_1[2] *= scaleFactor;
  109094. harmonics.l10[0] *= scaleFactor;
  109095. harmonics.l10[1] *= scaleFactor;
  109096. harmonics.l10[2] *= scaleFactor;
  109097. harmonics.l11[0] *= scaleFactor;
  109098. harmonics.l11[1] *= scaleFactor;
  109099. harmonics.l11[2] *= scaleFactor;
  109100. harmonics.l2_2[0] *= scaleFactor;
  109101. harmonics.l2_2[1] *= scaleFactor;
  109102. harmonics.l2_2[2] *= scaleFactor;
  109103. harmonics.l2_1[0] *= scaleFactor;
  109104. harmonics.l2_1[1] *= scaleFactor;
  109105. harmonics.l2_1[2] *= scaleFactor;
  109106. harmonics.l20[0] *= scaleFactor;
  109107. harmonics.l20[1] *= scaleFactor;
  109108. harmonics.l20[2] *= scaleFactor;
  109109. harmonics.l21[0] *= scaleFactor;
  109110. harmonics.l21[1] *= scaleFactor;
  109111. harmonics.l21[2] *= scaleFactor;
  109112. harmonics.l22[0] *= scaleFactor;
  109113. harmonics.l22[1] *= scaleFactor;
  109114. harmonics.l22[2] *= scaleFactor;
  109115. };
  109116. return EnvironmentDeserializer;
  109117. }());
  109118. exports.EnvironmentDeserializer = EnvironmentDeserializer;
  109119. /***/ }),
  109120. /* 33 */
  109121. /***/ (function(module, exports, __webpack_require__) {
  109122. "use strict";
  109123. Object.defineProperty(exports, "__esModule", { value: true });
  109124. var extended_1 = __webpack_require__(34);
  109125. var cache = {};
  109126. /**
  109127. *
  109128. * @param name the name of the custom optimizer configuration
  109129. * @param upgrade set to true if you want to upgrade optimizer and false if you want to degrade
  109130. */
  109131. function getCustomOptimizerByName(name, upgrade) {
  109132. if (!cache[name]) {
  109133. switch (name) {
  109134. case 'extended':
  109135. if (upgrade) {
  109136. return extended_1.extendedUpgrade;
  109137. }
  109138. else {
  109139. return extended_1.extendedDegrade;
  109140. }
  109141. }
  109142. }
  109143. return cache[name];
  109144. }
  109145. exports.getCustomOptimizerByName = getCustomOptimizerByName;
  109146. /***/ }),
  109147. /* 34 */
  109148. /***/ (function(module, exports, __webpack_require__) {
  109149. "use strict";
  109150. Object.defineProperty(exports, "__esModule", { value: true });
  109151. var babylonjs_1 = __webpack_require__(0);
  109152. /**
  109153. * A custom upgrade-oriented function configuration for the scene optimizer.
  109154. *
  109155. * @param viewer the viewer to optimize
  109156. */
  109157. function extendedUpgrade(viewer) {
  109158. var defaultPipeline = viewer.sceneManager.defaultRenderingPipeline;
  109159. // if (!this.Scene.BackgroundHelper) {
  109160. // this.Scene.EngineScene.autoClear = false;
  109161. // this.Scene.BackgroundHelper = true;
  109162. // Would require a dedicated clear color;
  109163. // return false;
  109164. // }
  109165. if (viewer.engine.getHardwareScalingLevel() > 1) {
  109166. var scaling = babylonjs_1.Scalar.Clamp(viewer.engine.getHardwareScalingLevel() - 0.25, 0, 1);
  109167. viewer.engine.setHardwareScalingLevel(scaling);
  109168. return false;
  109169. }
  109170. if (!viewer.sceneManager.scene.postProcessesEnabled) {
  109171. viewer.sceneManager.scene.postProcessesEnabled = true;
  109172. return false;
  109173. }
  109174. if (!viewer.sceneManager.groundEnabled) {
  109175. viewer.sceneManager.groundEnabled = true;
  109176. return false;
  109177. }
  109178. if (defaultPipeline && !viewer.sceneManager.fxaaEnabled) {
  109179. viewer.sceneManager.fxaaEnabled = true;
  109180. return false;
  109181. }
  109182. var hardwareScalingLevel = Math.max(1 / 2, 1 / (window.devicePixelRatio || 2));
  109183. if (viewer.engine.getHardwareScalingLevel() > hardwareScalingLevel) {
  109184. var scaling = babylonjs_1.Scalar.Clamp(viewer.engine.getHardwareScalingLevel() - 0.25, 0, hardwareScalingLevel);
  109185. viewer.engine.setHardwareScalingLevel(scaling);
  109186. return false;
  109187. }
  109188. if (!viewer.sceneManager.processShadows) {
  109189. viewer.sceneManager.processShadows = true;
  109190. return false;
  109191. }
  109192. if (defaultPipeline && !viewer.sceneManager.bloomEnabled) {
  109193. viewer.sceneManager.bloomEnabled = true;
  109194. return false;
  109195. }
  109196. if (!viewer.sceneManager.groundMirrorEnabled) {
  109197. viewer.sceneManager.groundMirrorEnabled = true;
  109198. return false;
  109199. }
  109200. return true;
  109201. }
  109202. exports.extendedUpgrade = extendedUpgrade;
  109203. /**
  109204. * A custom degrade-oriented function configuration for the scene optimizer.
  109205. *
  109206. * @param viewer the viewer to optimize
  109207. */
  109208. function extendedDegrade(viewer) {
  109209. var defaultPipeline = viewer.sceneManager.defaultRenderingPipeline;
  109210. if (viewer.sceneManager.groundMirrorEnabled) {
  109211. viewer.sceneManager.groundMirrorEnabled = false;
  109212. return false;
  109213. }
  109214. if (defaultPipeline && viewer.sceneManager.bloomEnabled) {
  109215. viewer.sceneManager.bloomEnabled = false;
  109216. return false;
  109217. }
  109218. if (viewer.sceneManager.processShadows) {
  109219. viewer.sceneManager.processShadows = false;
  109220. return false;
  109221. }
  109222. if (viewer.engine.getHardwareScalingLevel() < 1) {
  109223. var scaling = babylonjs_1.Scalar.Clamp(viewer.engine.getHardwareScalingLevel() + 0.25, 0, 1);
  109224. viewer.engine.setHardwareScalingLevel(scaling);
  109225. return false;
  109226. }
  109227. if (defaultPipeline && viewer.sceneManager.fxaaEnabled) {
  109228. viewer.sceneManager.fxaaEnabled = false;
  109229. return false;
  109230. }
  109231. if (viewer.sceneManager.groundEnabled) {
  109232. viewer.sceneManager.groundEnabled = false;
  109233. return false;
  109234. }
  109235. if (viewer.sceneManager.scene.postProcessesEnabled) {
  109236. viewer.sceneManager.scene.postProcessesEnabled = false;
  109237. return false;
  109238. }
  109239. if (viewer.engine.getHardwareScalingLevel() < 1.25) {
  109240. var scaling = babylonjs_1.Scalar.Clamp(viewer.engine.getHardwareScalingLevel() + 0.25, 0, 1.25);
  109241. viewer.engine.setHardwareScalingLevel(scaling);
  109242. return false;
  109243. }
  109244. // if (this.Scene.BackgroundHelper) {
  109245. // this.Scene.EngineScene.autoClear = true;
  109246. // this.Scene.BackgroundHelper = false;
  109247. // Would require a dedicated clear color;
  109248. // return false;
  109249. // }
  109250. return true;
  109251. }
  109252. exports.extendedDegrade = extendedDegrade;
  109253. /***/ }),
  109254. /* 35 */
  109255. /***/ (function(module, exports, __webpack_require__) {
  109256. "use strict";
  109257. Object.defineProperty(exports, "__esModule", { value: true });
  109258. var babylonjs_1 = __webpack_require__(0);
  109259. var helper_1 = __webpack_require__(2);
  109260. var deepmerge = __webpack_require__(1);
  109261. /**
  109262. * The template manager, a member of the viewer class, will manage the viewer's templates and generate the HTML.
  109263. * The template manager managers a single viewer and can be seen as the collection of all sub-templates of the viewer.
  109264. */
  109265. var TemplateManager = /** @class */ (function () {
  109266. function TemplateManager(containerElement) {
  109267. this.containerElement = containerElement;
  109268. this.templates = {};
  109269. this.onTemplateInit = new babylonjs_1.Observable();
  109270. this.onTemplateLoaded = new babylonjs_1.Observable();
  109271. this.onTemplateStateChange = new babylonjs_1.Observable();
  109272. this.onAllLoaded = new babylonjs_1.Observable();
  109273. this.onEventTriggered = new babylonjs_1.Observable();
  109274. this.eventManager = new eventManager_1.EventManager(this);
  109275. }
  109276. /**
  109277. * Initialize the template(s) for the viewer. Called bay the Viewer class
  109278. * @param templates the templates to be used to initialize the main template
  109279. */
  109280. TemplateManager.prototype.initTemplate = function (templates) {
  109281. var _this = this;
  109282. var internalInit = function (dependencyMap, name, parentTemplate) {
  109283. //init template
  109284. var template = _this.templates[name];
  109285. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  109286. return internalInit(dependencyMap[childName], childName, template);
  109287. });
  109288. // register the observers
  109289. //template.onLoaded.add(() => {
  109290. var addToParent = function () {
  109291. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  109292. template.appendTo(containingElement);
  109293. _this._checkLoadedState();
  109294. };
  109295. if (parentTemplate && !parentTemplate.parent) {
  109296. parentTemplate.onAppended.add(function () {
  109297. addToParent();
  109298. });
  109299. }
  109300. else {
  109301. addToParent();
  109302. }
  109303. //});
  109304. return template;
  109305. };
  109306. //build the html tree
  109307. return this._buildHTMLTree(templates).then(function (htmlTree) {
  109308. if (_this.templates['main']) {
  109309. internalInit(htmlTree, 'main');
  109310. }
  109311. else {
  109312. _this._checkLoadedState();
  109313. }
  109314. return;
  109315. });
  109316. };
  109317. /**
  109318. *
  109319. * This function will create a simple map with child-dependencies of the template html tree.
  109320. * It will compile each template, check if its children exist in the configuration and will add them if they do.
  109321. * It is expected that the main template will be called main!
  109322. *
  109323. * @param templates
  109324. */
  109325. TemplateManager.prototype._buildHTMLTree = function (templates) {
  109326. var _this = this;
  109327. var promises = Object.keys(templates).map(function (name) {
  109328. // if the template was overridden
  109329. if (!templates[name])
  109330. return Promise.resolve(false);
  109331. // else - we have a template, let's do our job!
  109332. var template = new Template(name, templates[name]);
  109333. template.onLoaded.add(function () {
  109334. _this.onTemplateLoaded.notifyObservers(template);
  109335. });
  109336. template.onStateChange.add(function () {
  109337. _this.onTemplateStateChange.notifyObservers(template);
  109338. });
  109339. _this.onTemplateInit.notifyObservers(template);
  109340. // make sure the global onEventTriggered is called as well
  109341. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  109342. _this.templates[name] = template;
  109343. return template.initPromise;
  109344. });
  109345. return Promise.all(promises).then(function () {
  109346. var templateStructure = {};
  109347. // now iterate through all templates and check for children:
  109348. var buildTree = function (parentObject, name) {
  109349. _this.templates[name].isInHtmlTree = true;
  109350. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  109351. childNodes.forEach(function (element) {
  109352. parentObject[element] = {};
  109353. buildTree(parentObject[element], element);
  109354. });
  109355. };
  109356. if (_this.templates['main']) {
  109357. buildTree(templateStructure, "main");
  109358. }
  109359. return templateStructure;
  109360. });
  109361. };
  109362. /**
  109363. * Get the canvas in the template tree.
  109364. * There must be one and only one canvas inthe template.
  109365. */
  109366. TemplateManager.prototype.getCanvas = function () {
  109367. return this.containerElement.querySelector('canvas');
  109368. };
  109369. /**
  109370. * Get a specific template from the template tree
  109371. * @param name the name of the template to load
  109372. */
  109373. TemplateManager.prototype.getTemplate = function (name) {
  109374. return this.templates[name];
  109375. };
  109376. TemplateManager.prototype._checkLoadedState = function () {
  109377. var _this = this;
  109378. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  109379. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  109380. });
  109381. if (done) {
  109382. this.onAllLoaded.notifyObservers(this);
  109383. }
  109384. };
  109385. /**
  109386. * Dispose the template manager
  109387. */
  109388. TemplateManager.prototype.dispose = function () {
  109389. var _this = this;
  109390. // dispose all templates
  109391. Object.keys(this.templates).forEach(function (template) {
  109392. _this.templates[template].dispose();
  109393. });
  109394. this.templates = {};
  109395. this.eventManager.dispose();
  109396. this.onTemplateInit.clear();
  109397. this.onAllLoaded.clear();
  109398. this.onEventTriggered.clear();
  109399. this.onTemplateLoaded.clear();
  109400. this.onTemplateStateChange.clear();
  109401. };
  109402. return TemplateManager;
  109403. }());
  109404. exports.TemplateManager = TemplateManager;
  109405. var Handlebars = __webpack_require__(36);
  109406. var eventManager_1 = __webpack_require__(37);
  109407. // register a new helper. modified https://stackoverflow.com/questions/9838925/is-there-any-method-to-iterate-a-map-with-handlebars-js
  109408. Handlebars.registerHelper('eachInMap', function (map, block) {
  109409. var out = '';
  109410. Object.keys(map).map(function (prop) {
  109411. var data = map[prop];
  109412. if (typeof data === 'object') {
  109413. data.id = data.id || prop;
  109414. out += block.fn(data);
  109415. }
  109416. else {
  109417. out += block.fn({ id: prop, value: data });
  109418. }
  109419. });
  109420. return out;
  109421. });
  109422. Handlebars.registerHelper('add', function (a, b) {
  109423. var out = a + b;
  109424. return out;
  109425. });
  109426. Handlebars.registerHelper('eq', function (a, b) {
  109427. var out = (a == b);
  109428. return out;
  109429. });
  109430. Handlebars.registerHelper('or', function (a, b) {
  109431. var out = a || b;
  109432. return out;
  109433. });
  109434. Handlebars.registerHelper('not', function (a) {
  109435. var out = !a;
  109436. return out;
  109437. });
  109438. Handlebars.registerHelper('count', function (map) {
  109439. return map.length;
  109440. });
  109441. Handlebars.registerHelper('gt', function (a, b) {
  109442. var out = a > b;
  109443. return out;
  109444. });
  109445. /**
  109446. * This class represents a single template in the viewer's template tree.
  109447. * An example for a template is a single canvas, an overlay (containing sub-templates) or the navigation bar.
  109448. * A template is injected using the template manager in the correct position.
  109449. * The template is rendered using Handlebars and can use Handlebars' features (such as parameter injection)
  109450. *
  109451. * For further information please refer to the documentation page, https://doc.babylonjs.com
  109452. */
  109453. var Template = /** @class */ (function () {
  109454. function Template(name, _configuration) {
  109455. var _this = this;
  109456. this.name = name;
  109457. this._configuration = _configuration;
  109458. this.onLoaded = new babylonjs_1.Observable();
  109459. this.onAppended = new babylonjs_1.Observable();
  109460. this.onStateChange = new babylonjs_1.Observable();
  109461. this.onEventTriggered = new babylonjs_1.Observable();
  109462. this.loadRequests = [];
  109463. this.isLoaded = false;
  109464. this.isShown = false;
  109465. this.isInHtmlTree = false;
  109466. var htmlContentPromise = this._getTemplateAsHtml(_configuration);
  109467. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  109468. if (htmlTemplate) {
  109469. _this._htmlTemplate = htmlTemplate;
  109470. var compiledTemplate = Handlebars.compile(htmlTemplate, { noEscape: (_this._configuration.params && _this._configuration.params.noEscape) });
  109471. var config = _this._configuration.params || {};
  109472. _this._rawHtml = compiledTemplate(config);
  109473. try {
  109474. _this._fragment = document.createRange().createContextualFragment(_this._rawHtml);
  109475. }
  109476. catch (e) {
  109477. var test = document.createElement(_this.name);
  109478. test.innerHTML = _this._rawHtml;
  109479. _this._fragment = test;
  109480. }
  109481. _this.isLoaded = true;
  109482. _this.isShown = true;
  109483. _this.onLoaded.notifyObservers(_this);
  109484. }
  109485. return _this;
  109486. });
  109487. }
  109488. /**
  109489. * Some templates have parameters (like background color for example).
  109490. * The parameters are provided to Handlebars which in turn generates the template.
  109491. * This function will update the template with the new parameters
  109492. *
  109493. * Note that when updating parameters the events will be registered again (after being cleared).
  109494. *
  109495. * @param params the new template parameters
  109496. */
  109497. Template.prototype.updateParams = function (params, append) {
  109498. if (append === void 0) { append = true; }
  109499. if (append) {
  109500. this._configuration.params = deepmerge(this._configuration.params, params);
  109501. }
  109502. else {
  109503. this._configuration.params = params;
  109504. }
  109505. // update the template
  109506. if (this.isLoaded) {
  109507. // this.dispose();
  109508. }
  109509. var compiledTemplate = Handlebars.compile(this._htmlTemplate);
  109510. var config = this._configuration.params || {};
  109511. this._rawHtml = compiledTemplate(config);
  109512. try {
  109513. this._fragment = document.createRange().createContextualFragment(this._rawHtml);
  109514. }
  109515. catch (e) {
  109516. var test = document.createElement(this.name);
  109517. test.innerHTML = this._rawHtml;
  109518. this._fragment = test;
  109519. }
  109520. if (this.parent) {
  109521. this.appendTo(this.parent, true);
  109522. }
  109523. };
  109524. Object.defineProperty(Template.prototype, "configuration", {
  109525. /**
  109526. * Get the template'S configuration
  109527. */
  109528. get: function () {
  109529. return this._configuration;
  109530. },
  109531. enumerable: true,
  109532. configurable: true
  109533. });
  109534. /**
  109535. * A template can be a parent element for other templates or HTML elements.
  109536. * This function will deliver all child HTML elements of this template.
  109537. */
  109538. Template.prototype.getChildElements = function () {
  109539. var childrenArray = [];
  109540. //Edge and IE don't support frage,ent.children
  109541. var children = this._fragment && this._fragment.children;
  109542. if (!this._fragment) {
  109543. var fragment = this.parent.querySelector(this.name);
  109544. if (fragment) {
  109545. children = fragment.querySelectorAll('*');
  109546. }
  109547. }
  109548. if (!children) {
  109549. // casting to HTMLCollection, as both NodeListOf and HTMLCollection have 'item()' and 'length'.
  109550. children = this._fragment.querySelectorAll('*');
  109551. }
  109552. for (var i = 0; i < children.length; ++i) {
  109553. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  109554. }
  109555. return childrenArray;
  109556. };
  109557. /**
  109558. * Appending the template to a parent HTML element.
  109559. * If a parent is already set and you wish to replace the old HTML with new one, forceRemove should be true.
  109560. * @param parent the parent to which the template is added
  109561. * @param forceRemove if the parent already exists, shoud the template be removed from it?
  109562. */
  109563. Template.prototype.appendTo = function (parent, forceRemove) {
  109564. var _this = this;
  109565. if (this.parent) {
  109566. if (forceRemove && this._addedFragment) {
  109567. /*let fragement = this.parent.querySelector(this.name)
  109568. if (fragement)
  109569. this.parent.removeChild(fragement);*/
  109570. this.parent.innerHTML = '';
  109571. }
  109572. else {
  109573. return;
  109574. }
  109575. }
  109576. this.parent = parent;
  109577. if (this._configuration.id) {
  109578. this.parent.id = this._configuration.id;
  109579. }
  109580. if (this._fragment) {
  109581. this.parent.appendChild(this._fragment);
  109582. this._addedFragment = this._fragment;
  109583. }
  109584. else {
  109585. this.parent.insertAdjacentHTML("beforeend", this._rawHtml);
  109586. }
  109587. // appended only one frame after.
  109588. setTimeout(function () {
  109589. _this._registerEvents();
  109590. _this.onAppended.notifyObservers(_this);
  109591. });
  109592. };
  109593. /**
  109594. * Show the template using the provided visibilityFunction, or natively using display: flex.
  109595. * The provided function returns a promise that should be fullfilled when the element is shown.
  109596. * Since it is a promise async operations are more than possible.
  109597. * See the default viewer for an opacity example.
  109598. * @param visibilityFunction The function to execute to show the template.
  109599. */
  109600. Template.prototype.show = function (visibilityFunction) {
  109601. var _this = this;
  109602. if (this._isHiding)
  109603. return Promise.resolve(this);
  109604. return Promise.resolve().then(function () {
  109605. _this._isShowing = true;
  109606. if (visibilityFunction) {
  109607. return visibilityFunction(_this);
  109608. }
  109609. else {
  109610. // flex? box? should this be configurable easier than the visibilityFunction?
  109611. _this.parent.style.display = 'flex';
  109612. // support old browsers with no flex:
  109613. if (_this.parent.style.display !== 'flex') {
  109614. _this.parent.style.display = '';
  109615. }
  109616. return _this;
  109617. }
  109618. }).then(function () {
  109619. _this.isShown = true;
  109620. _this._isShowing = false;
  109621. _this.onStateChange.notifyObservers(_this);
  109622. return _this;
  109623. });
  109624. };
  109625. /**
  109626. * Hide the template using the provided visibilityFunction, or natively using display: none.
  109627. * The provided function returns a promise that should be fullfilled when the element is hidden.
  109628. * Since it is a promise async operations are more than possible.
  109629. * See the default viewer for an opacity example.
  109630. * @param visibilityFunction The function to execute to show the template.
  109631. */
  109632. Template.prototype.hide = function (visibilityFunction) {
  109633. var _this = this;
  109634. if (this._isShowing)
  109635. return Promise.resolve(this);
  109636. return Promise.resolve().then(function () {
  109637. _this._isHiding = true;
  109638. if (visibilityFunction) {
  109639. return visibilityFunction(_this);
  109640. }
  109641. else {
  109642. // flex? box? should this be configurable easier than the visibilityFunction?
  109643. _this.parent.style.display = 'none';
  109644. return _this;
  109645. }
  109646. }).then(function () {
  109647. _this.isShown = false;
  109648. _this._isHiding = false;
  109649. _this.onStateChange.notifyObservers(_this);
  109650. return _this;
  109651. });
  109652. };
  109653. /**
  109654. * Dispose this template
  109655. */
  109656. Template.prototype.dispose = function () {
  109657. this.onAppended.clear();
  109658. this.onEventTriggered.clear();
  109659. this.onLoaded.clear();
  109660. this.onStateChange.clear();
  109661. this.isLoaded = false;
  109662. // remove from parent
  109663. try {
  109664. this.parent.removeChild(this._fragment);
  109665. }
  109666. catch (e) {
  109667. //noop
  109668. }
  109669. this.loadRequests.forEach(function (request) {
  109670. request.abort();
  109671. });
  109672. if (this._registeredEvents) {
  109673. this._registeredEvents.forEach(function (evt) {
  109674. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  109675. });
  109676. }
  109677. delete this._fragment;
  109678. };
  109679. Template.prototype._getTemplateAsHtml = function (templateConfig) {
  109680. var _this = this;
  109681. if (!templateConfig) {
  109682. return Promise.reject('No templateConfig provided');
  109683. }
  109684. else if (templateConfig.html !== undefined) {
  109685. return Promise.resolve(templateConfig.html);
  109686. }
  109687. else {
  109688. var location_1 = this._getTemplateLocation(templateConfig);
  109689. if (helper_1.isUrl(location_1)) {
  109690. return new Promise(function (resolve, reject) {
  109691. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  109692. resolve(data);
  109693. }, undefined, undefined, false, function (request, error) {
  109694. reject(error);
  109695. });
  109696. _this.loadRequests.push(fileRequest);
  109697. });
  109698. }
  109699. else {
  109700. location_1 = location_1.replace('#', '');
  109701. var element = document.getElementById(location_1);
  109702. if (element) {
  109703. return Promise.resolve(element.innerHTML);
  109704. }
  109705. else {
  109706. return Promise.reject('Template ID not found');
  109707. }
  109708. }
  109709. }
  109710. };
  109711. Template.prototype._registerEvents = function () {
  109712. var _this = this;
  109713. this._registeredEvents = this._registeredEvents || [];
  109714. if (this._registeredEvents.length) {
  109715. // first remove the registered events
  109716. this._registeredEvents.forEach(function (evt) {
  109717. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  109718. });
  109719. }
  109720. if (this._configuration.events) {
  109721. var _loop_1 = function (eventName) {
  109722. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  109723. var functionToFire_1 = function (selector, event) {
  109724. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  109725. };
  109726. // if boolean, set the parent as the event listener
  109727. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  109728. var selector = this_1.parent.id;
  109729. if (selector) {
  109730. selector = '#' + selector;
  109731. }
  109732. else {
  109733. selector = this_1.parent.tagName;
  109734. }
  109735. var binding = functionToFire_1.bind(this_1, selector);
  109736. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, selector), false);
  109737. this_1._registeredEvents.push({
  109738. htmlElement: this_1.parent,
  109739. eventName: eventName,
  109740. function: binding
  109741. });
  109742. }
  109743. else if (typeof this_1._configuration.events[eventName] === 'object') {
  109744. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  109745. // strict null checl is working incorrectly, must override:
  109746. var event_1 = this_1._configuration.events[eventName] || {};
  109747. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  109748. if (selector && selector.indexOf('#') !== 0) {
  109749. selector = '#' + selector;
  109750. }
  109751. var htmlElement = _this.parent.querySelector(selector);
  109752. if (htmlElement) {
  109753. var binding = functionToFire_1.bind(_this, selector);
  109754. htmlElement.addEventListener(eventName, binding, false);
  109755. _this._registeredEvents.push({
  109756. htmlElement: htmlElement,
  109757. eventName: eventName,
  109758. function: binding
  109759. });
  109760. }
  109761. });
  109762. }
  109763. }
  109764. };
  109765. var this_1 = this;
  109766. for (var eventName in this._configuration.events) {
  109767. _loop_1(eventName);
  109768. }
  109769. }
  109770. };
  109771. Template.prototype._getTemplateLocation = function (templateConfig) {
  109772. if (!templateConfig || typeof templateConfig === 'string') {
  109773. return templateConfig;
  109774. }
  109775. else {
  109776. return templateConfig.location;
  109777. }
  109778. };
  109779. return Template;
  109780. }());
  109781. exports.Template = Template;
  109782. /***/ }),
  109783. /* 36 */
  109784. /***/ (function(module, exports, __webpack_require__) {
  109785. /**!
  109786. @license
  109787. handlebars v4.0.11
  109788. Copyright (C) 2011-2017 by Yehuda Katz
  109789. Permission is hereby granted, free of charge, to any person obtaining a copy
  109790. of this software and associated documentation files (the "Software"), to deal
  109791. in the Software without restriction, including without limitation the rights
  109792. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  109793. copies of the Software, and to permit persons to whom the Software is
  109794. furnished to do so, subject to the following conditions:
  109795. The above copyright notice and this permission notice shall be included in
  109796. all copies or substantial portions of the Software.
  109797. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  109798. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  109799. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  109800. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  109801. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  109802. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  109803. THE SOFTWARE.
  109804. */
  109805. !function(a,b){ true?module.exports=b():"function"==typeof define&&define.amd?define([],b):"object"==typeof exports?exports.Handlebars=b():a.Handlebars=b()}(this,function(){return function(a){function b(d){if(c[d])return c[d].exports;var e=c[d]={exports:{},id:d,loaded:!1};return a[d].call(e.exports,e,e.exports,b),e.loaded=!0,e.exports}var c={};return b.m=a,b.c=c,b.p="",b(0)}([function(a,b,c){"use strict";function d(){var a=r();return a.compile=function(b,c){return k.compile(b,c,a)},a.precompile=function(b,c){return k.precompile(b,c,a)},a.AST=i["default"],a.Compiler=k.Compiler,a.JavaScriptCompiler=m["default"],a.Parser=j.parser,a.parse=j.parse,a}var e=c(1)["default"];b.__esModule=!0;var f=c(2),g=e(f),h=c(35),i=e(h),j=c(36),k=c(41),l=c(42),m=e(l),n=c(39),o=e(n),p=c(34),q=e(p),r=g["default"].create,s=d();s.create=d,q["default"](s),s.Visitor=o["default"],s["default"]=s,b["default"]=s,a.exports=b["default"]},function(a,b){"use strict";b["default"]=function(a){return a&&a.__esModule?a:{"default":a}},b.__esModule=!0},function(a,b,c){"use strict";function d(){var a=new h.HandlebarsEnvironment;return n.extend(a,h),a.SafeString=j["default"],a.Exception=l["default"],a.Utils=n,a.escapeExpression=n.escapeExpression,a.VM=p,a.template=function(b){return p.template(b,a)},a}var e=c(3)["default"],f=c(1)["default"];b.__esModule=!0;var g=c(4),h=e(g),i=c(21),j=f(i),k=c(6),l=f(k),m=c(5),n=e(m),o=c(22),p=e(o),q=c(34),r=f(q),s=d();s.create=d,r["default"](s),s["default"]=s,b["default"]=s,a.exports=b["default"]},function(a,b){"use strict";b["default"]=function(a){if(a&&a.__esModule)return a;var b={};if(null!=a)for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&(b[c]=a[c]);return b["default"]=a,b},b.__esModule=!0},function(a,b,c){"use strict";function d(a,b,c){this.helpers=a||{},this.partials=b||{},this.decorators=c||{},i.registerDefaultHelpers(this),j.registerDefaultDecorators(this)}var e=c(1)["default"];b.__esModule=!0,b.HandlebarsEnvironment=d;var f=c(5),g=c(6),h=e(g),i=c(10),j=c(18),k=c(20),l=e(k),m="4.0.11";b.VERSION=m;var n=7;b.COMPILER_REVISION=n;var o={1:"<= 1.0.rc.2",2:"== 1.0.0-rc.3",3:"== 1.0.0-rc.4",4:"== 1.x.x",5:"== 2.0.0-alpha.x",6:">= 2.0.0-beta.1",7:">= 4.0.0"};b.REVISION_CHANGES=o;var p="[object Object]";d.prototype={constructor:d,logger:l["default"],log:l["default"].log,registerHelper:function(a,b){if(f.toString.call(a)===p){if(b)throw new h["default"]("Arg not supported with multiple helpers");f.extend(this.helpers,a)}else this.helpers[a]=b},unregisterHelper:function(a){delete this.helpers[a]},registerPartial:function(a,b){if(f.toString.call(a)===p)f.extend(this.partials,a);else{if("undefined"==typeof b)throw new h["default"]('Attempting to register a partial called "'+a+'" as undefined');this.partials[a]=b}},unregisterPartial:function(a){delete this.partials[a]},registerDecorator:function(a,b){if(f.toString.call(a)===p){if(b)throw new h["default"]("Arg not supported with multiple decorators");f.extend(this.decorators,a)}else this.decorators[a]=b},unregisterDecorator:function(a){delete this.decorators[a]}};var q=l["default"].log;b.log=q,b.createFrame=f.createFrame,b.logger=l["default"]},function(a,b){"use strict";function c(a){return k[a]}function d(a){for(var b=1;b<arguments.length;b++)for(var c in arguments[b])Object.prototype.hasOwnProperty.call(arguments[b],c)&&(a[c]=arguments[b][c]);return a}function e(a,b){for(var c=0,d=a.length;c<d;c++)if(a[c]===b)return c;return-1}function f(a){if("string"!=typeof a){if(a&&a.toHTML)return a.toHTML();if(null==a)return"";if(!a)return a+"";a=""+a}return m.test(a)?a.replace(l,c):a}function g(a){return!a&&0!==a||!(!p(a)||0!==a.length)}function h(a){var b=d({},a);return b._parent=a,b}function i(a,b){return a.path=b,a}function j(a,b){return(a?a+".":"")+b}b.__esModule=!0,b.extend=d,b.indexOf=e,b.escapeExpression=f,b.isEmpty=g,b.createFrame=h,b.blockParams=i,b.appendContextPath=j;var k={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;","=":"&#x3D;"},l=/[&<>"'`=]/g,m=/[&<>"'`=]/,n=Object.prototype.toString;b.toString=n;var o=function(a){return"function"==typeof a};o(/x/)&&(b.isFunction=o=function(a){return"function"==typeof a&&"[object Function]"===n.call(a)}),b.isFunction=o;var p=Array.isArray||function(a){return!(!a||"object"!=typeof a)&&"[object Array]"===n.call(a)};b.isArray=p},function(a,b,c){"use strict";function d(a,b){var c=b&&b.loc,g=void 0,h=void 0;c&&(g=c.start.line,h=c.start.column,a+=" - "+g+":"+h);for(var i=Error.prototype.constructor.call(this,a),j=0;j<f.length;j++)this[f[j]]=i[f[j]];Error.captureStackTrace&&Error.captureStackTrace(this,d);try{c&&(this.lineNumber=g,e?Object.defineProperty(this,"column",{value:h,enumerable:!0}):this.column=h)}catch(k){}}var e=c(7)["default"];b.__esModule=!0;var f=["description","fileName","lineNumber","message","name","number","stack"];d.prototype=new Error,b["default"]=d,a.exports=b["default"]},function(a,b,c){a.exports={"default":c(8),__esModule:!0}},function(a,b,c){var d=c(9);a.exports=function(a,b,c){return d.setDesc(a,b,c)}},function(a,b){var c=Object;a.exports={create:c.create,getProto:c.getPrototypeOf,isEnum:{}.propertyIsEnumerable,getDesc:c.getOwnPropertyDescriptor,setDesc:c.defineProperty,setDescs:c.defineProperties,getKeys:c.keys,getNames:c.getOwnPropertyNames,getSymbols:c.getOwnPropertySymbols,each:[].forEach}},function(a,b,c){"use strict";function d(a){g["default"](a),i["default"](a),k["default"](a),m["default"](a),o["default"](a),q["default"](a),s["default"](a)}var e=c(1)["default"];b.__esModule=!0,b.registerDefaultHelpers=d;var f=c(11),g=e(f),h=c(12),i=e(h),j=c(13),k=e(j),l=c(14),m=e(l),n=c(15),o=e(n),p=c(16),q=e(p),r=c(17),s=e(r)},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerHelper("blockHelperMissing",function(b,c){var e=c.inverse,f=c.fn;if(b===!0)return f(this);if(b===!1||null==b)return e(this);if(d.isArray(b))return b.length>0?(c.ids&&(c.ids=[c.name]),a.helpers.each(b,c)):e(this);if(c.data&&c.ids){var g=d.createFrame(c.data);g.contextPath=d.appendContextPath(c.data.contextPath,c.name),c={data:g}}return f(b,c)})},a.exports=b["default"]},function(a,b,c){"use strict";var d=c(1)["default"];b.__esModule=!0;var e=c(5),f=c(6),g=d(f);b["default"]=function(a){a.registerHelper("each",function(a,b){function c(b,c,f){j&&(j.key=b,j.index=c,j.first=0===c,j.last=!!f,k&&(j.contextPath=k+b)),i+=d(a[b],{data:j,blockParams:e.blockParams([a[b],b],[k+b,null])})}if(!b)throw new g["default"]("Must pass iterator to #each");var d=b.fn,f=b.inverse,h=0,i="",j=void 0,k=void 0;if(b.data&&b.ids&&(k=e.appendContextPath(b.data.contextPath,b.ids[0])+"."),e.isFunction(a)&&(a=a.call(this)),b.data&&(j=e.createFrame(b.data)),a&&"object"==typeof a)if(e.isArray(a))for(var l=a.length;h<l;h++)h in a&&c(h,h,h===a.length-1);else{var m=void 0;for(var n in a)a.hasOwnProperty(n)&&(void 0!==m&&c(m,h-1),m=n,h++);void 0!==m&&c(m,h-1,!0)}return 0===h&&(i=f(this)),i})},a.exports=b["default"]},function(a,b,c){"use strict";var d=c(1)["default"];b.__esModule=!0;var e=c(6),f=d(e);b["default"]=function(a){a.registerHelper("helperMissing",function(){if(1!==arguments.length)throw new f["default"]('Missing helper: "'+arguments[arguments.length-1].name+'"')})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerHelper("if",function(a,b){return d.isFunction(a)&&(a=a.call(this)),!b.hash.includeZero&&!a||d.isEmpty(a)?b.inverse(this):b.fn(this)}),a.registerHelper("unless",function(b,c){return a.helpers["if"].call(this,b,{fn:c.inverse,inverse:c.fn,hash:c.hash})})},a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,b["default"]=function(a){a.registerHelper("log",function(){for(var b=[void 0],c=arguments[arguments.length-1],d=0;d<arguments.length-1;d++)b.push(arguments[d]);var e=1;null!=c.hash.level?e=c.hash.level:c.data&&null!=c.data.level&&(e=c.data.level),b[0]=e,a.log.apply(a,b)})},a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,b["default"]=function(a){a.registerHelper("lookup",function(a,b){return a&&a[b]})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerHelper("with",function(a,b){d.isFunction(a)&&(a=a.call(this));var c=b.fn;if(d.isEmpty(a))return b.inverse(this);var e=b.data;return b.data&&b.ids&&(e=d.createFrame(b.data),e.contextPath=d.appendContextPath(b.data.contextPath,b.ids[0])),c(a,{data:e,blockParams:d.blockParams([a],[e&&e.contextPath])})})},a.exports=b["default"]},function(a,b,c){"use strict";function d(a){g["default"](a)}var e=c(1)["default"];b.__esModule=!0,b.registerDefaultDecorators=d;var f=c(19),g=e(f)},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerDecorator("inline",function(a,b,c,e){var f=a;return b.partials||(b.partials={},f=function(e,f){var g=c.partials;c.partials=d.extend({},g,b.partials);var h=a(e,f);return c.partials=g,h}),b.partials[e.args[0]]=e.fn,f})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5),e={methodMap:["debug","info","warn","error"],level:"info",lookupLevel:function(a){if("string"==typeof a){var b=d.indexOf(e.methodMap,a.toLowerCase());a=b>=0?b:parseInt(a,10)}return a},log:function(a){if(a=e.lookupLevel(a),"undefined"!=typeof console&&e.lookupLevel(e.level)<=a){var b=e.methodMap[a];console[b]||(b="log");for(var c=arguments.length,d=Array(c>1?c-1:0),f=1;f<c;f++)d[f-1]=arguments[f];console[b].apply(console,d)}}};b["default"]=e,a.exports=b["default"]},function(a,b){"use strict";function c(a){this.string=a}b.__esModule=!0,c.prototype.toString=c.prototype.toHTML=function(){return""+this.string},b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(a){var b=a&&a[0]||1,c=s.COMPILER_REVISION;if(b!==c){if(b<c){var d=s.REVISION_CHANGES[c],e=s.REVISION_CHANGES[b];throw new r["default"]("Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version ("+d+") or downgrade your runtime to an older version ("+e+").")}throw new r["default"]("Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version ("+a[1]+").")}}function e(a,b){function c(c,d,e){e.hash&&(d=p.extend({},d,e.hash),e.ids&&(e.ids[0]=!0)),c=b.VM.resolvePartial.call(this,c,d,e);var f=b.VM.invokePartial.call(this,c,d,e);if(null==f&&b.compile&&(e.partials[e.name]=b.compile(c,a.compilerOptions,b),f=e.partials[e.name](d,e)),null!=f){if(e.indent){for(var g=f.split("\n"),h=0,i=g.length;h<i&&(g[h]||h+1!==i);h++)g[h]=e.indent+g[h];f=g.join("\n")}return f}throw new r["default"]("The partial "+e.name+" could not be compiled when running in runtime-only mode")}function d(b){function c(b){return""+a.main(e,b,e.helpers,e.partials,g,i,h)}var f=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],g=f.data;d._setup(f),!f.partial&&a.useData&&(g=j(b,g));var h=void 0,i=a.useBlockParams?[]:void 0;return a.useDepths&&(h=f.depths?b!=f.depths[0]?[b].concat(f.depths):f.depths:[b]),(c=k(a.main,c,e,f.depths||[],g,i))(b,f)}if(!b)throw new r["default"]("No environment passed to template");if(!a||!a.main)throw new r["default"]("Unknown template object: "+typeof a);a.main.decorator=a.main_d,b.VM.checkRevision(a.compiler);var e={strict:function(a,b){if(!(b in a))throw new r["default"]('"'+b+'" not defined in '+a);return a[b]},lookup:function(a,b){for(var c=a.length,d=0;d<c;d++)if(a[d]&&null!=a[d][b])return a[d][b]},lambda:function(a,b){return"function"==typeof a?a.call(b):a},escapeExpression:p.escapeExpression,invokePartial:c,fn:function(b){var c=a[b];return c.decorator=a[b+"_d"],c},programs:[],program:function(a,b,c,d,e){var g=this.programs[a],h=this.fn(a);return b||e||d||c?g=f(this,a,h,b,c,d,e):g||(g=this.programs[a]=f(this,a,h)),g},data:function(a,b){for(;a&&b--;)a=a._parent;return a},merge:function(a,b){var c=a||b;return a&&b&&a!==b&&(c=p.extend({},b,a)),c},nullContext:l({}),noop:b.VM.noop,compilerInfo:a.compiler};return d.isTop=!0,d._setup=function(c){c.partial?(e.helpers=c.helpers,e.partials=c.partials,e.decorators=c.decorators):(e.helpers=e.merge(c.helpers,b.helpers),a.usePartial&&(e.partials=e.merge(c.partials,b.partials)),(a.usePartial||a.useDecorators)&&(e.decorators=e.merge(c.decorators,b.decorators)))},d._child=function(b,c,d,g){if(a.useBlockParams&&!d)throw new r["default"]("must pass block params");if(a.useDepths&&!g)throw new r["default"]("must pass parent depths");return f(e,b,a[b],c,0,d,g)},d}function f(a,b,c,d,e,f,g){function h(b){var e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],h=g;return!g||b==g[0]||b===a.nullContext&&null===g[0]||(h=[b].concat(g)),c(a,b,a.helpers,a.partials,e.data||d,f&&[e.blockParams].concat(f),h)}return h=k(c,h,a,g,d,f),h.program=b,h.depth=g?g.length:0,h.blockParams=e||0,h}function g(a,b,c){return a?a.call||c.name||(c.name=a,a=c.partials[a]):a="@partial-block"===c.name?c.data["partial-block"]:c.partials[c.name],a}function h(a,b,c){var d=c.data&&c.data["partial-block"];c.partial=!0,c.ids&&(c.data.contextPath=c.ids[0]||c.data.contextPath);var e=void 0;if(c.fn&&c.fn!==i&&!function(){c.data=s.createFrame(c.data);var a=c.fn;e=c.data["partial-block"]=function(b){var c=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];return c.data=s.createFrame(c.data),c.data["partial-block"]=d,a(b,c)},a.partials&&(c.partials=p.extend({},c.partials,a.partials))}(),void 0===a&&e&&(a=e),void 0===a)throw new r["default"]("The partial "+c.name+" could not be found");if(a instanceof Function)return a(b,c)}function i(){return""}function j(a,b){return b&&"root"in b||(b=b?s.createFrame(b):{},b.root=a),b}function k(a,b,c,d,e,f){if(a.decorator){var g={};b=a.decorator(b,g,c,d&&d[0],e,f,d),p.extend(b,g)}return b}var l=c(23)["default"],m=c(3)["default"],n=c(1)["default"];b.__esModule=!0,b.checkRevision=d,b.template=e,b.wrapProgram=f,b.resolvePartial=g,b.invokePartial=h,b.noop=i;var o=c(5),p=m(o),q=c(6),r=n(q),s=c(4)},function(a,b,c){a.exports={"default":c(24),__esModule:!0}},function(a,b,c){c(25),a.exports=c(30).Object.seal},function(a,b,c){var d=c(26);c(27)("seal",function(a){return function(b){return a&&d(b)?a(b):b}})},function(a,b){a.exports=function(a){return"object"==typeof a?null!==a:"function"==typeof a}},function(a,b,c){var d=c(28),e=c(30),f=c(33);a.exports=function(a,b){var c=(e.Object||{})[a]||Object[a],g={};g[a]=b(c),d(d.S+d.F*f(function(){c(1)}),"Object",g)}},function(a,b,c){var d=c(29),e=c(30),f=c(31),g="prototype",h=function(a,b,c){var i,j,k,l=a&h.F,m=a&h.G,n=a&h.S,o=a&h.P,p=a&h.B,q=a&h.W,r=m?e:e[b]||(e[b]={}),s=m?d:n?d[b]:(d[b]||{})[g];m&&(c=b);for(i in c)j=!l&&s&&i in s,j&&i in r||(k=j?s[i]:c[i],r[i]=m&&"function"!=typeof s[i]?c[i]:p&&j?f(k,d):q&&s[i]==k?function(a){var b=function(b){return this instanceof a?new a(b):a(b)};return b[g]=a[g],b}(k):o&&"function"==typeof k?f(Function.call,k):k,o&&((r[g]||(r[g]={}))[i]=k))};h.F=1,h.G=2,h.S=4,h.P=8,h.B=16,h.W=32,a.exports=h},function(a,b){var c=a.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=c)},function(a,b){var c=a.exports={version:"1.2.6"};"number"==typeof __e&&(__e=c)},function(a,b,c){var d=c(32);a.exports=function(a,b,c){if(d(a),void 0===b)return a;switch(c){case 1:return function(c){return a.call(b,c)};case 2:return function(c,d){return a.call(b,c,d)};case 3:return function(c,d,e){return a.call(b,c,d,e)}}return function(){return a.apply(b,arguments)}}},function(a,b){a.exports=function(a){if("function"!=typeof a)throw TypeError(a+" is not a function!");return a}},function(a,b){a.exports=function(a){try{return!!a()}catch(b){return!0}}},function(a,b){(function(c){"use strict";b.__esModule=!0,b["default"]=function(a){var b="undefined"!=typeof c?c:window,d=b.Handlebars;a.noConflict=function(){return b.Handlebars===a&&(b.Handlebars=d),a}},a.exports=b["default"]}).call(b,function(){return this}())},function(a,b){"use strict";b.__esModule=!0;var c={helpers:{helperExpression:function(a){return"SubExpression"===a.type||("MustacheStatement"===a.type||"BlockStatement"===a.type)&&!!(a.params&&a.params.length||a.hash)},scopedId:function(a){return/^\.|this\b/.test(a.original)},simpleId:function(a){return 1===a.parts.length&&!c.helpers.scopedId(a)&&!a.depth}}};b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b){if("Program"===a.type)return a;h["default"].yy=n,n.locInfo=function(a){return new n.SourceLocation(b&&b.srcName,a)};var c=new j["default"](b);return c.accept(h["default"].parse(a))}var e=c(1)["default"],f=c(3)["default"];b.__esModule=!0,b.parse=d;var g=c(37),h=e(g),i=c(38),j=e(i),k=c(40),l=f(k),m=c(5);b.parser=h["default"];var n={};m.extend(n,l)},function(a,b){"use strict";b.__esModule=!0;var c=function(){function a(){this.yy={}}var b={trace:function(){},yy:{},symbols_:{error:2,root:3,program:4,EOF:5,program_repetition0:6,statement:7,mustache:8,block:9,rawBlock:10,partial:11,partialBlock:12,content:13,COMMENT:14,CONTENT:15,openRawBlock:16,rawBlock_repetition_plus0:17,END_RAW_BLOCK:18,OPEN_RAW_BLOCK:19,helperName:20,openRawBlock_repetition0:21,openRawBlock_option0:22,CLOSE_RAW_BLOCK:23,openBlock:24,block_option0:25,closeBlock:26,openInverse:27,block_option1:28,OPEN_BLOCK:29,openBlock_repetition0:30,openBlock_option0:31,openBlock_option1:32,CLOSE:33,OPEN_INVERSE:34,openInverse_repetition0:35,openInverse_option0:36,openInverse_option1:37,openInverseChain:38,OPEN_INVERSE_CHAIN:39,openInverseChain_repetition0:40,openInverseChain_option0:41,openInverseChain_option1:42,inverseAndProgram:43,INVERSE:44,inverseChain:45,inverseChain_option0:46,OPEN_ENDBLOCK:47,OPEN:48,mustache_repetition0:49,mustache_option0:50,OPEN_UNESCAPED:51,mustache_repetition1:52,mustache_option1:53,CLOSE_UNESCAPED:54,OPEN_PARTIAL:55,partialName:56,partial_repetition0:57,partial_option0:58,openPartialBlock:59,OPEN_PARTIAL_BLOCK:60,openPartialBlock_repetition0:61,openPartialBlock_option0:62,param:63,sexpr:64,OPEN_SEXPR:65,sexpr_repetition0:66,sexpr_option0:67,CLOSE_SEXPR:68,hash:69,hash_repetition_plus0:70,hashSegment:71,ID:72,EQUALS:73,blockParams:74,OPEN_BLOCK_PARAMS:75,blockParams_repetition_plus0:76,CLOSE_BLOCK_PARAMS:77,path:78,dataName:79,STRING:80,NUMBER:81,BOOLEAN:82,UNDEFINED:83,NULL:84,DATA:85,pathSegments:86,SEP:87,$accept:0,$end:1},terminals_:{2:"error",5:"EOF",14:"COMMENT",15:"CONTENT",18:"END_RAW_BLOCK",19:"OPEN_RAW_BLOCK",23:"CLOSE_RAW_BLOCK",29:"OPEN_BLOCK",33:"CLOSE",34:"OPEN_INVERSE",39:"OPEN_INVERSE_CHAIN",44:"INVERSE",47:"OPEN_ENDBLOCK",48:"OPEN",51:"OPEN_UNESCAPED",54:"CLOSE_UNESCAPED",55:"OPEN_PARTIAL",60:"OPEN_PARTIAL_BLOCK",65:"OPEN_SEXPR",68:"CLOSE_SEXPR",72:"ID",73:"EQUALS",75:"OPEN_BLOCK_PARAMS",77:"CLOSE_BLOCK_PARAMS",80:"STRING",81:"NUMBER",82:"BOOLEAN",83:"UNDEFINED",84:"NULL",85:"DATA",87:"SEP"},productions_:[0,[3,2],[4,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[13,1],[10,3],[16,5],[9,4],[9,4],[24,6],[27,6],[38,6],[43,2],[45,3],[45,1],[26,3],[8,5],[8,5],[11,5],[12,3],[59,5],[63,1],[63,1],[64,5],[69,1],[71,3],[74,3],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[56,1],[56,1],[79,2],[78,1],[86,3],[86,1],[6,0],[6,2],[17,1],[17,2],[21,0],[21,2],[22,0],[22,1],[25,0],[25,1],[28,0],[28,1],[30,0],[30,2],[31,0],[31,1],[32,0],[32,1],[35,0],[35,2],[36,0],[36,1],[37,0],[37,1],[40,0],[40,2],[41,0],[41,1],[42,0],[42,1],[46,0],[46,1],[49,0],[49,2],[50,0],[50,1],[52,0],[52,2],[53,0],[53,1],[57,0],[57,2],[58,0],[58,1],[61,0],[61,2],[62,0],[62,1],[66,0],[66,2],[67,0],[67,1],[70,1],[70,2],[76,1],[76,2]],performAction:function(a,b,c,d,e,f,g){var h=f.length-1;switch(e){case 1:return f[h-1];case 2:this.$=d.prepareProgram(f[h]);break;case 3:this.$=f[h];break;case 4:this.$=f[h];break;case 5:this.$=f[h];break;case 6:this.$=f[h];break;case 7:this.$=f[h];break;case 8:this.$=f[h];break;case 9:this.$={type:"CommentStatement",value:d.stripComment(f[h]),strip:d.stripFlags(f[h],f[h]),loc:d.locInfo(this._$)};break;case 10:this.$={type:"ContentStatement",original:f[h],value:f[h],loc:d.locInfo(this._$)};break;case 11:this.$=d.prepareRawBlock(f[h-2],f[h-1],f[h],this._$);break;case 12:this.$={path:f[h-3],params:f[h-2],hash:f[h-1]};break;case 13:this.$=d.prepareBlock(f[h-3],f[h-2],f[h-1],f[h],!1,this._$);break;case 14:this.$=d.prepareBlock(f[h-3],f[h-2],f[h-1],f[h],!0,this._$);break;case 15:this.$={open:f[h-5],path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 16:this.$={path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 17:this.$={path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 18:this.$={strip:d.stripFlags(f[h-1],f[h-1]),program:f[h]};break;case 19:var i=d.prepareBlock(f[h-2],f[h-1],f[h],f[h],!1,this._$),j=d.prepareProgram([i],f[h-1].loc);j.chained=!0,this.$={strip:f[h-2].strip,program:j,chain:!0};break;case 20:this.$=f[h];break;case 21:this.$={path:f[h-1],strip:d.stripFlags(f[h-2],f[h])};break;case 22:this.$=d.prepareMustache(f[h-3],f[h-2],f[h-1],f[h-4],d.stripFlags(f[h-4],f[h]),this._$);break;case 23:this.$=d.prepareMustache(f[h-3],f[h-2],f[h-1],f[h-4],d.stripFlags(f[h-4],f[h]),this._$);break;case 24:this.$={type:"PartialStatement",name:f[h-3],params:f[h-2],hash:f[h-1],indent:"",strip:d.stripFlags(f[h-4],f[h]),loc:d.locInfo(this._$)};break;case 25:this.$=d.preparePartialBlock(f[h-2],f[h-1],f[h],this._$);break;case 26:this.$={path:f[h-3],params:f[h-2],hash:f[h-1],strip:d.stripFlags(f[h-4],f[h])};break;case 27:this.$=f[h];break;case 28:this.$=f[h];break;case 29:this.$={type:"SubExpression",path:f[h-3],params:f[h-2],hash:f[h-1],loc:d.locInfo(this._$)};break;case 30:this.$={type:"Hash",pairs:f[h],loc:d.locInfo(this._$)};break;case 31:this.$={type:"HashPair",key:d.id(f[h-2]),value:f[h],loc:d.locInfo(this._$)};break;case 32:this.$=d.id(f[h-1]);break;case 33:this.$=f[h];break;case 34:this.$=f[h];break;case 35:this.$={type:"StringLiteral",value:f[h],original:f[h],loc:d.locInfo(this._$)};break;case 36:this.$={type:"NumberLiteral",value:Number(f[h]),original:Number(f[h]),loc:d.locInfo(this._$)};break;case 37:this.$={type:"BooleanLiteral",value:"true"===f[h],original:"true"===f[h],loc:d.locInfo(this._$)};break;case 38:this.$={type:"UndefinedLiteral",original:void 0,value:void 0,loc:d.locInfo(this._$)};break;case 39:this.$={type:"NullLiteral",original:null,value:null,loc:d.locInfo(this._$)};break;case 40:this.$=f[h];break;case 41:this.$=f[h];break;case 42:this.$=d.preparePath(!0,f[h],this._$);break;case 43:this.$=d.preparePath(!1,f[h],this._$);break;case 44:f[h-2].push({part:d.id(f[h]),original:f[h],separator:f[h-1]}),this.$=f[h-2];break;case 45:this.$=[{part:d.id(f[h]),original:f[h]}];break;case 46:this.$=[];break;case 47:f[h-1].push(f[h]);break;case 48:this.$=[f[h]];break;case 49:f[h-1].push(f[h]);break;case 50:this.$=[];break;case 51:f[h-1].push(f[h]);break;case 58:this.$=[];break;case 59:f[h-1].push(f[h]);break;case 64:this.$=[];break;case 65:f[h-1].push(f[h]);break;case 70:this.$=[];break;case 71:f[h-1].push(f[h]);break;case 78:this.$=[];break;case 79:f[h-1].push(f[h]);break;case 82:this.$=[];break;case 83:f[h-1].push(f[h]);break;case 86:this.$=[];break;case 87:f[h-1].push(f[h]);break;case 90:this.$=[];break;case 91:f[h-1].push(f[h]);break;case 94:this.$=[];break;case 95:f[h-1].push(f[h]);break;case 98:this.$=[f[h]];break;case 99:f[h-1].push(f[h]);break;case 100:this.$=[f[h]];break;case 101:f[h-1].push(f[h])}},table:[{3:1,4:2,5:[2,46],6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{1:[3]},{5:[1,4]},{5:[2,2],7:5,8:6,9:7,10:8,11:9,12:10,13:11,14:[1,12],15:[1,20],16:17,19:[1,23],24:15,27:16,29:[1,21],34:[1,22],39:[2,2],44:[2,2],47:[2,2],48:[1,13],51:[1,14],55:[1,18],59:19,60:[1,24]},{1:[2,1]},{5:[2,47],14:[2,47],15:[2,47],19:[2,47],29:[2,47],34:[2,47],39:[2,47],44:[2,47],47:[2,47],48:[2,47],51:[2,47],55:[2,47],60:[2,47]},{5:[2,3],14:[2,3],15:[2,3],19:[2,3],29:[2,3],34:[2,3],39:[2,3],44:[2,3],47:[2,3],48:[2,3],51:[2,3],55:[2,3],60:[2,3]},{5:[2,4],14:[2,4],15:[2,4],19:[2,4],29:[2,4],34:[2,4],39:[2,4],44:[2,4],47:[2,4],48:[2,4],51:[2,4],55:[2,4],60:[2,4]},{5:[2,5],14:[2,5],15:[2,5],19:[2,5],29:[2,5],34:[2,5],39:[2,5],44:[2,5],47:[2,5],48:[2,5],51:[2,5],55:[2,5],60:[2,5]},{5:[2,6],14:[2,6],15:[2,6],19:[2,6],29:[2,6],34:[2,6],39:[2,6],44:[2,6],47:[2,6],48:[2,6],51:[2,6],55:[2,6],60:[2,6]},{5:[2,7],14:[2,7],15:[2,7],19:[2,7],29:[2,7],34:[2,7],39:[2,7],44:[2,7],47:[2,7],48:[2,7],51:[2,7],55:[2,7],60:[2,7]},{5:[2,8],14:[2,8],15:[2,8],19:[2,8],29:[2,8],34:[2,8],39:[2,8],44:[2,8],47:[2,8],48:[2,8],51:[2,8],55:[2,8],60:[2,8]},{5:[2,9],14:[2,9],15:[2,9],19:[2,9],29:[2,9],34:[2,9],39:[2,9],44:[2,9],47:[2,9],48:[2,9],51:[2,9],55:[2,9],60:[2,9]},{20:25,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:36,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:37,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{4:38,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{13:40,15:[1,20],17:39},{20:42,56:41,64:43,65:[1,44],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:45,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{5:[2,10],14:[2,10],15:[2,10],18:[2,10],19:[2,10],29:[2,10],34:[2,10],39:[2,10],44:[2,10],47:[2,10],48:[2,10],51:[2,10],55:[2,10],60:[2,10]},{20:46,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:47,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:48,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:42,56:49,64:43,65:[1,44],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[2,78],49:50,65:[2,78],72:[2,78],80:[2,78],81:[2,78],82:[2,78],83:[2,78],84:[2,78],85:[2,78]},{23:[2,33],33:[2,33],54:[2,33],65:[2,33],68:[2,33],72:[2,33],75:[2,33],80:[2,33],81:[2,33],82:[2,33],83:[2,33],84:[2,33],85:[2,33]},{23:[2,34],33:[2,34],54:[2,34],65:[2,34],68:[2,34],72:[2,34],75:[2,34],80:[2,34],81:[2,34],82:[2,34],83:[2,34],84:[2,34],85:[2,34]},{23:[2,35],33:[2,35],54:[2,35],65:[2,35],68:[2,35],72:[2,35],75:[2,35],80:[2,35],81:[2,35],82:[2,35],83:[2,35],84:[2,35],85:[2,35]},{23:[2,36],33:[2,36],54:[2,36],65:[2,36],68:[2,36],72:[2,36],75:[2,36],80:[2,36],81:[2,36],82:[2,36],83:[2,36],84:[2,36],85:[2,36]},{23:[2,37],33:[2,37],54:[2,37],65:[2,37],68:[2,37],72:[2,37],75:[2,37],80:[2,37],81:[2,37],82:[2,37],83:[2,37],84:[2,37],85:[2,37]},{23:[2,38],33:[2,38],54:[2,38],65:[2,38],68:[2,38],72:[2,38],75:[2,38],80:[2,38],81:[2,38],82:[2,38],83:[2,38],84:[2,38],85:[2,38]},{23:[2,39],33:[2,39],54:[2,39],65:[2,39],68:[2,39],72:[2,39],75:[2,39],80:[2,39],81:[2,39],82:[2,39],83:[2,39],84:[2,39],85:[2,39]},{23:[2,43],33:[2,43],54:[2,43],65:[2,43],68:[2,43],72:[2,43],75:[2,43],80:[2,43],81:[2,43],82:[2,43],83:[2,43],84:[2,43],85:[2,43],87:[1,51]},{72:[1,35],86:52},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{52:53,54:[2,82],65:[2,82],72:[2,82],80:[2,82],81:[2,82],82:[2,82],83:[2,82],84:[2,82],85:[2,82]},{25:54,38:56,39:[1,58],43:57,44:[1,59],45:55,47:[2,54]},{28:60,43:61,44:[1,59],47:[2,56]},{13:63,15:[1,20],18:[1,62]},{15:[2,48],18:[2,48]},{33:[2,86],57:64,65:[2,86],72:[2,86],80:[2,86],81:[2,86],82:[2,86],83:[2,86],84:[2,86],85:[2,86]},{33:[2,40],65:[2,40],72:[2,40],80:[2,40],81:[2,40],82:[2,40],83:[2,40],84:[2,40],85:[2,40]},{33:[2,41],65:[2,41],72:[2,41],80:[2,41],81:[2,41],82:[2,41],83:[2,41],84:[2,41],85:[2,41]},{20:65,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:66,47:[1,67]},{30:68,33:[2,58],65:[2,58],72:[2,58],75:[2,58],80:[2,58],81:[2,58],82:[2,58],83:[2,58],84:[2,58],85:[2,58]},{33:[2,64],35:69,65:[2,64],72:[2,64],75:[2,64],80:[2,64],81:[2,64],82:[2,64],83:[2,64],84:[2,64],85:[2,64]},{21:70,23:[2,50],65:[2,50],72:[2,50],80:[2,50],81:[2,50],82:[2,50],83:[2,50],84:[2,50],85:[2,50]},{33:[2,90],61:71,65:[2,90],72:[2,90],80:[2,90],81:[2,90],82:[2,90],83:[2,90],84:[2,90],85:[2,90]},{20:75,33:[2,80],50:72,63:73,64:76,65:[1,44],69:74,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{72:[1,80]},{23:[2,42],33:[2,42],54:[2,42],65:[2,42],68:[2,42],72:[2,42],75:[2,42],80:[2,42],81:[2,42],82:[2,42],83:[2,42],84:[2,42],85:[2,42],87:[1,51]},{20:75,53:81,54:[2,84],63:82,64:76,65:[1,44],69:83,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:84,47:[1,67]},{47:[2,55]},{4:85,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{47:[2,20]},{20:86,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:87,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{26:88,47:[1,67]},{47:[2,57]},{5:[2,11],14:[2,11],15:[2,11],19:[2,11],29:[2,11],34:[2,11],39:[2,11],44:[2,11],47:[2,11],48:[2,11],51:[2,11],55:[2,11],60:[2,11]},{15:[2,49],18:[2,49]},{20:75,33:[2,88],58:89,63:90,64:76,65:[1,44],69:91,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{65:[2,94],66:92,68:[2,94],72:[2,94],80:[2,94],81:[2,94],82:[2,94],83:[2,94],84:[2,94],85:[2,94]},{5:[2,25],14:[2,25],15:[2,25],19:[2,25],29:[2,25],34:[2,25],39:[2,25],44:[2,25],47:[2,25],48:[2,25],51:[2,25],55:[2,25],60:[2,25]},{20:93,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,31:94,33:[2,60],63:95,64:76,65:[1,44],69:96,70:77,71:78,72:[1,79],75:[2,60],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,33:[2,66],36:97,63:98,64:76,65:[1,44],69:99,70:77,71:78,72:[1,79],75:[2,66],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,22:100,23:[2,52],63:101,64:76,65:[1,44],69:102,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,33:[2,92],62:103,63:104,64:76,65:[1,44],69:105,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,106]},{33:[2,79],65:[2,79],72:[2,79],80:[2,79],81:[2,79],82:[2,79],83:[2,79],84:[2,79],85:[2,79]},{33:[2,81]},{23:[2,27],33:[2,27],54:[2,27],65:[2,27],68:[2,27],72:[2,27],75:[2,27],80:[2,27],81:[2,27],82:[2,27],83:[2,27],84:[2,27],85:[2,27]},{23:[2,28],33:[2,28],54:[2,28],65:[2,28],68:[2,28],72:[2,28],75:[2,28],80:[2,28],81:[2,28],82:[2,28],83:[2,28],84:[2,28],85:[2,28]},{23:[2,30],33:[2,30],54:[2,30],68:[2,30],71:107,72:[1,108],75:[2,30]},{23:[2,98],33:[2,98],54:[2,98],68:[2,98],72:[2,98],75:[2,98]},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],73:[1,109],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{23:[2,44],33:[2,44],54:[2,44],65:[2,44],68:[2,44],72:[2,44],75:[2,44],80:[2,44],81:[2,44],82:[2,44],83:[2,44],84:[2,44],85:[2,44],87:[2,44]},{54:[1,110]},{54:[2,83],65:[2,83],72:[2,83],80:[2,83],81:[2,83],82:[2,83],83:[2,83],84:[2,83],85:[2,83]},{54:[2,85]},{5:[2,13],14:[2,13],15:[2,13],19:[2,13],29:[2,13],34:[2,13],39:[2,13],44:[2,13],47:[2,13],48:[2,13],51:[2,13],55:[2,13],60:[2,13]},{38:56,39:[1,58],43:57,44:[1,59],45:112,46:111,47:[2,76]},{33:[2,70],40:113,65:[2,70],72:[2,70],75:[2,70],80:[2,70],81:[2,70],82:[2,70],83:[2,70],84:[2,70],85:[2,70]},{47:[2,18]},{5:[2,14],14:[2,14],15:[2,14],19:[2,14],29:[2,14],34:[2,14],39:[2,14],44:[2,14],47:[2,14],48:[2,14],51:[2,14],55:[2,14],60:[2,14]},{33:[1,114]},{33:[2,87],65:[2,87],72:[2,87],80:[2,87],81:[2,87],82:[2,87],83:[2,87],84:[2,87],
  109806. 85:[2,87]},{33:[2,89]},{20:75,63:116,64:76,65:[1,44],67:115,68:[2,96],69:117,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,118]},{32:119,33:[2,62],74:120,75:[1,121]},{33:[2,59],65:[2,59],72:[2,59],75:[2,59],80:[2,59],81:[2,59],82:[2,59],83:[2,59],84:[2,59],85:[2,59]},{33:[2,61],75:[2,61]},{33:[2,68],37:122,74:123,75:[1,121]},{33:[2,65],65:[2,65],72:[2,65],75:[2,65],80:[2,65],81:[2,65],82:[2,65],83:[2,65],84:[2,65],85:[2,65]},{33:[2,67],75:[2,67]},{23:[1,124]},{23:[2,51],65:[2,51],72:[2,51],80:[2,51],81:[2,51],82:[2,51],83:[2,51],84:[2,51],85:[2,51]},{23:[2,53]},{33:[1,125]},{33:[2,91],65:[2,91],72:[2,91],80:[2,91],81:[2,91],82:[2,91],83:[2,91],84:[2,91],85:[2,91]},{33:[2,93]},{5:[2,22],14:[2,22],15:[2,22],19:[2,22],29:[2,22],34:[2,22],39:[2,22],44:[2,22],47:[2,22],48:[2,22],51:[2,22],55:[2,22],60:[2,22]},{23:[2,99],33:[2,99],54:[2,99],68:[2,99],72:[2,99],75:[2,99]},{73:[1,109]},{20:75,63:126,64:76,65:[1,44],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,23],14:[2,23],15:[2,23],19:[2,23],29:[2,23],34:[2,23],39:[2,23],44:[2,23],47:[2,23],48:[2,23],51:[2,23],55:[2,23],60:[2,23]},{47:[2,19]},{47:[2,77]},{20:75,33:[2,72],41:127,63:128,64:76,65:[1,44],69:129,70:77,71:78,72:[1,79],75:[2,72],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,24],14:[2,24],15:[2,24],19:[2,24],29:[2,24],34:[2,24],39:[2,24],44:[2,24],47:[2,24],48:[2,24],51:[2,24],55:[2,24],60:[2,24]},{68:[1,130]},{65:[2,95],68:[2,95],72:[2,95],80:[2,95],81:[2,95],82:[2,95],83:[2,95],84:[2,95],85:[2,95]},{68:[2,97]},{5:[2,21],14:[2,21],15:[2,21],19:[2,21],29:[2,21],34:[2,21],39:[2,21],44:[2,21],47:[2,21],48:[2,21],51:[2,21],55:[2,21],60:[2,21]},{33:[1,131]},{33:[2,63]},{72:[1,133],76:132},{33:[1,134]},{33:[2,69]},{15:[2,12]},{14:[2,26],15:[2,26],19:[2,26],29:[2,26],34:[2,26],47:[2,26],48:[2,26],51:[2,26],55:[2,26],60:[2,26]},{23:[2,31],33:[2,31],54:[2,31],68:[2,31],72:[2,31],75:[2,31]},{33:[2,74],42:135,74:136,75:[1,121]},{33:[2,71],65:[2,71],72:[2,71],75:[2,71],80:[2,71],81:[2,71],82:[2,71],83:[2,71],84:[2,71],85:[2,71]},{33:[2,73],75:[2,73]},{23:[2,29],33:[2,29],54:[2,29],65:[2,29],68:[2,29],72:[2,29],75:[2,29],80:[2,29],81:[2,29],82:[2,29],83:[2,29],84:[2,29],85:[2,29]},{14:[2,15],15:[2,15],19:[2,15],29:[2,15],34:[2,15],39:[2,15],44:[2,15],47:[2,15],48:[2,15],51:[2,15],55:[2,15],60:[2,15]},{72:[1,138],77:[1,137]},{72:[2,100],77:[2,100]},{14:[2,16],15:[2,16],19:[2,16],29:[2,16],34:[2,16],44:[2,16],47:[2,16],48:[2,16],51:[2,16],55:[2,16],60:[2,16]},{33:[1,139]},{33:[2,75]},{33:[2,32]},{72:[2,101],77:[2,101]},{14:[2,17],15:[2,17],19:[2,17],29:[2,17],34:[2,17],39:[2,17],44:[2,17],47:[2,17],48:[2,17],51:[2,17],55:[2,17],60:[2,17]}],defaultActions:{4:[2,1],55:[2,55],57:[2,20],61:[2,57],74:[2,81],83:[2,85],87:[2,18],91:[2,89],102:[2,53],105:[2,93],111:[2,19],112:[2,77],117:[2,97],120:[2,63],123:[2,69],124:[2,12],136:[2,75],137:[2,32]},parseError:function(a,b){throw new Error(a)},parse:function(a){function b(){var a;return a=c.lexer.lex()||1,"number"!=typeof a&&(a=c.symbols_[a]||a),a}var c=this,d=[0],e=[null],f=[],g=this.table,h="",i=0,j=0,k=0;this.lexer.setInput(a),this.lexer.yy=this.yy,this.yy.lexer=this.lexer,this.yy.parser=this,"undefined"==typeof this.lexer.yylloc&&(this.lexer.yylloc={});var l=this.lexer.yylloc;f.push(l);var m=this.lexer.options&&this.lexer.options.ranges;"function"==typeof this.yy.parseError&&(this.parseError=this.yy.parseError);for(var n,o,p,q,r,s,t,u,v,w={};;){if(p=d[d.length-1],this.defaultActions[p]?q=this.defaultActions[p]:(null!==n&&"undefined"!=typeof n||(n=b()),q=g[p]&&g[p][n]),"undefined"==typeof q||!q.length||!q[0]){var x="";if(!k){v=[];for(s in g[p])this.terminals_[s]&&s>2&&v.push("'"+this.terminals_[s]+"'");x=this.lexer.showPosition?"Parse error on line "+(i+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+v.join(", ")+", got '"+(this.terminals_[n]||n)+"'":"Parse error on line "+(i+1)+": Unexpected "+(1==n?"end of input":"'"+(this.terminals_[n]||n)+"'"),this.parseError(x,{text:this.lexer.match,token:this.terminals_[n]||n,line:this.lexer.yylineno,loc:l,expected:v})}}if(q[0]instanceof Array&&q.length>1)throw new Error("Parse Error: multiple actions possible at state: "+p+", token: "+n);switch(q[0]){case 1:d.push(n),e.push(this.lexer.yytext),f.push(this.lexer.yylloc),d.push(q[1]),n=null,o?(n=o,o=null):(j=this.lexer.yyleng,h=this.lexer.yytext,i=this.lexer.yylineno,l=this.lexer.yylloc,k>0&&k--);break;case 2:if(t=this.productions_[q[1]][1],w.$=e[e.length-t],w._$={first_line:f[f.length-(t||1)].first_line,last_line:f[f.length-1].last_line,first_column:f[f.length-(t||1)].first_column,last_column:f[f.length-1].last_column},m&&(w._$.range=[f[f.length-(t||1)].range[0],f[f.length-1].range[1]]),r=this.performAction.call(w,h,j,i,this.yy,q[1],e,f),"undefined"!=typeof r)return r;t&&(d=d.slice(0,-1*t*2),e=e.slice(0,-1*t),f=f.slice(0,-1*t)),d.push(this.productions_[q[1]][0]),e.push(w.$),f.push(w._$),u=g[d[d.length-2]][d[d.length-1]],d.push(u);break;case 3:return!0}}return!0}},c=function(){var a={EOF:1,parseError:function(a,b){if(!this.yy.parser)throw new Error(a);this.yy.parser.parseError(a,b)},setInput:function(a){return this._input=a,this._more=this._less=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var a=this._input[0];this.yytext+=a,this.yyleng++,this.offset++,this.match+=a,this.matched+=a;var b=a.match(/(?:\r\n?|\n).*/g);return b?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),a},unput:function(a){var b=a.length,c=a.split(/(?:\r\n?|\n)/g);this._input=a+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-b-1),this.offset-=b;var d=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),c.length-1&&(this.yylineno-=c.length-1);var e=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:c?(c.length===d.length?this.yylloc.first_column:0)+d[d.length-c.length].length-c[0].length:this.yylloc.first_column-b},this.options.ranges&&(this.yylloc.range=[e[0],e[0]+this.yyleng-b]),this},more:function(){return this._more=!0,this},less:function(a){this.unput(this.match.slice(a))},pastInput:function(){var a=this.matched.substr(0,this.matched.length-this.match.length);return(a.length>20?"...":"")+a.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var a=this.match;return a.length<20&&(a+=this._input.substr(0,20-a.length)),(a.substr(0,20)+(a.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var a=this.pastInput(),b=new Array(a.length+1).join("-");return a+this.upcomingInput()+"\n"+b+"^"},next:function(){if(this.done)return this.EOF;this._input||(this.done=!0);var a,b,c,d,e;this._more||(this.yytext="",this.match="");for(var f=this._currentRules(),g=0;g<f.length&&(c=this._input.match(this.rules[f[g]]),!c||b&&!(c[0].length>b[0].length)||(b=c,d=g,this.options.flex));g++);return b?(e=b[0].match(/(?:\r\n?|\n).*/g),e&&(this.yylineno+=e.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:e?e[e.length-1].length-e[e.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+b[0].length},this.yytext+=b[0],this.match+=b[0],this.matches=b,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._input=this._input.slice(b[0].length),this.matched+=b[0],a=this.performAction.call(this,this.yy,this,f[d],this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),a?a:void 0):""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){var a=this.next();return"undefined"!=typeof a?a:this.lex()},begin:function(a){this.conditionStack.push(a)},popState:function(){return this.conditionStack.pop()},_currentRules:function(){return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules},topState:function(){return this.conditionStack[this.conditionStack.length-2]},pushState:function(a){this.begin(a)}};return a.options={},a.performAction=function(a,b,c,d){function e(a,c){return b.yytext=b.yytext.substr(a,b.yyleng-c)}switch(c){case 0:if("\\\\"===b.yytext.slice(-2)?(e(0,1),this.begin("mu")):"\\"===b.yytext.slice(-1)?(e(0,1),this.begin("emu")):this.begin("mu"),b.yytext)return 15;break;case 1:return 15;case 2:return this.popState(),15;case 3:return this.begin("raw"),15;case 4:return this.popState(),"raw"===this.conditionStack[this.conditionStack.length-1]?15:(b.yytext=b.yytext.substr(5,b.yyleng-9),"END_RAW_BLOCK");case 5:return 15;case 6:return this.popState(),14;case 7:return 65;case 8:return 68;case 9:return 19;case 10:return this.popState(),this.begin("raw"),23;case 11:return 55;case 12:return 60;case 13:return 29;case 14:return 47;case 15:return this.popState(),44;case 16:return this.popState(),44;case 17:return 34;case 18:return 39;case 19:return 51;case 20:return 48;case 21:this.unput(b.yytext),this.popState(),this.begin("com");break;case 22:return this.popState(),14;case 23:return 48;case 24:return 73;case 25:return 72;case 26:return 72;case 27:return 87;case 28:break;case 29:return this.popState(),54;case 30:return this.popState(),33;case 31:return b.yytext=e(1,2).replace(/\\"/g,'"'),80;case 32:return b.yytext=e(1,2).replace(/\\'/g,"'"),80;case 33:return 85;case 34:return 82;case 35:return 82;case 36:return 83;case 37:return 84;case 38:return 81;case 39:return 75;case 40:return 77;case 41:return 72;case 42:return b.yytext=b.yytext.replace(/\\([\\\]])/g,"$1"),72;case 43:return"INVALID";case 44:return 5}},a.rules=[/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/,/^(?:\{\{\{\{(?=[^\/]))/,/^(?:\{\{\{\{\/[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.])\}\}\}\})/,/^(?:[^\x00]*?(?=(\{\{\{\{)))/,/^(?:[\s\S]*?--(~)?\}\})/,/^(?:\()/,/^(?:\))/,/^(?:\{\{\{\{)/,/^(?:\}\}\}\})/,/^(?:\{\{(~)?>)/,/^(?:\{\{(~)?#>)/,/^(?:\{\{(~)?#\*?)/,/^(?:\{\{(~)?\/)/,/^(?:\{\{(~)?\^\s*(~)?\}\})/,/^(?:\{\{(~)?\s*else\s*(~)?\}\})/,/^(?:\{\{(~)?\^)/,/^(?:\{\{(~)?\s*else\b)/,/^(?:\{\{(~)?\{)/,/^(?:\{\{(~)?&)/,/^(?:\{\{(~)?!--)/,/^(?:\{\{(~)?![\s\S]*?\}\})/,/^(?:\{\{(~)?\*?)/,/^(?:=)/,/^(?:\.\.)/,/^(?:\.(?=([=~}\s\/.)|])))/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}(~)?\}\})/,/^(?:(~)?\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@)/,/^(?:true(?=([~}\s)])))/,/^(?:false(?=([~}\s)])))/,/^(?:undefined(?=([~}\s)])))/,/^(?:null(?=([~}\s)])))/,/^(?:-?[0-9]+(?:\.[0-9]+)?(?=([~}\s)])))/,/^(?:as\s+\|)/,/^(?:\|)/,/^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)|]))))/,/^(?:\[(\\\]|[^\]])*\])/,/^(?:.)/,/^(?:$)/],a.conditions={mu:{rules:[7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44],inclusive:!1},emu:{rules:[2],inclusive:!1},com:{rules:[6],inclusive:!1},raw:{rules:[3,4,5],inclusive:!1},INITIAL:{rules:[0,1,44],inclusive:!0}},a}();return b.lexer=c,a.prototype=b,b.Parser=a,new a}();b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(){var a=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.options=a}function e(a,b,c){void 0===b&&(b=a.length);var d=a[b-1],e=a[b-2];return d?"ContentStatement"===d.type?(e||!c?/\r?\n\s*?$/:/(^|\r?\n)\s*?$/).test(d.original):void 0:c}function f(a,b,c){void 0===b&&(b=-1);var d=a[b+1],e=a[b+2];return d?"ContentStatement"===d.type?(e||!c?/^\s*?\r?\n/:/^\s*?(\r?\n|$)/).test(d.original):void 0:c}function g(a,b,c){var d=a[null==b?0:b+1];if(d&&"ContentStatement"===d.type&&(c||!d.rightStripped)){var e=d.value;d.value=d.value.replace(c?/^\s+/:/^[ \t]*\r?\n?/,""),d.rightStripped=d.value!==e}}function h(a,b,c){var d=a[null==b?a.length-1:b-1];if(d&&"ContentStatement"===d.type&&(c||!d.leftStripped)){var e=d.value;return d.value=d.value.replace(c?/\s+$/:/[ \t]+$/,""),d.leftStripped=d.value!==e,d.leftStripped}}var i=c(1)["default"];b.__esModule=!0;var j=c(39),k=i(j);d.prototype=new k["default"],d.prototype.Program=function(a){var b=!this.options.ignoreStandalone,c=!this.isRootSeen;this.isRootSeen=!0;for(var d=a.body,i=0,j=d.length;i<j;i++){var k=d[i],l=this.accept(k);if(l){var m=e(d,i,c),n=f(d,i,c),o=l.openStandalone&&m,p=l.closeStandalone&&n,q=l.inlineStandalone&&m&&n;l.close&&g(d,i,!0),l.open&&h(d,i,!0),b&&q&&(g(d,i),h(d,i)&&"PartialStatement"===k.type&&(k.indent=/([ \t]+$)/.exec(d[i-1].original)[1])),b&&o&&(g((k.program||k.inverse).body),h(d,i)),b&&p&&(g(d,i),h((k.inverse||k.program).body))}}return a},d.prototype.BlockStatement=d.prototype.DecoratorBlock=d.prototype.PartialBlockStatement=function(a){this.accept(a.program),this.accept(a.inverse);var b=a.program||a.inverse,c=a.program&&a.inverse,d=c,i=c;if(c&&c.chained)for(d=c.body[0].program;i.chained;)i=i.body[i.body.length-1].program;var j={open:a.openStrip.open,close:a.closeStrip.close,openStandalone:f(b.body),closeStandalone:e((d||b).body)};if(a.openStrip.close&&g(b.body,null,!0),c){var k=a.inverseStrip;k.open&&h(b.body,null,!0),k.close&&g(d.body,null,!0),a.closeStrip.open&&h(i.body,null,!0),!this.options.ignoreStandalone&&e(b.body)&&f(d.body)&&(h(b.body),g(d.body))}else a.closeStrip.open&&h(b.body,null,!0);return j},d.prototype.Decorator=d.prototype.MustacheStatement=function(a){return a.strip},d.prototype.PartialStatement=d.prototype.CommentStatement=function(a){var b=a.strip||{};return{inlineStandalone:!0,open:b.open,close:b.close}},b["default"]=d,a.exports=b["default"]},function(a,b,c){"use strict";function d(){this.parents=[]}function e(a){this.acceptRequired(a,"path"),this.acceptArray(a.params),this.acceptKey(a,"hash")}function f(a){e.call(this,a),this.acceptKey(a,"program"),this.acceptKey(a,"inverse")}function g(a){this.acceptRequired(a,"name"),this.acceptArray(a.params),this.acceptKey(a,"hash")}var h=c(1)["default"];b.__esModule=!0;var i=c(6),j=h(i);d.prototype={constructor:d,mutating:!1,acceptKey:function(a,b){var c=this.accept(a[b]);if(this.mutating){if(c&&!d.prototype[c.type])throw new j["default"]('Unexpected node type "'+c.type+'" found when accepting '+b+" on "+a.type);a[b]=c}},acceptRequired:function(a,b){if(this.acceptKey(a,b),!a[b])throw new j["default"](a.type+" requires "+b)},acceptArray:function(a){for(var b=0,c=a.length;b<c;b++)this.acceptKey(a,b),a[b]||(a.splice(b,1),b--,c--)},accept:function(a){if(a){if(!this[a.type])throw new j["default"]("Unknown type: "+a.type,a);this.current&&this.parents.unshift(this.current),this.current=a;var b=this[a.type](a);return this.current=this.parents.shift(),!this.mutating||b?b:b!==!1?a:void 0}},Program:function(a){this.acceptArray(a.body)},MustacheStatement:e,Decorator:e,BlockStatement:f,DecoratorBlock:f,PartialStatement:g,PartialBlockStatement:function(a){g.call(this,a),this.acceptKey(a,"program")},ContentStatement:function(){},CommentStatement:function(){},SubExpression:e,PathExpression:function(){},StringLiteral:function(){},NumberLiteral:function(){},BooleanLiteral:function(){},UndefinedLiteral:function(){},NullLiteral:function(){},Hash:function(a){this.acceptArray(a.pairs)},HashPair:function(a){this.acceptRequired(a,"value")}},b["default"]=d,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b){if(b=b.path?b.path.original:b,a.path.original!==b){var c={loc:a.path.loc};throw new q["default"](a.path.original+" doesn't match "+b,c)}}function e(a,b){this.source=a,this.start={line:b.first_line,column:b.first_column},this.end={line:b.last_line,column:b.last_column}}function f(a){return/^\[.*\]$/.test(a)?a.substr(1,a.length-2):a}function g(a,b){return{open:"~"===a.charAt(2),close:"~"===b.charAt(b.length-3)}}function h(a){return a.replace(/^\{\{~?\!-?-?/,"").replace(/-?-?~?\}\}$/,"")}function i(a,b,c){c=this.locInfo(c);for(var d=a?"@":"",e=[],f=0,g="",h=0,i=b.length;h<i;h++){var j=b[h].part,k=b[h].original!==j;if(d+=(b[h].separator||"")+j,k||".."!==j&&"."!==j&&"this"!==j)e.push(j);else{if(e.length>0)throw new q["default"]("Invalid path: "+d,{loc:c});".."===j&&(f++,g+="../")}}return{type:"PathExpression",data:a,depth:f,parts:e,original:d,loc:c}}function j(a,b,c,d,e,f){var g=d.charAt(3)||d.charAt(2),h="{"!==g&&"&"!==g,i=/\*/.test(d);return{type:i?"Decorator":"MustacheStatement",path:a,params:b,hash:c,escaped:h,strip:e,loc:this.locInfo(f)}}function k(a,b,c,e){d(a,c),e=this.locInfo(e);var f={type:"Program",body:b,strip:{},loc:e};return{type:"BlockStatement",path:a.path,params:a.params,hash:a.hash,program:f,openStrip:{},inverseStrip:{},closeStrip:{},loc:e}}function l(a,b,c,e,f,g){e&&e.path&&d(a,e);var h=/\*/.test(a.open);b.blockParams=a.blockParams;var i=void 0,j=void 0;if(c){if(h)throw new q["default"]("Unexpected inverse block on decorator",c);c.chain&&(c.program.body[0].closeStrip=e.strip),j=c.strip,i=c.program}return f&&(f=i,i=b,b=f),{type:h?"DecoratorBlock":"BlockStatement",path:a.path,params:a.params,hash:a.hash,program:b,inverse:i,openStrip:a.strip,inverseStrip:j,closeStrip:e&&e.strip,loc:this.locInfo(g)}}function m(a,b){if(!b&&a.length){var c=a[0].loc,d=a[a.length-1].loc;c&&d&&(b={source:c.source,start:{line:c.start.line,column:c.start.column},end:{line:d.end.line,column:d.end.column}})}return{type:"Program",body:a,strip:{},loc:b}}function n(a,b,c,e){return d(a,c),{type:"PartialBlockStatement",name:a.path,params:a.params,hash:a.hash,program:b,openStrip:a.strip,closeStrip:c&&c.strip,loc:this.locInfo(e)}}var o=c(1)["default"];b.__esModule=!0,b.SourceLocation=e,b.id=f,b.stripFlags=g,b.stripComment=h,b.preparePath=i,b.prepareMustache=j,b.prepareRawBlock=k,b.prepareBlock=l,b.prepareProgram=m,b.preparePartialBlock=n;var p=c(6),q=o(p)},function(a,b,c){"use strict";function d(){}function e(a,b,c){if(null==a||"string"!=typeof a&&"Program"!==a.type)throw new k["default"]("You must pass a string or Handlebars AST to Handlebars.precompile. You passed "+a);b=b||{},"data"in b||(b.data=!0),b.compat&&(b.useDepths=!0);var d=c.parse(a,b),e=(new c.Compiler).compile(d,b);return(new c.JavaScriptCompiler).compile(e,b)}function f(a,b,c){function d(){var d=c.parse(a,b),e=(new c.Compiler).compile(d,b),f=(new c.JavaScriptCompiler).compile(e,b,void 0,!0);return c.template(f)}function e(a,b){return f||(f=d()),f.call(this,a,b)}if(void 0===b&&(b={}),null==a||"string"!=typeof a&&"Program"!==a.type)throw new k["default"]("You must pass a string or Handlebars AST to Handlebars.compile. You passed "+a);b=l.extend({},b),"data"in b||(b.data=!0),b.compat&&(b.useDepths=!0);var f=void 0;return e._setup=function(a){return f||(f=d()),f._setup(a)},e._child=function(a,b,c,e){return f||(f=d()),f._child(a,b,c,e)},e}function g(a,b){if(a===b)return!0;if(l.isArray(a)&&l.isArray(b)&&a.length===b.length){for(var c=0;c<a.length;c++)if(!g(a[c],b[c]))return!1;return!0}}function h(a){if(!a.path.parts){var b=a.path;a.path={type:"PathExpression",data:!1,depth:0,parts:[b.original+""],original:b.original+"",loc:b.loc}}}var i=c(1)["default"];b.__esModule=!0,b.Compiler=d,b.precompile=e,b.compile=f;var j=c(6),k=i(j),l=c(5),m=c(35),n=i(m),o=[].slice;d.prototype={compiler:d,equals:function(a){var b=this.opcodes.length;if(a.opcodes.length!==b)return!1;for(var c=0;c<b;c++){var d=this.opcodes[c],e=a.opcodes[c];if(d.opcode!==e.opcode||!g(d.args,e.args))return!1}b=this.children.length;for(var c=0;c<b;c++)if(!this.children[c].equals(a.children[c]))return!1;return!0},guid:0,compile:function(a,b){this.sourceNode=[],this.opcodes=[],this.children=[],this.options=b,this.stringParams=b.stringParams,this.trackIds=b.trackIds,b.blockParams=b.blockParams||[];var c=b.knownHelpers;if(b.knownHelpers={helperMissing:!0,blockHelperMissing:!0,each:!0,"if":!0,unless:!0,"with":!0,log:!0,lookup:!0},c)for(var d in c)d in c&&(this.options.knownHelpers[d]=c[d]);return this.accept(a)},compileProgram:function(a){var b=new this.compiler,c=b.compile(a,this.options),d=this.guid++;return this.usePartial=this.usePartial||c.usePartial,this.children[d]=c,this.useDepths=this.useDepths||c.useDepths,d},accept:function(a){if(!this[a.type])throw new k["default"]("Unknown type: "+a.type,a);this.sourceNode.unshift(a);var b=this[a.type](a);return this.sourceNode.shift(),b},Program:function(a){this.options.blockParams.unshift(a.blockParams);for(var b=a.body,c=b.length,d=0;d<c;d++)this.accept(b[d]);return this.options.blockParams.shift(),this.isSimple=1===c,this.blockParams=a.blockParams?a.blockParams.length:0,this},BlockStatement:function(a){h(a);var b=a.program,c=a.inverse;b=b&&this.compileProgram(b),c=c&&this.compileProgram(c);var d=this.classifySexpr(a);"helper"===d?this.helperSexpr(a,b,c):"simple"===d?(this.simpleSexpr(a),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.opcode("emptyHash"),this.opcode("blockValue",a.path.original)):(this.ambiguousSexpr(a,b,c),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.opcode("emptyHash"),this.opcode("ambiguousBlockValue")),this.opcode("append")},DecoratorBlock:function(a){var b=a.program&&this.compileProgram(a.program),c=this.setupFullMustacheParams(a,b,void 0),d=a.path;this.useDecorators=!0,this.opcode("registerDecorator",c.length,d.original)},PartialStatement:function(a){this.usePartial=!0;var b=a.program;b&&(b=this.compileProgram(a.program));var c=a.params;if(c.length>1)throw new k["default"]("Unsupported number of partial arguments: "+c.length,a);c.length||(this.options.explicitPartialContext?this.opcode("pushLiteral","undefined"):c.push({type:"PathExpression",parts:[],depth:0}));var d=a.name.original,e="SubExpression"===a.name.type;e&&this.accept(a.name),this.setupFullMustacheParams(a,b,void 0,!0);var f=a.indent||"";this.options.preventIndent&&f&&(this.opcode("appendContent",f),f=""),this.opcode("invokePartial",e,d,f),this.opcode("append")},PartialBlockStatement:function(a){this.PartialStatement(a)},MustacheStatement:function(a){this.SubExpression(a),a.escaped&&!this.options.noEscape?this.opcode("appendEscaped"):this.opcode("append")},Decorator:function(a){this.DecoratorBlock(a)},ContentStatement:function(a){a.value&&this.opcode("appendContent",a.value)},CommentStatement:function(){},SubExpression:function(a){h(a);var b=this.classifySexpr(a);"simple"===b?this.simpleSexpr(a):"helper"===b?this.helperSexpr(a):this.ambiguousSexpr(a)},ambiguousSexpr:function(a,b,c){var d=a.path,e=d.parts[0],f=null!=b||null!=c;this.opcode("getContext",d.depth),this.opcode("pushProgram",b),this.opcode("pushProgram",c),d.strict=!0,this.accept(d),this.opcode("invokeAmbiguous",e,f)},simpleSexpr:function(a){var b=a.path;b.strict=!0,this.accept(b),this.opcode("resolvePossibleLambda")},helperSexpr:function(a,b,c){var d=this.setupFullMustacheParams(a,b,c),e=a.path,f=e.parts[0];if(this.options.knownHelpers[f])this.opcode("invokeKnownHelper",d.length,f);else{if(this.options.knownHelpersOnly)throw new k["default"]("You specified knownHelpersOnly, but used the unknown helper "+f,a);e.strict=!0,e.falsy=!0,this.accept(e),this.opcode("invokeHelper",d.length,e.original,n["default"].helpers.simpleId(e))}},PathExpression:function(a){this.addDepth(a.depth),this.opcode("getContext",a.depth);var b=a.parts[0],c=n["default"].helpers.scopedId(a),d=!a.depth&&!c&&this.blockParamIndex(b);d?this.opcode("lookupBlockParam",d,a.parts):b?a.data?(this.options.data=!0,this.opcode("lookupData",a.depth,a.parts,a.strict)):this.opcode("lookupOnContext",a.parts,a.falsy,a.strict,c):this.opcode("pushContext")},StringLiteral:function(a){this.opcode("pushString",a.value)},NumberLiteral:function(a){this.opcode("pushLiteral",a.value)},BooleanLiteral:function(a){this.opcode("pushLiteral",a.value)},UndefinedLiteral:function(){this.opcode("pushLiteral","undefined")},NullLiteral:function(){this.opcode("pushLiteral","null")},Hash:function(a){var b=a.pairs,c=0,d=b.length;for(this.opcode("pushHash");c<d;c++)this.pushParam(b[c].value);for(;c--;)this.opcode("assignToHash",b[c].key);this.opcode("popHash")},opcode:function(a){this.opcodes.push({opcode:a,args:o.call(arguments,1),loc:this.sourceNode[0].loc})},addDepth:function(a){a&&(this.useDepths=!0)},classifySexpr:function(a){var b=n["default"].helpers.simpleId(a.path),c=b&&!!this.blockParamIndex(a.path.parts[0]),d=!c&&n["default"].helpers.helperExpression(a),e=!c&&(d||b);if(e&&!d){var f=a.path.parts[0],g=this.options;g.knownHelpers[f]?d=!0:g.knownHelpersOnly&&(e=!1)}return d?"helper":e?"ambiguous":"simple"},pushParams:function(a){for(var b=0,c=a.length;b<c;b++)this.pushParam(a[b])},pushParam:function(a){var b=null!=a.value?a.value:a.original||"";if(this.stringParams)b.replace&&(b=b.replace(/^(\.?\.\/)*/g,"").replace(/\//g,".")),a.depth&&this.addDepth(a.depth),this.opcode("getContext",a.depth||0),this.opcode("pushStringParam",b,a.type),"SubExpression"===a.type&&this.accept(a);else{if(this.trackIds){var c=void 0;if(!a.parts||n["default"].helpers.scopedId(a)||a.depth||(c=this.blockParamIndex(a.parts[0])),c){var d=a.parts.slice(1).join(".");this.opcode("pushId","BlockParam",c,d)}else b=a.original||b,b.replace&&(b=b.replace(/^this(?:\.|$)/,"").replace(/^\.\//,"").replace(/^\.$/,"")),this.opcode("pushId",a.type,b)}this.accept(a)}},setupFullMustacheParams:function(a,b,c,d){var e=a.params;return this.pushParams(e),this.opcode("pushProgram",b),this.opcode("pushProgram",c),a.hash?this.accept(a.hash):this.opcode("emptyHash",d),e},blockParamIndex:function(a){for(var b=0,c=this.options.blockParams.length;b<c;b++){var d=this.options.blockParams[b],e=d&&l.indexOf(d,a);if(d&&e>=0)return[b,e]}}}},function(a,b,c){"use strict";function d(a){this.value=a}function e(){}function f(a,b,c,d){var e=b.popStack(),f=0,g=c.length;for(a&&g--;f<g;f++)e=b.nameLookup(e,c[f],d);return a?[b.aliasable("container.strict"),"(",e,", ",b.quotedString(c[f]),")"]:e}var g=c(1)["default"];b.__esModule=!0;var h=c(4),i=c(6),j=g(i),k=c(5),l=c(43),m=g(l);e.prototype={nameLookup:function(a,b){return e.isValidJavaScriptVariableName(b)?[a,".",b]:[a,"[",JSON.stringify(b),"]"]},depthedLookup:function(a){return[this.aliasable("container.lookup"),'(depths, "',a,'")']},compilerInfo:function(){var a=h.COMPILER_REVISION,b=h.REVISION_CHANGES[a];return[a,b]},appendToBuffer:function(a,b,c){return k.isArray(a)||(a=[a]),a=this.source.wrap(a,b),this.environment.isSimple?["return ",a,";"]:c?["buffer += ",a,";"]:(a.appendToBuffer=!0,a)},initializeBuffer:function(){return this.quotedString("")},compile:function(a,b,c,d){this.environment=a,this.options=b,this.stringParams=this.options.stringParams,this.trackIds=this.options.trackIds,this.precompile=!d,this.name=this.environment.name,this.isChild=!!c,this.context=c||{decorators:[],programs:[],environments:[]},this.preamble(),this.stackSlot=0,this.stackVars=[],this.aliases={},this.registers={list:[]},this.hashes=[],this.compileStack=[],this.inlineStack=[],this.blockParams=[],this.compileChildren(a,b),this.useDepths=this.useDepths||a.useDepths||a.useDecorators||this.options.compat,this.useBlockParams=this.useBlockParams||a.useBlockParams;var e=a.opcodes,f=void 0,g=void 0,h=void 0,i=void 0;for(h=0,i=e.length;h<i;h++)f=e[h],this.source.currentLocation=f.loc,g=g||f.loc,this[f.opcode].apply(this,f.args);if(this.source.currentLocation=g,this.pushSource(""),this.stackSlot||this.inlineStack.length||this.compileStack.length)throw new j["default"]("Compile completed with content left on stack");this.decorators.isEmpty()?this.decorators=void 0:(this.useDecorators=!0,this.decorators.prepend("var decorators = container.decorators;\n"),this.decorators.push("return fn;"),d?this.decorators=Function.apply(this,["fn","props","container","depth0","data","blockParams","depths",this.decorators.merge()]):(this.decorators.prepend("function(fn, props, container, depth0, data, blockParams, depths) {\n"),this.decorators.push("}\n"),this.decorators=this.decorators.merge()));var k=this.createFunctionContext(d);if(this.isChild)return k;var l={compiler:this.compilerInfo(),main:k};this.decorators&&(l.main_d=this.decorators,l.useDecorators=!0);var m=this.context,n=m.programs,o=m.decorators;for(h=0,i=n.length;h<i;h++)n[h]&&(l[h]=n[h],o[h]&&(l[h+"_d"]=o[h],l.useDecorators=!0));return this.environment.usePartial&&(l.usePartial=!0),this.options.data&&(l.useData=!0),this.useDepths&&(l.useDepths=!0),this.useBlockParams&&(l.useBlockParams=!0),this.options.compat&&(l.compat=!0),d?l.compilerOptions=this.options:(l.compiler=JSON.stringify(l.compiler),this.source.currentLocation={start:{line:1,column:0}},l=this.objectLiteral(l),b.srcName?(l=l.toStringWithSourceMap({file:b.destName}),l.map=l.map&&l.map.toString()):l=l.toString()),l},preamble:function(){this.lastContext=0,this.source=new m["default"](this.options.srcName),this.decorators=new m["default"](this.options.srcName)},createFunctionContext:function(a){var b="",c=this.stackVars.concat(this.registers.list);c.length>0&&(b+=", "+c.join(", "));var d=0;for(var e in this.aliases){var f=this.aliases[e];this.aliases.hasOwnProperty(e)&&f.children&&f.referenceCount>1&&(b+=", alias"+ ++d+"="+e,f.children[0]="alias"+d)}var g=["container","depth0","helpers","partials","data"];(this.useBlockParams||this.useDepths)&&g.push("blockParams"),this.useDepths&&g.push("depths");var h=this.mergeSource(b);return a?(g.push(h),Function.apply(this,g)):this.source.wrap(["function(",g.join(","),") {\n ",h,"}"])},mergeSource:function(a){var b=this.environment.isSimple,c=!this.forceBuffer,d=void 0,e=void 0,f=void 0,g=void 0;return this.source.each(function(a){a.appendToBuffer?(f?a.prepend(" + "):f=a,g=a):(f&&(e?f.prepend("buffer += "):d=!0,g.add(";"),f=g=void 0),e=!0,b||(c=!1))}),c?f?(f.prepend("return "),g.add(";")):e||this.source.push('return "";'):(a+=", buffer = "+(d?"":this.initializeBuffer()),f?(f.prepend("return buffer + "),g.add(";")):this.source.push("return buffer;")),a&&this.source.prepend("var "+a.substring(2)+(d?"":";\n")),this.source.merge()},blockValue:function(a){var b=this.aliasable("helpers.blockHelperMissing"),c=[this.contextName(0)];this.setupHelperArgs(a,0,c);var d=this.popStack();c.splice(1,0,d),this.push(this.source.functionCall(b,"call",c))},ambiguousBlockValue:function(){var a=this.aliasable("helpers.blockHelperMissing"),b=[this.contextName(0)];this.setupHelperArgs("",0,b,!0),this.flushInline();var c=this.topStack();b.splice(1,0,c),this.pushSource(["if (!",this.lastHelper,") { ",c," = ",this.source.functionCall(a,"call",b),"}"])},appendContent:function(a){this.pendingContent?a=this.pendingContent+a:this.pendingLocation=this.source.currentLocation,this.pendingContent=a},append:function(){if(this.isInline())this.replaceStack(function(a){return[" != null ? ",a,' : ""']}),this.pushSource(this.appendToBuffer(this.popStack()));else{var a=this.popStack();this.pushSource(["if (",a," != null) { ",this.appendToBuffer(a,void 0,!0)," }"]),this.environment.isSimple&&this.pushSource(["else { ",this.appendToBuffer("''",void 0,!0)," }"])}},appendEscaped:function(){this.pushSource(this.appendToBuffer([this.aliasable("container.escapeExpression"),"(",this.popStack(),")"]))},getContext:function(a){this.lastContext=a},pushContext:function(){this.pushStackLiteral(this.contextName(this.lastContext))},lookupOnContext:function(a,b,c,d){var e=0;d||!this.options.compat||this.lastContext?this.pushContext():this.push(this.depthedLookup(a[e++])),this.resolvePath("context",a,e,b,c)},lookupBlockParam:function(a,b){this.useBlockParams=!0,this.push(["blockParams[",a[0],"][",a[1],"]"]),this.resolvePath("context",b,1)},lookupData:function(a,b,c){a?this.pushStackLiteral("container.data(data, "+a+")"):this.pushStackLiteral("data"),this.resolvePath("data",b,0,!0,c)},resolvePath:function(a,b,c,d,e){var g=this;if(this.options.strict||this.options.assumeObjects)return void this.push(f(this.options.strict&&e,this,b,a));for(var h=b.length;c<h;c++)this.replaceStack(function(e){
  109807. var f=g.nameLookup(e,b[c],a);return d?[" && ",f]:[" != null ? ",f," : ",e]})},resolvePossibleLambda:function(){this.push([this.aliasable("container.lambda"),"(",this.popStack(),", ",this.contextName(0),")"])},pushStringParam:function(a,b){this.pushContext(),this.pushString(b),"SubExpression"!==b&&("string"==typeof a?this.pushString(a):this.pushStackLiteral(a))},emptyHash:function(a){this.trackIds&&this.push("{}"),this.stringParams&&(this.push("{}"),this.push("{}")),this.pushStackLiteral(a?"undefined":"{}")},pushHash:function(){this.hash&&this.hashes.push(this.hash),this.hash={values:[],types:[],contexts:[],ids:[]}},popHash:function(){var a=this.hash;this.hash=this.hashes.pop(),this.trackIds&&this.push(this.objectLiteral(a.ids)),this.stringParams&&(this.push(this.objectLiteral(a.contexts)),this.push(this.objectLiteral(a.types))),this.push(this.objectLiteral(a.values))},pushString:function(a){this.pushStackLiteral(this.quotedString(a))},pushLiteral:function(a){this.pushStackLiteral(a)},pushProgram:function(a){null!=a?this.pushStackLiteral(this.programExpression(a)):this.pushStackLiteral(null)},registerDecorator:function(a,b){var c=this.nameLookup("decorators",b,"decorator"),d=this.setupHelperArgs(b,a);this.decorators.push(["fn = ",this.decorators.functionCall(c,"",["fn","props","container",d])," || fn;"])},invokeHelper:function(a,b,c){var d=this.popStack(),e=this.setupHelper(a,b),f=c?[e.name," || "]:"",g=["("].concat(f,d);this.options.strict||g.push(" || ",this.aliasable("helpers.helperMissing")),g.push(")"),this.push(this.source.functionCall(g,"call",e.callParams))},invokeKnownHelper:function(a,b){var c=this.setupHelper(a,b);this.push(this.source.functionCall(c.name,"call",c.callParams))},invokeAmbiguous:function(a,b){this.useRegister("helper");var c=this.popStack();this.emptyHash();var d=this.setupHelper(0,a,b),e=this.lastHelper=this.nameLookup("helpers",a,"helper"),f=["(","(helper = ",e," || ",c,")"];this.options.strict||(f[0]="(helper = ",f.push(" != null ? helper : ",this.aliasable("helpers.helperMissing"))),this.push(["(",f,d.paramsInit?["),(",d.paramsInit]:[],"),","(typeof helper === ",this.aliasable('"function"')," ? ",this.source.functionCall("helper","call",d.callParams)," : helper))"])},invokePartial:function(a,b,c){var d=[],e=this.setupParams(b,1,d);a&&(b=this.popStack(),delete e.name),c&&(e.indent=JSON.stringify(c)),e.helpers="helpers",e.partials="partials",e.decorators="container.decorators",a?d.unshift(b):d.unshift(this.nameLookup("partials",b,"partial")),this.options.compat&&(e.depths="depths"),e=this.objectLiteral(e),d.push(e),this.push(this.source.functionCall("container.invokePartial","",d))},assignToHash:function(a){var b=this.popStack(),c=void 0,d=void 0,e=void 0;this.trackIds&&(e=this.popStack()),this.stringParams&&(d=this.popStack(),c=this.popStack());var f=this.hash;c&&(f.contexts[a]=c),d&&(f.types[a]=d),e&&(f.ids[a]=e),f.values[a]=b},pushId:function(a,b,c){"BlockParam"===a?this.pushStackLiteral("blockParams["+b[0]+"].path["+b[1]+"]"+(c?" + "+JSON.stringify("."+c):"")):"PathExpression"===a?this.pushString(b):"SubExpression"===a?this.pushStackLiteral("true"):this.pushStackLiteral("null")},compiler:e,compileChildren:function(a,b){for(var c=a.children,d=void 0,e=void 0,f=0,g=c.length;f<g;f++){d=c[f],e=new this.compiler;var h=this.matchExistingProgram(d);if(null==h){this.context.programs.push("");var i=this.context.programs.length;d.index=i,d.name="program"+i,this.context.programs[i]=e.compile(d,b,this.context,!this.precompile),this.context.decorators[i]=e.decorators,this.context.environments[i]=d,this.useDepths=this.useDepths||e.useDepths,this.useBlockParams=this.useBlockParams||e.useBlockParams,d.useDepths=this.useDepths,d.useBlockParams=this.useBlockParams}else d.index=h.index,d.name="program"+h.index,this.useDepths=this.useDepths||h.useDepths,this.useBlockParams=this.useBlockParams||h.useBlockParams}},matchExistingProgram:function(a){for(var b=0,c=this.context.environments.length;b<c;b++){var d=this.context.environments[b];if(d&&d.equals(a))return d}},programExpression:function(a){var b=this.environment.children[a],c=[b.index,"data",b.blockParams];return(this.useBlockParams||this.useDepths)&&c.push("blockParams"),this.useDepths&&c.push("depths"),"container.program("+c.join(", ")+")"},useRegister:function(a){this.registers[a]||(this.registers[a]=!0,this.registers.list.push(a))},push:function(a){return a instanceof d||(a=this.source.wrap(a)),this.inlineStack.push(a),a},pushStackLiteral:function(a){this.push(new d(a))},pushSource:function(a){this.pendingContent&&(this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent),this.pendingLocation)),this.pendingContent=void 0),a&&this.source.push(a)},replaceStack:function(a){var b=["("],c=void 0,e=void 0,f=void 0;if(!this.isInline())throw new j["default"]("replaceStack on non-inline");var g=this.popStack(!0);if(g instanceof d)c=[g.value],b=["(",c],f=!0;else{e=!0;var h=this.incrStack();b=["((",this.push(h)," = ",g,")"],c=this.topStack()}var i=a.call(this,c);f||this.popStack(),e&&this.stackSlot--,this.push(b.concat(i,")"))},incrStack:function(){return this.stackSlot++,this.stackSlot>this.stackVars.length&&this.stackVars.push("stack"+this.stackSlot),this.topStackName()},topStackName:function(){return"stack"+this.stackSlot},flushInline:function(){var a=this.inlineStack;this.inlineStack=[];for(var b=0,c=a.length;b<c;b++){var e=a[b];if(e instanceof d)this.compileStack.push(e);else{var f=this.incrStack();this.pushSource([f," = ",e,";"]),this.compileStack.push(f)}}},isInline:function(){return this.inlineStack.length},popStack:function(a){var b=this.isInline(),c=(b?this.inlineStack:this.compileStack).pop();if(!a&&c instanceof d)return c.value;if(!b){if(!this.stackSlot)throw new j["default"]("Invalid stack pop");this.stackSlot--}return c},topStack:function(){var a=this.isInline()?this.inlineStack:this.compileStack,b=a[a.length-1];return b instanceof d?b.value:b},contextName:function(a){return this.useDepths&&a?"depths["+a+"]":"depth"+a},quotedString:function(a){return this.source.quotedString(a)},objectLiteral:function(a){return this.source.objectLiteral(a)},aliasable:function(a){var b=this.aliases[a];return b?(b.referenceCount++,b):(b=this.aliases[a]=this.source.wrap(a),b.aliasable=!0,b.referenceCount=1,b)},setupHelper:function(a,b,c){var d=[],e=this.setupHelperArgs(b,a,d,c),f=this.nameLookup("helpers",b,"helper"),g=this.aliasable(this.contextName(0)+" != null ? "+this.contextName(0)+" : (container.nullContext || {})");return{params:d,paramsInit:e,name:f,callParams:[g].concat(d)}},setupParams:function(a,b,c){var d={},e=[],f=[],g=[],h=!c,i=void 0;h&&(c=[]),d.name=this.quotedString(a),d.hash=this.popStack(),this.trackIds&&(d.hashIds=this.popStack()),this.stringParams&&(d.hashTypes=this.popStack(),d.hashContexts=this.popStack());var j=this.popStack(),k=this.popStack();(k||j)&&(d.fn=k||"container.noop",d.inverse=j||"container.noop");for(var l=b;l--;)i=this.popStack(),c[l]=i,this.trackIds&&(g[l]=this.popStack()),this.stringParams&&(f[l]=this.popStack(),e[l]=this.popStack());return h&&(d.args=this.source.generateArray(c)),this.trackIds&&(d.ids=this.source.generateArray(g)),this.stringParams&&(d.types=this.source.generateArray(f),d.contexts=this.source.generateArray(e)),this.options.data&&(d.data="data"),this.useBlockParams&&(d.blockParams="blockParams"),d},setupHelperArgs:function(a,b,c,d){var e=this.setupParams(a,b,c);return e=this.objectLiteral(e),d?(this.useRegister("options"),c.push("options"),["options=",e]):c?(c.push(e),""):e}},function(){for(var a="break else new var case finally return void catch for switch while continue function this with default if throw delete in try do instanceof typeof abstract enum int short boolean export interface static byte extends long super char final native synchronized class float package throws const goto private transient debugger implements protected volatile double import public let yield await null true false".split(" "),b=e.RESERVED_WORDS={},c=0,d=a.length;c<d;c++)b[a[c]]=!0}(),e.isValidJavaScriptVariableName=function(a){return!e.RESERVED_WORDS[a]&&/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(a)},b["default"]=e,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b,c){if(f.isArray(a)){for(var d=[],e=0,g=a.length;e<g;e++)d.push(b.wrap(a[e],c));return d}return"boolean"==typeof a||"number"==typeof a?a+"":a}function e(a){this.srcFile=a,this.source=[]}b.__esModule=!0;var f=c(5),g=void 0;try{}catch(h){}g||(g=function(a,b,c,d){this.src="",d&&this.add(d)},g.prototype={add:function(a){f.isArray(a)&&(a=a.join("")),this.src+=a},prepend:function(a){f.isArray(a)&&(a=a.join("")),this.src=a+this.src},toStringWithSourceMap:function(){return{code:this.toString()}},toString:function(){return this.src}}),e.prototype={isEmpty:function(){return!this.source.length},prepend:function(a,b){this.source.unshift(this.wrap(a,b))},push:function(a,b){this.source.push(this.wrap(a,b))},merge:function(){var a=this.empty();return this.each(function(b){a.add([" ",b,"\n"])}),a},each:function(a){for(var b=0,c=this.source.length;b<c;b++)a(this.source[b])},empty:function(){var a=this.currentLocation||{start:{}};return new g(a.start.line,a.start.column,this.srcFile)},wrap:function(a){var b=arguments.length<=1||void 0===arguments[1]?this.currentLocation||{start:{}}:arguments[1];return a instanceof g?a:(a=d(a,this,b),new g(b.start.line,b.start.column,this.srcFile,a))},functionCall:function(a,b,c){return c=this.generateList(c),this.wrap([a,b?"."+b+"(":"(",c,")"])},quotedString:function(a){return'"'+(a+"").replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")+'"'},objectLiteral:function(a){var b=[];for(var c in a)if(a.hasOwnProperty(c)){var e=d(a[c],this);"undefined"!==e&&b.push([this.quotedString(c),":",e])}var f=this.generateList(b);return f.prepend("{"),f.add("}"),f},generateList:function(a){for(var b=this.empty(),c=0,e=a.length;c<e;c++)c&&b.add(","),b.add(d(a[c],this));return b},generateArray:function(a){var b=this.generateList(a);return b.prepend("["),b.add("]"),b}},b["default"]=e,a.exports=b["default"]}])});
  109808. /***/ }),
  109809. /* 37 */
  109810. /***/ (function(module, exports, __webpack_require__) {
  109811. "use strict";
  109812. Object.defineProperty(exports, "__esModule", { value: true });
  109813. /**
  109814. * The EventManager is in charge of registering user interctions with the viewer.
  109815. * It is used in the TemplateManager
  109816. */
  109817. var EventManager = /** @class */ (function () {
  109818. function EventManager(_templateManager) {
  109819. var _this = this;
  109820. this._templateManager = _templateManager;
  109821. this._callbacksContainer = {};
  109822. this._templateManager.onEventTriggered.add(function (eventData) {
  109823. _this._eventTriggered(eventData);
  109824. });
  109825. }
  109826. /**
  109827. * Register a new callback to a specific template.
  109828. * The best example for the usage can be found in the DefaultViewer
  109829. *
  109830. * @param templateName the templateName to register the event to
  109831. * @param callback The callback to be executed
  109832. * @param eventType the type of event to register
  109833. * @param selector an optional selector. if not defined the parent object in the template will be selected
  109834. */
  109835. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  109836. if (!this._callbacksContainer[templateName]) {
  109837. this._callbacksContainer[templateName] = [];
  109838. }
  109839. this._callbacksContainer[templateName].push({
  109840. eventType: eventType,
  109841. callback: callback,
  109842. selector: selector
  109843. });
  109844. };
  109845. /**
  109846. * This will remove a registered event from the defined template.
  109847. * Each one of the variables apart from the template name are optional, but one must be provided.
  109848. *
  109849. * @param templateName the templateName
  109850. * @param callback the callback to remove (optional)
  109851. * @param eventType the event type to remove (optional)
  109852. * @param selector the selector from which to remove the event (optional)
  109853. */
  109854. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  109855. var callbackDefs = this._callbacksContainer[templateName] || [];
  109856. this._callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  109857. };
  109858. EventManager.prototype._eventTriggered = function (data) {
  109859. var templateName = data.template.name;
  109860. var eventType = data.event.type;
  109861. var selector = data.selector;
  109862. var callbackDefs = this._callbacksContainer[templateName] || [];
  109863. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  109864. callbackDef.callback(data);
  109865. });
  109866. };
  109867. /**
  109868. * Dispose the event manager
  109869. */
  109870. EventManager.prototype.dispose = function () {
  109871. this._callbacksContainer = {};
  109872. };
  109873. return EventManager;
  109874. }());
  109875. exports.EventManager = EventManager;
  109876. /***/ }),
  109877. /* 38 */
  109878. /***/ (function(module, exports, __webpack_require__) {
  109879. "use strict";
  109880. Object.defineProperty(exports, "__esModule", { value: true });
  109881. var mappers_1 = __webpack_require__(3);
  109882. var types_1 = __webpack_require__(39);
  109883. var configurationCompatibility_1 = __webpack_require__(50);
  109884. var deepmerge = __webpack_require__(1);
  109885. var babylonjs_1 = __webpack_require__(0);
  109886. /**
  109887. * The configuration loader will load the configuration object from any source and will use the defined mapper to
  109888. * parse the object and return a conform ViewerConfiguration.
  109889. * It is a private member of the scene.
  109890. */
  109891. var ConfigurationLoader = /** @class */ (function () {
  109892. function ConfigurationLoader(_enableCache) {
  109893. if (_enableCache === void 0) { _enableCache = false; }
  109894. this._enableCache = _enableCache;
  109895. this._configurationCache = {};
  109896. this._loadRequests = [];
  109897. }
  109898. /**
  109899. * load a configuration object that is defined in the initial configuration provided.
  109900. * The viewer configuration can extend different types of configuration objects and have an extra configuration defined.
  109901. *
  109902. * @param initConfig the initial configuration that has the definitions of further configuration to load.
  109903. * @param callback an optional callback that will be called sync, if noconfiguration needs to be loaded or configuration is payload-only
  109904. * @returns A promise that delivers the extended viewer configuration, when done.
  109905. */
  109906. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  109907. var _this = this;
  109908. if (initConfig === void 0) { initConfig = {}; }
  109909. var loadedConfig = deepmerge({}, initConfig);
  109910. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  109911. if (loadedConfig.configuration) {
  109912. var mapperType_1 = "json";
  109913. return Promise.resolve().then(function () {
  109914. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  109915. // a file to load
  109916. var url = '';
  109917. if (typeof loadedConfig.configuration === "string") {
  109918. url = loadedConfig.configuration;
  109919. }
  109920. // if configuration is an object
  109921. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  109922. url = loadedConfig.configuration.url;
  109923. var type = loadedConfig.configuration.mapper;
  109924. // empty string?
  109925. if (!type) {
  109926. // load mapper type from filename / url
  109927. type = loadedConfig.configuration.url.split('.').pop();
  109928. }
  109929. mapperType_1 = type || mapperType_1;
  109930. }
  109931. return _this._loadFile(url);
  109932. }
  109933. else {
  109934. if (typeof loadedConfig.configuration === "object") {
  109935. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  109936. return loadedConfig.configuration.payload || {};
  109937. }
  109938. return {};
  109939. }
  109940. }).then(function (data) {
  109941. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  109942. var parsed = deepmerge(mapper.map(data), loadedConfig);
  109943. var merged = deepmerge(extendedConfiguration, parsed);
  109944. configurationCompatibility_1.processConfigurationCompatibility(merged);
  109945. if (callback)
  109946. callback(merged);
  109947. return merged;
  109948. });
  109949. }
  109950. else {
  109951. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  109952. configurationCompatibility_1.processConfigurationCompatibility(loadedConfig);
  109953. if (callback)
  109954. callback(loadedConfig);
  109955. return Promise.resolve(loadedConfig);
  109956. }
  109957. };
  109958. /**
  109959. * Dispose the configuration loader. This will cancel file requests, if active.
  109960. */
  109961. ConfigurationLoader.prototype.dispose = function () {
  109962. this._loadRequests.forEach(function (request) {
  109963. request.abort();
  109964. });
  109965. this._loadRequests.length = 0;
  109966. };
  109967. ConfigurationLoader.prototype._loadFile = function (url) {
  109968. var _this = this;
  109969. var cacheReference = this._configurationCache;
  109970. if (this._enableCache && cacheReference[url]) {
  109971. return Promise.resolve(cacheReference[url]);
  109972. }
  109973. return new Promise(function (resolve, reject) {
  109974. var fileRequest = babylonjs_1.Tools.LoadFile(url, function (result) {
  109975. var idx = _this._loadRequests.indexOf(fileRequest);
  109976. if (idx !== -1)
  109977. _this._loadRequests.splice(idx, 1);
  109978. if (_this._enableCache)
  109979. cacheReference[url] = result;
  109980. resolve(result);
  109981. }, undefined, undefined, false, function (request, error) {
  109982. var idx = _this._loadRequests.indexOf(fileRequest);
  109983. if (idx !== -1)
  109984. _this._loadRequests.splice(idx, 1);
  109985. reject(error);
  109986. });
  109987. _this._loadRequests.push(fileRequest);
  109988. });
  109989. };
  109990. return ConfigurationLoader;
  109991. }());
  109992. exports.ConfigurationLoader = ConfigurationLoader;
  109993. /***/ }),
  109994. /* 39 */
  109995. /***/ (function(module, exports, __webpack_require__) {
  109996. "use strict";
  109997. Object.defineProperty(exports, "__esModule", { value: true });
  109998. var minimal_1 = __webpack_require__(40);
  109999. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  110000. var default_1 = __webpack_require__(41);
  110001. exports.defaultConfiguration = default_1.defaultConfiguration;
  110002. var extended_1 = __webpack_require__(47);
  110003. var shadowLight_1 = __webpack_require__(48);
  110004. var environmentMap_1 = __webpack_require__(49);
  110005. var deepmerge = __webpack_require__(1);
  110006. /**
  110007. * Get the configuration type you need to use as the base for your viewer.
  110008. * The types can either be a single string, or comma separated types that will extend each other. for example:
  110009. *
  110010. * "default, environmentMap" will first load the default configuration and will extend it using the environmentMap configuration.
  110011. *
  110012. * @param types a comma-separated string of the type(s) or configuration to load.
  110013. */
  110014. var getConfigurationType = function (types) {
  110015. var config = {};
  110016. var typesSeparated = types.split(",");
  110017. typesSeparated.forEach(function (type) {
  110018. switch (type.trim()) {
  110019. case 'environmentMap':
  110020. config = deepmerge(config, environmentMap_1.environmentMapConfiguration);
  110021. break;
  110022. case 'shadowDirectionalLight':
  110023. config = deepmerge(config, shadowLight_1.shadowDirectionalLightConfiguration);
  110024. break;
  110025. case 'shadowSpotLight':
  110026. config = deepmerge(config, shadowLight_1.shadowSpotlLightConfiguration);
  110027. break;
  110028. case 'extended':
  110029. config = deepmerge(config, extended_1.extendedConfiguration);
  110030. break;
  110031. case 'minimal':
  110032. config = deepmerge(config, minimal_1.minimalConfiguration);
  110033. break;
  110034. case 'none':
  110035. break;
  110036. case 'default':
  110037. default:
  110038. config = deepmerge(config, default_1.defaultConfiguration);
  110039. break;
  110040. }
  110041. if (config.extends) {
  110042. config = deepmerge(config, getConfigurationType(config.extends));
  110043. }
  110044. });
  110045. return config;
  110046. };
  110047. exports.getConfigurationType = getConfigurationType;
  110048. /***/ }),
  110049. /* 40 */
  110050. /***/ (function(module, exports, __webpack_require__) {
  110051. "use strict";
  110052. Object.defineProperty(exports, "__esModule", { value: true });
  110053. /**
  110054. * The minimal configuration needed to make the viewer work.
  110055. * Some functionalities might not work correctly (like fill-screen)
  110056. */
  110057. exports.minimalConfiguration = {
  110058. version: "0.1",
  110059. templates: {
  110060. main: {
  110061. html: __webpack_require__(13)
  110062. },
  110063. fillContainer: {
  110064. html: __webpack_require__(14),
  110065. params: {
  110066. disable: false
  110067. }
  110068. },
  110069. loadingScreen: {
  110070. html: __webpack_require__(15),
  110071. params: {
  110072. backgroundColor: "#000000",
  110073. loadingImage: __webpack_require__(16)
  110074. }
  110075. },
  110076. viewer: {
  110077. html: __webpack_require__(17),
  110078. },
  110079. overlay: {
  110080. html: __webpack_require__(18),
  110081. params: {
  110082. closeImage: __webpack_require__(19),
  110083. closeText: 'Close'
  110084. }
  110085. },
  110086. error: {
  110087. html: __webpack_require__(20)
  110088. }
  110089. },
  110090. engine: {
  110091. antialiasing: true
  110092. }
  110093. };
  110094. /***/ }),
  110095. /* 41 */
  110096. /***/ (function(module, exports, __webpack_require__) {
  110097. "use strict";
  110098. Object.defineProperty(exports, "__esModule", { value: true });
  110099. /**
  110100. * The default configuration of the viewer, including templates (canvas, overly, loading screen)
  110101. * This configuration doesn't hold specific parameters, and only defines objects that are needed for the viewer to fully work correctly.
  110102. */
  110103. exports.defaultConfiguration = {
  110104. version: "3.2.0-alpha4",
  110105. templates: {
  110106. main: {
  110107. html: __webpack_require__(13),
  110108. params: {
  110109. babylonFont: __webpack_require__(42),
  110110. noEscape: true
  110111. }
  110112. },
  110113. fillContainer: {
  110114. html: __webpack_require__(14),
  110115. params: {
  110116. disable: false
  110117. }
  110118. },
  110119. loadingScreen: {
  110120. html: __webpack_require__(15),
  110121. params: {
  110122. backgroundColor: "#000000",
  110123. loadingImage: __webpack_require__(16)
  110124. }
  110125. },
  110126. viewer: {
  110127. html: __webpack_require__(17),
  110128. params: {
  110129. enableDragAndDrop: false
  110130. }
  110131. },
  110132. navBar: {
  110133. html: __webpack_require__(43),
  110134. params: {
  110135. speedList: {
  110136. "0.5x": "0.5",
  110137. "1.0x": "1.0",
  110138. "1.5x": "1.5",
  110139. "2.0x": "2.0",
  110140. },
  110141. logoImage: __webpack_require__(44),
  110142. logoText: 'BabylonJS',
  110143. logoLink: 'https://babylonjs.com',
  110144. hideHelp: true,
  110145. disableOnFullscreen: false,
  110146. },
  110147. events: {
  110148. pointerdown: {
  110149. 'navbar-control': true,
  110150. 'help-button': true
  110151. },
  110152. input: {
  110153. 'progress-wrapper': true
  110154. },
  110155. pointerup: {
  110156. 'progress-wrapper': true
  110157. }
  110158. }
  110159. },
  110160. overlay: {
  110161. html: __webpack_require__(18),
  110162. params: {
  110163. closeImage: __webpack_require__(19),
  110164. closeText: 'Close'
  110165. }
  110166. },
  110167. help: {
  110168. html: __webpack_require__(45)
  110169. },
  110170. share: {
  110171. html: __webpack_require__(46)
  110172. },
  110173. error: {
  110174. html: __webpack_require__(20)
  110175. }
  110176. },
  110177. camera: {
  110178. behaviors: {
  110179. autoRotate: {
  110180. type: 0
  110181. },
  110182. framing: {
  110183. type: 2,
  110184. zoomOnBoundingInfo: true,
  110185. zoomStopsAnimation: false
  110186. },
  110187. bouncing: {
  110188. type: 1
  110189. }
  110190. },
  110191. wheelPrecision: 200,
  110192. },
  110193. skybox: {},
  110194. ground: {
  110195. receiveShadows: true
  110196. },
  110197. engine: {
  110198. antialiasing: true
  110199. },
  110200. scene: {}
  110201. };
  110202. /***/ }),
  110203. /* 42 */
  110204. /***/ (function(module, exports) {
  110205. module.exports = "data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAABIgAA8AAAAAH7gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABPUy8yAAABWAAAAEcAAABgSlp9rlZETVgAAAGgAAACBQAABeCBXolxY21hcAAAA6gAAABxAAAAsqyRvzljdnQgAAAEHAAAACAAAAAqCdkJr2ZwZ20AAAQ8AAAA8AAAAVn8nuaOZ2FzcAAABSwAAAAMAAAADAAIABtnbHlmAAAFOAAABlUAAAh+MHVDHWhlYWQAAAuQAAAAMgAAADb+LvI4aGhlYQAAC8QAAAAVAAAAJBABCAZobXR4AAAL3AAAACYAAAAqErQDvGxvY2EAAAwEAAAAIgAAACIJ6we4bWF4cAAADCgAAAAcAAAAIACJANFuYW1lAAAMRAAABTsAAAvzM/OUeXBvc3QAABGAAAAAEwAAACD/UQB3cHJlcAAAEZQAAACJAAAA03i98g542mNgZk9knMDAysDBOovVmIGBURpCM19kSGMS4mBl5WJkYgQDBiAQYEAA32AFBQYHBt7vwhxgPoRkAKtjgfAUGBgAoqoGywB42hXJUxQYBgAEwclf2qa2bdu2bdu2bdu2bdu2bTtlur15734WAwz4fwYZPHCIgWGoMHQYJqqD+mHDcGH4MEIYMYwURg6jhFHDaGH0MEYYM4wVxg7jhHHDeGH8MEGYMEwUJg6ThEnDZGHyMEWYMkwVpg7ThGnDdGH6MEOYMcwUZg6zhFnDbGH2MEeYM8wV5g7zhHnDfGH+sEBYMCwUFg6LhEXDYmHxsERYMiwVlg7LhGXDcmH5sEJYMawUVg6rhFXDamH1sEZYM6wV1g7rhHXDemH9sEHYMGwUNg6bhE3DZmHzsEXYMmwVtg7bhG3DdmH7sEPYMewUdg67hF3DbmH3sEfYM+wV9g77hH3DfmH/cEA4MBwUDg6HhEPDYeHwcEQ4MhwVjg7HhGPDceH4cEI4MZwUTg6nhFPDaeH0cEY4M5wVzg7nhHPDeeH8cEG4MFwULg6XhEvDZeHycEW4MlwVrg7XhGvDdeH6cEO4MdwUbg63hFvDbeH2cEe4M9wV7g73hHvDfeH+8EB4MDwUHg6PhEfDY+Hx8ER4MjwVng7PhGfDc+H58EJ4MbwUXg6vhFfDa+H18EZ4M7wV3g7vhHfDe+H98EH4MHwUPg6fhE/DZ+Hz8EX4MnwVvg7fhG/Dd+H78EP4MfwUfg6/hF/Db+H3MDj8Ef4Mf4W/wz/h3zAk/gPilQDpAAAAeNpjYGBgYmBkAAERBmYwy42BjcEISPMCRSAyhAATAwtDDpAWYxAAmsEG1KnwnO+5w/PMF0/f+33b9533u/D//2ATFZ7zPrd/ngEV5wGJ///y/5HEd4njEgvEVQX2cvoxMHD8wWIvG5jkY+AFANeUIx8AAAB42mPQYghlKGBoYFjFyMDYwOzAeIDBAYsIEAAAqhwHlXjaXY+/TsNADMZzJLSEJ0A6IZ11KkOViJ3phksk1CUlDOelgNRKpO+AlIXFA8/ibhnzYgjMEf4utr/P+ny/c6f5yXx2nKVHKilWnDfhoNQLDurtmf35IU/vNmVhTNV5VvdlwWoJomtOF/VNsGjI0PWWTG0eH7acLWKXxY7w0nDShk7qbQB2qL/HHeJVPJLFI4QS30/xfYxL+rUsVobTiyasA/des/OoAUzFYxN49BoQf8ikP3VnE+NsOWXbwE5zgkSfygL3RJqE+0uPf/Wgkv+G+23Iv6tB9U3c9Bb0h2HBgrChl2fbUAkaYPkOhPxkxgABAAIACAAK//8AD3jaVVRvbFvVFT/nvD/XThMnL8+OUyd1eH7YThPFiWw/G8jiuCn12q780QRE2EtgbC2FrpuqtdUKrLtCmzKlIFCL0LQPbEsUBBLtBzqxTpO2TOMDElCGkPZhlcY0CbQhFYEmdU3we+zc5xRB4nffuefP7/zOfedcIHgRQP+pcRI0EAAly7GyjuW8qP2j/Rq95u83Tm4uP6ffCQg2fiiumhNgAGAyilUU55ptu203tXPmBEva1Wb7KPtppAnfbCm/KOWjKFbbC+2FpuZrPmnaSnuxqQVtAiDOyJ7ChwhYjOlYroV5dNBJOFbJwiQCSekvNGklaOktXPOlpNWmJn3J8mKTVgkkyaBFK00OBwlS8D/08EZBbcE4npBysxNurAUtEcZvtsJQY00CMRcpgCMp5IyWzaThM5Dab9oP6NBm48Y1WqZl5kwSwWBF57SwZLkqF/OUmgLZBDN8lF0CCD8CXF0CBtk3z44iHyXFy1FR6uXw8azK1SbO4MyGZsCm1FuUlQFn1QGzwRXSVvwWra2wR/CXwJUR8K8EWZQEgcQsqFzIypDRTpgED6Zhl2KWcO1imhLxmL4DXa9c071ygdxMjBJuuUZZxSLk7nhchePtJHVcGhdSnzs+X8rdOndrToZrutwYHW2U07I4f6L9pMrL+SRnl0wT5QY/gfoQUq+X5o/Pfe3+vdPTu8fq9VCYG1ehCkKhrnMYA3CEbKsg3oQVgKpAwj5YgDW4CH+Gd7iCeIxcJzOJIjmQsNQmU6AZzAuTtQXiimgaqwX0LJZKjlo69ZJIKglVqfE0a2ukSsdixSvnxjHDLWbFB1iNuRpOY3EgETfHMREXqJDNBNucaqVUHEGVlx0rnpXPeeVZDJUYV268r5Sc4oD1lZ3YAusoIqDq/hxS9rlD79lfHOM5OxXIG6fywd1ePe4WhghGGwuet9AYTU3uGn36oLIHMFRw48o6WLh5oN+ZQjeVy6Vkyg7O+ldyqeyQHtGHsuuh0v4c7BTnYhkPXrBTKXvdzqVSuas2C7y78NlajvOG9nDd8uW13kHlRa+rvPbZg+99haM8+wX7u5IP3oZS8VJcFeexO+pTPU+xnX6hqCqT7YxvHy5mEz4oBjYeVXkn935z76Tar6cUVyWdD7ndIP1xh7R9nkJC/AQfbgl/D1d+ALq4WzpzZUMexrnjS1Dlnp+F3XCAu2arB9ytFrG3vr671Q225W4nvhUSjmd4TgIFVg3koUxiVnQGFLX1hdXHGo3HVhduvFXrqtaeOzFf5CF4km8lbmST23jzb63g06ZxZ/BpC/s2X8XeVvCJ+btmZ6JN+DKIevvA4XNfhjPUGMvr/AQ88FL9kcFYzWbwSQt7GbKPMxw79nv/CmXVJcCXNd8sxPPyb+jlM8hAgasWFlpci8WXlym8qBE3BRo21lBNgijn3AwrRBUrHOxLqtzkP6rVtfruGV/6d9ExOuY/o9fTw34pWFqkt3fsHR3bVxmRO0diqS7/QGaJfpugn0g6hbva7wQfSDyg9+KvgweDv3Zl3g7+hC8Fb+AteEv7ofx+hljEU/TWjuG0t29sJB/l+KUMXUzwR4P7YEK8Ii5Dkr/bLliE4/Bz+BWzj+nUS91o5Chfw6qVtWtoFJDlWUxjkn8miRiKKNdTjWEvdodmLc9LGpVLAScx54XbJIOkcQQTA/2s1liXy4cmjmUrwwz0Y0cwBas7lhpqlZurHRdkE//YwFnEK4iiZ9BNaf3BNf+/wf+6EpGZUzN0aX/5kfbF25d2n/jPye75l+8zIkbPjp4z7SeCC7ob2x6LdEf6gw3/WrDBM/qRaSDNPB58pJn6+D1jBvUMxvYs3b5tIFr70cy2SF/0jud/MPXAFOlkZWP10/XZx2e//sye7iTeveepxvQPp0WXLjTOWnmkoot/XcKjlzRDI5PordKhkmZqD7972L9Ye8JM6b3Fh84H1/9oi+++fuh9/MP7VqbPP3yVTvUNPV/8Tmm4mNIK354iUzsTfHymcM+o/0982ogaE/MT4si7R1nC0Uj23tz+Z/GNxnKj+v2qYPA3H9733DdewOoL3pFKNHY5OHy5+SqernyvQqap/fj66a7ByMS3JnqHEz8LNnHZO1juu8kiYoaVRyvdyW1I2Oc2XEQkouCXse09rLntSPX0ZAv+D0t//44AAAB42mNgZGBgYDpluyBuyf14fpuvDNwcDCCw/+/BBhB9XVCyFkRzMIDFORmYQBQAWhsJ1AAAeNpjYGRg4GAAATjJyIAKWAECzQAgAAAAeNpj1WJYxgAETIYMYMDBwCDMwAyEDUwMTA0MDRBRIB0GAEEkA4QAAAAAABQAFAAUABQAKAA9AGQAgQCXAKwA4AFBAlgC2QM1BD8AAHjaY2BkYGAQYLjAwMUAAoxgEsROAbMYABpgAVt42p1Uz2/cRBQe106T0CQqlCJQVRhVqLTV4m3CIUorhNJWooWkSElUqeI0a8/aQ70ea2bcxeKM4MIJISRuiFMlDiAOCCTEAf4RjvwXvPc83nXabQXsyjPfvHnvez9txtjmiQMWMPoFK7i0kJ2BU4tPsOXgnMdhTx718BJbCy54fJI9H8QeL7Od4B2PV9jZ4GOPT7ErwRcerwd/Bj97vEHykAVRCH7Xwk8ILwE+HX5G+CTJvya8TPLvCK8Q/onwKjCl4R8eB+xi9IbHJ9hGtO9x2JNHPbzEXo4+9PgkuxBZj5eZib7yeIVdWVr2+BQ7Wtr0eD38fOlTjzdm8ud6uZzCOFfXCa/15BuIV88TPo1xrl4mfAbwC6vbhF/s6Z8lnjuEX+rJXyHb+4TPkU5G+HxP57Uefp30p4SvEG7jf5Pwl4hXevGv9Hyt9eRrPpdHfOvq5jbfV4nRVo8dv6lNpY1wSpcx3y0KfqCy3Fl+IK00D2Uar9+WIyOn/INKlkdNJfmeaHTteKEzlfBEV41BC47MV9/iF3HbHvADUVQ5vy3KRCcPQPqezkt+u04t+jnKleVFn2esDb+hRoVKRMG9R9DR4JRbXZtEcgx3KozkdZlKw10u+f6dI76nEllaeZ1bKbmcjGSaypQXrZSn0iZGVZge+UilE6qw8Q0xagqQ7d/a2+K71kpnD2RWF8Lck8ai9la8veO1UKnVOZSZlhiY4M6IVE6EecD1uA1mVtPM6LpCcaInlSiVtPHCgufOVdeGw+l0Gk+6+xhshq6pdGZElTfDsS6dHc7NbV1VhYIM8SLm93XNJ6LhNeTqsKoo5k7zxEjh5ICnylZQ6QEXZcoro+A2ARUJu7C8kmainAO6UUNJdHVzcAHlNx0Yo4fBk6lWRqd14gYcpwVsB2jTOVAln+YqyXuRTcGpKpOihibNo9dl0fBL6nLbv546MDwr2rbdqsy4kdYZlWBV5w7QfMZ1nSpwSYEXJyfYAqPAa6qnZaFFerx6oi0VjBmko8EVrLWrYFxTiWmiTi6L6nhF4QUqG6+ODQFCqE+uRgpijtldpplhEyZYAWjEmmCdSfYRK9nf8MzvDpmDvWQprAY+lN+EP4a/hb/D80v4a/g9e8Q422JX2SbbBrTPFEtATzMLzxhsObtJbBWtAiQKUMliuNkF/gL2A5BlLIc7SycJuwTth7CmoHkD7CBCirQkL7fYHnhFBku6aIl2GatBCyO9RwzWe8MYY4hw5zGujqnPc0g8GlYO1hiRgMdR9ClIJ8T/AGSYId7kpLso94zONWTfaSewT+CMNVWUafwfqoY1ciC9xobwn9I/Br7H7WPvZwi4IZaMeCpgaEA6JjbMdrjQu6WYK6iSoh7wmQX27T7lxKkSDew11a6tRFuxThtlmrI2oIF5SDaAc0p6FfWqIUk7YxxkBu5a28SzSH8WxF1RZzFnR3doNaI4uk4UlBFadXG1Fpa6YJ6QjGc5DP5VVys6p2CTwHlA9WrntfU7mPl5PANFszilOiWwLq7Z1GeK2glkU9PcpQtrjzYFoUugfxl2nNCRr8si9jaG/1vbOXtKTBnIDM2xo84ls1ldlEHn/cm4rvdmADNpc3Hkr3sLkL/NNQXJlDLX9FY+a/bEsamS1Bft1zarFtf0ZtVkidF23ex4ULOgN/npM9p+1UrfmTl794YoX2WcH4x3RJVuezv/Igua4O78F5z6X2t57JtMX+Vj9+A9ejXajN6P3o3ehnXnGFMJ9ndB7yHVrWyjDH4Ivg0ZdXMXNA3Ei9mIfwCJoYWxAHjaY2BmAIP/fgzlDFgAACkqAcgAeNrbwKDNsImRk0mbcRMXiNzO1ZobaqvKwKG9nTs12EFPBsTiifCw0JAEsXidzbXlhUEsPh0VGREeEItfTkKYjwPEEuDj4WRnAbEEwQDEEtowoSDAAMhi2M4IN5oJbjQz3GgWuNGscKPZ5CShRrPDjeaAG80JN3qTMCO79gYGBdfaTAkXAMQBKBoAAAA="
  110206. /***/ }),
  110207. /* 43 */
  110208. /***/ (function(module, exports) {
  110209. module.exports = "<style>nav-bar{position:absolute;height:48px;width:100%;bottom:10px;display:flex;justify-content:center}nav-bar .nav-container{display:flex;flex-direction:row;margin:0 10px;height:100%;width:100%;justify-content:center}nav-bar .animation-control{background-color:rgba(91,93,107,.75);display:flex;flex-direction:row;height:100%;width:100%;max-width:1280px;justify-content:center}nav-bar .flex-container{display:flex;flex-direction:row;justify-content:center;height:100%;width:100%}nav-bar button{background:0 0;border:none;color:#fff;margin:0;padding:0;height:100%;min-width:48px;cursor:pointer}nav-bar button:active,nav-bar button:focus,nav-bar button:hover{background:0 0;border:none;outline:0}nav-bar button:hover{background-color:rgba(22,24,26,.2)}nav-bar .control-text{font-family:\"Segoe UI\";font-size:12px;font-weight:400;pointer-events:none}nav-bar .icon,nav-bar img{pointer-events:none}.logo-button{display:flex;align-items:center;flex-direction:row;justify-content:center;background-color:rgba(91,93,107,.75);height:48px;min-width:48px;margin-right:4px}.logo-button img{height:20px;width:20px}.types{display:flex;flex-direction:column;width:48px}.speed .flex-container,.types .flex-container{align-items:center}.menu-options{position:absolute;bottom:48px;width:48px;background-color:rgba(22,24,26,.9)}.animation-label,.help,.logo-button,.speed,.types-icon{display:none}.types-icon:after{font-size:16px;content:\"\\F6BE\"}.up-icon:after{line-height:16px;font-size:12px;content:\"\\E70E\"}.play-icon:after{font-size:16px;content:\"\\E768\"}.pause-icon:after{font-size:16px;content:\"\\E769\"}.fullscreen-icon:after{font-size:16px;content:\"\\E740\"}.help-icon:after{font-size:16px;content:\"\\EF4E\"}.progress-control{display:flex;flex:1;position:relative;overflow:hidden;cursor:pointer;align-items:center}.animation-number{margin:0 6px}.speed-text{margin-right:6px}.progress-circle{width:12px;height:12px;border:2px solid #fff;border-radius:50%;background-color:#5b5d6b;cursor:pointer;position:relative;bottom:10px;pointer-events:none}.default-control{display:flex;flex-direction:row;height:100%;background-color:rgba(91,93,107,.75)}.menu-options button{width:100%;height:48px;color:#8e939b}.menu-options button{width:100%;height:48px;color:#8e939b}.menu-options button:hover{background-color:transparent;color:#fff}.menu-options .animation-number{margin:0 18px 0 6px}.menu-options .speed-text{margin-right:18px}.menu-options{visibility:hidden}.open .menu-options{visibility:visible}.types .menu-options{width:144px}.types .menu-options button{padding:0 8px;justify-content:left}.types .menu-options button>*{display:flex;margin:8px}.types .menu-options button span.animation-number{display:none}.fullscreen{display:none}@media screen and (min-width:540px){.help,.speed,.types-icon{display:inline-block}.logo-button{display:flex}.types{width:84px}.progress-bar-container{margin:0 12px}.speed{width:64px}.speed .menu-options{width:64px}.fullscreen{display:block}}@media screen and (min-width:1024px){.animation-label{display:block;margin-left:6px;text-overflow:ellipsis;overflow:hidden}nav-bar button.animation-buttons{padding:0 8px;justify-content:left}.icon.up-icon{margin-left:8px}nav-bar button.animation-buttons>div{display:flex;pointer-events:none}.animation-number{display:none}.progress-bar-container{margin:0 12px}.types{width:144px}}.progress-wrapper{-webkit-appearance:none;cursor:pointer;width:100%;outline:0;margin:0 12px;height:30px;background-color:transparent}.progress-wrapper::-webkit-slider-thumb{-webkit-appearance:none;width:20px;height:20px;border:2px solid #fff;border-radius:50%;background:rgba(91,93,107,1);margin-top:-10px}.progress-wrapper::-webkit-slider-runnable-track{height:2px;-webkit-appearance:none;background-color:#fff}.progress-wrapper::-moz-range-progress{background-color:#fff;height:2px}.progress-wrapper::-moz-range-thumb{width:20px;height:20px;border:2px solid #fff;border-radius:50%;background:rgba(91,93,107,1)}.progress-wrapper::-moz-range-track{background:#fff;height:2px}.progress-wrapper::-ms-track{height:2px;background:0 0;border-color:transparent;border-width:10px 0;color:transparent}.progress-wrapper::-ms-fill-lower{background:#fff;border-radius:5px}.progress-wrapper::-ms-fill-upper{background:#fff;border-radius:5px}.progress-wrapper::-ms-thumb{width:16px;height:16px;border:2px solid #fff;border-radius:50%;background:rgba(91,93,107,1);margin-top:0}span{display:inline-block}</style> {{#if (or (not animations) hideAnimations)}} {{#if hideLogo}} <style>nav-bar .nav-container{justify-content:flex-end}</style> {{else}} <style>nav-bar .nav-container{justify-content:space-between}</style> {{/if}} {{/if}} {{#if disableOnFullscreen}} <style>viewer:fullscreen nav-bar{display:none}viewer:-moz-full-screen nav-bar{display:none}viewer:-webkit-full-screen nav-bar{display:none}</style> {{/if}} <div class=nav-container id=navbar-control> {{#unless hideLogo}} <div class=logo-button title={{logoText}}> {{#if logoLink}} <a href={{logoLink}} target=_blank> <img src={{logoImage}}> </a> {{else}} <img src={{logoImage}}> {{/if}} </div> {{/unless}}{{#unless (or (not animations) hideAnimations)}} <div class=animation-control> <div class=types> <button class=\"flex-container animation-buttons\" id=types-button> <span class=\"icon types-icon\"></span> <span class=\"control-text animation-label\">{{selectedAnimationName}}</span> <span class=\"control-text animation-number\">{{selectedAnimation}}</span> {{#if (gt (count animations) 1)}} <span class=\"icon up-icon\"></span> {{/if}} </button> <div class=menu-options> {{#each animations}} {{#unless (eq ../selectedAnimation (add @index 1))}} <button class=\"flex-container animation-buttons\" id=label-option-button data-value={{this}}> <span class=\"icon types-icon\"></span> <span class=\"control-text animation-label\">{{this}}</span> <span class=\"control-text animation-number\">{{add @index 1}}</span> </button> {{/unless}} {{/each}} </div> </div> <div class=progress-control id=progress-control> <button class=play-pause id=play-pause-button> {{#if paused}} <span class=\"icon play-icon\"></span> {{else}} <span class=\"icon pause-icon\"></span> {{/if}} </button> <input class=progress-wrapper id=progress-wrapper type=range min=0 max=100 step=0.01> </div> <div class=speed> <button class=flex-container id=speed-button> <span class=\"control-text speed-text\">{{selectedSpeed}}</span> <span class=\"icon up-icon\"></span> </button> <div class=menu-options> {{#eachInMap speedList}} {{#unless (eq ../selectedSpeed id)}} <button class=flex-container id=speed-option-button data-value={{value}}> <span class=\"control-text speed-text\">{{id}}</span> </button> {{/unless}} {{/eachInMap}} </div> </div> </div> {{/unless}} <div class=default-control> {{#unless hideHelp}} <button class=help id=help-button title=Help> <span class=\"icon help-icon\"></span> </button> {{/unless}} {{#unless hideFullScreen}} <button class=fullscreen id=fullscreen-button title=Fullscreen> <span class=\"icon fullscreen-icon\"></span> </button> {{/unless}} </div> </div>";
  110210. /***/ }),
  110211. /* 44 */
  110212. /***/ (function(module, exports) {
  110213. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAB7MAAAgHCAYAAABZmyd0AAAACXBIWXMAAC4jAAAuIwF4pT92AAAgAElEQVR42uzd7XEb6Zm24Wtc+5/IgO0IyDcCtiMQNwLBEYgTgaAIhhOBpQhMRSAwghEjWCoCixHw/fE0DIKiKAIE+vM4qlDi1I531/fYRDdOPHf/dn9/HwAAAAAmb5bkNMnSKAAAgD74HyMAAAAAmJwqJVyfJqmbP4+a/9m3JIskH40JAADo0m9OZgMAAACM2ukTr6MX/OtEbQAAoFNiNgAAAMB41FkH6yrJ2R7+d4raAABAJ8RsAAAAgOFZPd+6znpl+MmB/2+K2gAAQKvEbAAAAIB+q/LjmvDjDv//EbUBAIBWiNkAAAAA/bFaD746df3S51t3QdQGAAAOSswGAAAA6Mbj09ZnA/33IWoDAAAHIWYDAAAAHF6dzXB9MsJ/j6I2AACwV2I2AAAAwP7MsrkivOvnW3dB1AYAAPZCzAYAAADYTZV1sK6bvz42lv8StQEAgFcRswEAAAB+bRWtq6xPXR8Zy4uI2gAAwE7EbAAAAIBNddbh+jTJmZHshagNAABsRcwGAAAApmr1fOuHrxNjOThRGwAAeBExGwAAAJiCVbiusw7Xnm/dLVEbAAB4lpgNAAAAjE2VdbCu4/nWfSdqAwAATxKzAQAAgCF7vCbc862HS9QGAAA2iNkAAADAUNRZR+sqwvVYidoAAEASMRsAAADon4fPt66an0+MZXJEbQAAmDgxGwAAAOhSlR9XhR8bCw+I2gAAMFFiNgAAANCW1Xrw1anr0yRHxsILidoAADAxYjYAAABwCHU2T117vjX7ImoDAMBEiNkAAADAa9XZXBPu+da0QdQGAICRE7MBAACAl5plc0W451vTB6I2AACMlJgNAAAAPKXKOljXzV8L1/SZqA0AACMjZgMAAACnT7yOjIWBErUBAGAkxGwAAACYljolVlfNn2dGwkiJ2gAAMHBiNgAAAIzT6vnWD18nxsIEidoAADBQYjYAAAAMX9W86qzDtedbwyZRGwAABkbMBgAAgGGpsg7WdTzfGrYlagMAwECI2QAAANBfj9eEe7417I+oDQAAPSdmAwAAQD/UWUfrKsI1tEXUBgCAnhKzAQAAoF2zbK4Ir5KcGAt0TtQGAICeEbMBAADgcKr8uCr82Fig10RtAADoCTEbAAAA9mN1yvrhqesjY4HBErUBAKBjYjYAAABsr87mqWvPt4bxErUBAKAjYjYAAAA8r87mmnDPt4ZpErUBAKBlYjYAAAAUs2yuCPd8a+ApojYAALREzAYAAGCKqqyDdd38tXANbEPUBgCAAxOzAQAAGLvTJ15HxgLsiagNAAAHImYDAAAwJnVKrK6aP8+MBGiJqA0AAHsmZgMAADBED59vXTU/nxgL0AOiNgAA7ImYDQAAQN9VzavOek2451sDfSdqAwDAK4nZAAAA9EmVdbCu4/nWwPCJ2gAAsCMxGwAAgK6cPnp5vjUwZqI2AABsScwGAACgDXU2w7XnWwNTJWoDAMALidkAAADs0yybK8KrCNcATxG1AQDgF8RsAAAAdlXlx1Xhx8YCsBVRGwAAfkLMBgAA4CVWsbrK+tT1kbEA7I2oDQAAj4jZAAAAPFZn89T1mZEAtEbUBgCAhpgNAAAwbXU214R7vjVAP4jaAABMnpgNAAAwDbOUWF3H860BhkTUBgBgssRsAACA8amyDtZ1PN8aYAxEbQAAJkfMBgAAGLbTJ17CNcB4idoAAEyGmA0AADAcdUqsrpo/z4wEYLJEbQAARk/MBgAA6J+Hz7eump9PjAWAJ4jaAACMlpgNAADQrap51VmvCT82FgC2JGoDADA6YjYAAEB7Hq4Ir+P51gDsn6gNAMBoiNkAAACHcfro5fnWALRJ1AYAYPDEbAAAgNersxmuPd8agL4QtQEAGCwxGwAA4OVm2VwRXkW4BmAYRG0AAAZHzAYAAHhalfVJ67r562NjAWDgRG0AAAZDzAYAAFhH6yrrU9dHxgLAiInaAAD0npgNAABMTZ3NU9dnRgLAhInaAAD0lpgNAACM1er51g9fnm8NAE8TtQEA6B0xGwAAGINVuK6zDteebw0A2xO1AQDoDTEbAAAYmirrYF3H860B4BBEbQAAOidmAwAAfXb6xEu4BoD2iNoAAHRGzAYAAPqizjpYV0nOjAQAekPUBgCgdWI2AADQtofPt66an0+MBQAGQdQGAKA1YjYAAHBIVfOqsz51fWwsADB4ojYAAAcnZgMAAPuyWg++OnXt+dYAMH6iNgAAByNmAwAAuzh99PJ8awCYNlEbAIC9E7MBAIBfqbMZrj3fGgD4GVEbAIC9EbMBAICVWTZXhFcRrgGA3YjaAAC8mpgNAADTVGV90rpu/vrYWACAPRO1AQDYmZgNAADjt4rWVdanro+MBQBokagNAMDWxGwAABiXOutwfZrkzEgAgB4RtQEAeDExGwAAhmn1fOuHL8+3BgCGQtQGAOCXxGwAAOi/Vbiusw7Xnm8NAIyBqA0AwE+J2QAA0C9V1sG6judbAwDTIGoDAPADMRsAALrzeE2451sDAFMnagMA8F9iNgAAtKPOOlpXEa4BAJ4jagMAIGYDAMCePXy+ddX8fGIsAAA7EbUBACZMzAYAgN1V+XFV+LGxAADsnagNADBBYjYAALzMaj346tT1aZIjYwEAaJWoDQAwIWI2AAD86PFpa8+3BgDoF1EbAGACxGwAAKauzma49nxrAIDhELUBAEZMzAYAYCpm2VwR7vnWAADjIWoDAIyQmA0AwBhVWQfruvlr4RoAYPxEbQCAERGzAQAYulW0rrI+dX1kLAAAkyZqAwCMgJgNAMCQ1FmH69MkZ0YCAMAzRG0AgAETswEA6KPV860fvk6MBQCAHYnaAAADJGYDANC1Vbiusw7Xnm8NAMAhiNoAAAMiZgMA0KYq62Bdx/OtAQDohqgNADAAYjYAAIfyeE2451sDANA3ojYAQI+J2QAA7EOddbSuIlwDADAsojYAQA+J2QAAbOPx862rJCfGAgDASIjaAAA9ImYDAPAzVX5cFX5sLAAATICoDQDQA2I2AADJ+pT1w1PXR8YCAMDEidoAAB0SswEApqfO5qlrz7cGAIDnidoAAB0QswEAxq3O5ppwz7cGAIDdidoAAC0SswEAxmGWzRXhnm8NAACHI2oDALRAzAYAGJ4q62BdN38tXAMAQPtEbQCAAxKzAQD67fSJ15GxAABAr4jaAAAHIGYDAPRHnRKrq+bPMyMBAIBBEbUBAPZIzAYAaN/q+dYPXyfGAgAAoyFqAwDsgZgNAHBYVfOqsw7Xnm8NAADTIGoDALyCmA0AsD9V1sG6judbAwAAhagNALADMRsAYDeP14R7vjUAAPArojYAwBbEbACAX6uzjtZVhGsAAOB1RG0AgBcQswEA1mbZXBFeJTkxFgAA4EBEbQCAZ4jZAMBUVflxVfixsQAAAB0QtQEAniBmAwBT8HBFeN38fGQsAABAz4jaAAAPiNkAwNjU2Tx17fnWAADA0IjaAAARswGAYauzuSbc860BAIAxEbUBgEkTswGAIZilxOo6nm8NAABMj6gNAEySmA0A9E2VdbCu4/nWAAAAK6I2ADApYjYA0KXTJ17CNQAAwPNEbQBgEsRsAKAtdUqsrpo/z4wEAADgVURtAGDUxGwAYN8ePt+6an4+MRYAAICDEbUBgFESswGA16iaV531mvBjYwEAAOiEqA0AjIqYDQC8VJV1sK7j+dYAAAB9JWoDAKMgZgMATzl99PJ8awAAgOERtQGAQROzAYA6m+Ha860BAADGRdQGAAZJzAaA6Zhlc0V4FeEaAABgSkRtAGBQxGwAGKcqP64KPzYWAAAAImoDAAMhZgPA8K1idZX1qesjYwEAAOAXRG0AoNfEbAAYljqbp67PjAQAAIBXErUBgF4SswGgv+psrgn3fGsAAAAOSdQGAHpFzAaA7s1SYnUdz7cGAACge6I2ANALYjYAtKvKOljX8XxrAAAA+kvUBgA6JWYDwOGcPvESrgEAABgaURsA6ISYDQD7UWcdrKskZ0YCAADAyIjaAECrxGwA2M7D51tXzc8nxgIAAMCEiNoAQCvEbAD4uap51Vmfuj42FgAAAEgiagMAByZmA0CxWg++OnXt+dYAAADwMqI2AHAQYjYAU3T66OX51gAAAPB6ojYAsFdiNgBjVyU5zzpce741AAAAHJaoDQDshZgNwNhVSa4iYgMAAEDbRG0A4FX+ZgQAjNxtyonsP40CAAAAWnWc5F/NvfncOACAbTmZDcCUnKd8G/zIKAAAAKB1TmoDAFtxMhuAKblKOaV9bRQAAADQOie1AYCtiNkATM1tkjrJB6MAAABG6M4IGABRGwB4ETEbgKlaJPlHfNADAAAM23XKl3X/N8nfk8yaex0bqRgCURsAeJZnZgMwdbOU9eNnRgEAAPTcTZKvSZbNn19/8ffXKV/kdb/DUHimNgCwQcwGgOIiyR/GAAAA9MS3rIP1snntap4SCI+NlQH9538RURsAJk/MBoC105RT2j7gAQAA2nadzRPXtwf4vzGPqM2wiNoAMHFiNgBsmjU3yW+MAgAAOJBt14Xv20VKIDzyj4KBELUBYKLEbAB42jzJZXy4AwAAvM4+14Xv0ywlal+472Fg/31aRNQGgMkQswHg506bG+QTowAAAF6ojXXh+yRqM0SiNgBMhJgNAM+bpZzQfmsUAADAI12vC9+nKiUOuvdhSERtABg5MRsAXua8uTl2UgEAAKapr+vC962KqM0w//u5iKgNAKMjZgPAy1VJrmLtOAAAjN1dfjxxfTuxGZymbKk68x8HBkTUBoCREbMBYHuXSd4ZAwAAjMZNNsP1VyP5rzolDoraDImoDQAjIWYDwG6sHQcAgGFarQtfPviTX6tTvthrUxVD++/7IqI2AAyWmA0Au5ulrB13QgEAAPrp8brwZZLvxvIq85Q4eGwUDIioDQADJWYDwOstkrw3BgAA6Jx14e2ZR9RmeERtABgYMRsA9qNOOaVt7TgAALTDuvDuzZJcNC/3Qgzt98ciojYA9J6YDQD7M2tuhN8YBQAA7JV14f2/FxK1GSJRGwB6TswGgP27SPKHMQAAwM6sCx+mWUoYfGcUDIyoDQA9JWYDwGGcpqwd9/w4AAB4nnXh41OlhMG3RsEAfx8tImoDQG+I2QBwONaOAwDAJuvCp6VKcumeiAEStQGgJ8RsADi8ecoHOJ4dBwDA1FgXTpLUKWHwzCgYGFEbADomZgNAO06bm98TowAAYKSsC+dX6ojaDPf32yKiNgC0TswGgPbMUk5oe24cAABDZ104r3He3BsdGwUDI2oDQMvEbABo33lz42vtOAAAQ2FdOIcwTwmDojZDI2oDQEvEbADoRpXkKtaOAwDQP9aF07aLlDDoC78M8fflIqI2AByMmA0A3bpM8s4YAADoiHXh9MUsJWpfRNRmeERtADgQMRsAulennNL2gQ0AAIdmXTh9J2ozZKI2AOyZmA0A/TBLCdpnRgEAwJ5YF86QVSlR8K1RMNDfv4uI2gDwamI2APTLIsl7YwAAYEvWhTNWVURthkvUBoBXErMBoH/q5kb32CgAAPiJ66zXhC+T3BoJI3ea5DK2WTFMojYA7EjMBoB+mjU3uW+MAgBg8r5l8znXSyNhwuqUKChqM9Tf54uI2gDwYmI2APTbRZI/jAEAYDIergtfNj9bFw4/qlNOap8YBQMkagPAC4nZANB/p0muYu04AMAYWRcOrzNPiYLulxgiURsAfkHMBoBhmKWcOnhrFAAAg2VdOBzOPKI2w35/WETUBoAfiNkAMCzzlKh9ZBQAAL1mXTi0b5byqKYL90wMlKgNAI+I2QAwPKfNja1nwwEA9Id14dAfojZDJ2oDQEPMBoBhmjU3tu+MAgCgddaFg/smaOv9ZhFRG4AJE7MBYNjOm5tapw0AAA7DunAYviolCL41CgZK1AZgssRsABi+KslVrB0HANgH68Jh3PdOi4jaDJeoDcDkiNkAMB6XsT4PAGAb1oXDNNUpQfDMKBjw+9ciojYAEyBmQzdmSU6bV/Xg56Mkn5PMY20dsJs65ZS2teMAAJusCweeun9aRNRmuERtAEZPzIbDei5a/+pC9DzlwxWAXX73XMUHMgDAtFkXDrzUecqmq2OjYKBEbQBGS8yG/dg1Wv/K783NFMAuFkneGwMAMAHWhQP7MG/uo0Rthvx+uIioDcCIiNmwvTr7j9bPuU75hrD1d8AuTlNOafswBgAYC+vCgUObpxwu8PgmhkrUBmA0xGz4uTolWFcPfu4qBt2lBO2lfyzADmbNDewbowAABsi6cKCr+6iL5iVqM1SiNgCDJ2ZDv6L1r/zZ3EQB7OIiyR/GAAD0mHXhQN+I2ozl/XURURuAARKzmZI6w4nWz7lJOaV96x8psIPT5ub1xCgAgI5ZFw4MSZUSA98aBQMmagMwOGI2Y1RnHNH6OXcp3wh24QnsYpby/DcfwgAAbbIuHBiDKqI2wydqAzAYYjZDdtq8qow3Wv/Kp5So7fQCsIt5StS2Kg8A2LebbIbrr0YCjEyVEgLPjIIBE7UB6D0xmyFYBeuH8dp63LWblCDlwyFg19+xH/1eBQBe4S7rYL360xdugamoU2KgqM2QidoA9JaYTZ+I1q/ze8oJS4BdXCZ5ZwwAwAus1oUvmz9vjQQgdXNf5bMshkzUBqB3xGy6IFofzueUU9pOQQC7OG9uWK0dBwBWrAsH2M48JQYeGwUDJmoD0BtiNockWnfjLiVILY0C2EGV5MrvawCY7L3EMtaFA+zDPKI2wydqA9A5MZt9qLIO1qJ1f3xoLjYBdrFI8t4YAGDUrAsHaOfe6iI2YDFsojYAnRGz2UbVvOoHP58ZS69dp3wT+NYogB3UKae0fegCAMNnXThAd2YpQVvUZuhEbQBaJ2bzlCqi9ZjcpQTtK6MAdjBrfn94HwCAYd0DLGNdOEAf768WSd4ZBQMnagPQGjF72qqI1lPyZ3OR6UMsYBeLWDsOAH1lXTjAsFTNPdZbo2DgRG0ADk7Mns4FchXRmrJacB4rBYHdnKac0j42CgDo9JreunCAcagiajMOojYAByNmj+8CuIpozfPuUp7R5OIS2MWs+f3xxigAoJVr92WsCwcYuzolBPocj6ETtQHYOzF7mGYpp+NOU4L16ucjo2ELn1NOafswDNjFRZI/jAEA9sq6cIBpqyNqMw6iNgB7I2b3m2hNGxeW57GaENjNaXNjemIUALA168IB+JnzJJfxiCeGT9QG4NXE7H4Qrenah+bCEmCX97DLeMYbADzHunAAdjFP+bxG1GboRG0AdiZmt0u0ps+uU77560M1YBfzlKjtPQ0ArAsHwP0WPEXUBmBrYvZhiNYM1V1K0F4aBbCDKslVrB0HYFqsCwegDbMkF83LZ4wMnagNwIuJ2a9Xp3x4Xz342eofhu7P5uYIYBeXSd4ZAwAjZF04AF0TtRkTURuAXxKzX66OaM203KSc0r41CmAH583NqA9XABgy68IB6KsqJQK+NQpGQNQG4KfE7B/VEa1h5S7lm74uJIFdVM3vjzOjAGAArAsHYKj3XYuI2oyDqA3AD6Ycs+uI1vBSn1KithWKwC4WSd4bAwA98i2b4XppJAAMXBVfJmZc12qLiNoAZBoxu45oDfu6iDyPEyrA7u/HV7F2HIBuXGd92tq6cADGfu+1iKjNOIjaAIwqZp+mhOrTBz+f+EcMe/d7kktjAHYwSwnaPlQB4JBW68KXWcdrAJiaOuXzG5+PMgaiNsCEDTFmi9bQvc9J5rF2HNjNRZI/jAGAPbAuHACeN0+JgDZVMpZrv0VEbYBJ6XPMFq2h3+5S1o4vjQLY8X3+Kj5QAWA71oUDwG7mEbUZD1EbYEL6ELNFaxi2D83FI8C2Zs2N5xujAOAJ1oUDwP4tUrZlHRkFIyBqA0xAmzFbtIbxukk5pX1rFMAOLpqbTx+mAEyXdeEA0J5Zcx8majOma8lFRG2AUTpEzK6aV511vBatYfzuUlZWXRkFsIPT5qbTNQPANFgXDgDdW0Xt90bBSIjaACP0mphdZTNaV0nOjBQm78/movG7UQBbmiW5TPLWKABGxbpwAOi3KuWzHPdijIWoDTAiL4nZVURrYDs3Kae0fVAJ7GKeErWtuwMYHuvCAWC4qojajO/adBFRG2DQHsbsKqI1sD93zcXipVEAO6hSHltg7ThAv1kXDgDjU6d8puOzYcZC1AYYsN/u7+/nSf5lFMCBfE45ZWntOLCLyyTvjAGgF6wLB4BpqSNqMy6iNsAA/XZ/f79I8t4ogANfKJ7HB57Abs6bG01rxwHavX6zLhwASErU/pjk2CgY0bXuIqI2wCD8dn9/Xyf5YhRACz40F4oA26qam0wnAgAOw7pwAOBX5imf64jajIWoDTAAv93f358m+csogJZcp5yytHYc2MUiNsoAvJZ14QDAa8xTHgllexZjIWoD9Nhv9/f3SXJvFECL7pobnyujAHZQN78/fHAC8GvWhQMAhzBLctG83JsxpmvnRURtgF5ZxezbWA8DtO/P5qYHYFuz5ubyjVEAbLAuHABo+95M1GZsRG2AHlnF7GU8gxLoxk3KKW3rLYFdXCT5wxiACV9HWRcOAPTBLGX1+FujYEREbYAeWMXsjy40gA7dpQQpF4bALk5T1o7bMgOM2Wpd+PLBnwAAfVOlxD+fNTO2a/FFfHYJ0IlVzF4keW8cQMc+pUTt70YBbMnacWBM7vJjuHZ9BAAMSdXco9kGypiI2gAdWMXs8yT/Ng6gJxeF57EmE9jNPGW1nWe1AUNyk81V4a6DAICxqFPin6jNmIjaAC1axew6yRfjAHrk95QgBbCt0+aG8sQogB6yLhwAmKI6ojbjvLZfRNQGOKhVzE6Se+MAeuY65ZS2tZrAtmYpX4jxnDagS9aFAwBsmqfEv2OjYEREbYADehizv8dKTqB/7lKC9tIogB2cNzeTrnGANlgXDgDwMvOI2oyPqA1wAA9j9jLWvAD99aG5GATYVpXkKtaOA/tlXTgAwOstklzEF5AZ373CIqI2wF48jNlXSd4YCdBjNymnLG+NAtjBZZJ3xgDswLpwAIDDmaUEbVGbsRG1AfbgYcxeJHlvJEDP3aWsoroyCmAH1o4DL2FdOABA+1ZR22fUjI2oDfAKD2P2PMm/jAQYiE/NDY5TUcC2ZilfiPF4FSCxLhwAoG+qlPD31igY4b3HIqI2wFYexuw6yRcjAQbkJuWLOE5LAbtYxDf+YWqsCwcAGI4qojbjJGoDbOFhzJ4l+Y+RAANz11z8XRoFsIM65ZS2teMwTtaFAwCM475tEdu1GB9RG+AFHsbsJLk3EmCgPqec0na6CtjWrLlxfGMUMGjWhQMAjFsdUZvx3sssImoDPOlxzP6a5MRYgAFf+M3jw2tgNxdJ/jAGGATrwgEApqtOiX7HRsHIiNoAT3gcs5fxzTZg+D40F34A2zpNWTvuQxHoF+vCAQB4bJ7y+Y/7N8ZG1AZ44HHMXiR5byzACFwnOY9TWsD2rB2HblkXDgDANuZJLpMcGQUjvDdaRNQGJu5xzLZeExiTu+aG5soogB3M4wMRaOO92rpwAABea5by2faFezhGSNQGJu1xzK6TfDEWYGT+bG5mALZ12twsnhgF7IV14QAAHJKozZiJ2sAkPY7ZVZL/MxZghG5STln60BzY1qy5WXxnFLAV68IBAOjyPu4yyVujYKT3WouI2sBEPI7ZSXJvLMBI3aV8M9eFHrCL8+b3h2/3w9PvsatgvWx+ti4cAICuVSnRT9RmjERtYBKeitm3SY6NBhixzymntH3IDmyrSnIVa8fhOus14cvmHgIAAPp8L3eZ5I1RMEKiNjBqT8XsZZIzowEmcJF3HmvHgd1cxtpxpvWeucxmvAYAgCGqU6Kfz78Z673bIqI2MDJPxWwfzgJT8nvzew9gW3XKKW1rxxkT68IBAJjK/dwiojbjJGoDo/JUzF4keW80wIRcp5zS9mE9sK1ZStD2AQhDfg+0LhwAgKmap3we7rGbjJGoDYzCUzG7TvLFaICJuUsJ2kujAHawiC8D0n/WhQMAwNPmEbUZ973gIqI2MFBiNsCmP5NcGAOwg7q5MfThB31gXTgAAGzvIiX6eZwUYyRqA4P0VMxOknujASbsJuWU9q1RAFuaNTeFb4yCllkXDgAA+7uvu2heojZjJGoDg/KzmP3dGzUwcXcpK6aujALYwUWSP4yBA7EuHAAADm8VtT1SijHfWy4iagM997OYvUxyZjwA+dTcuFjNCmzrNOULMdaO8xrWhQMAQLeqlOD31igYKVEb6LWfxeyP3pwB/usm5ZT2V6MAtjRLcum6ii1YFw4AAP1URdRm3ERtoJd+FrMXsT4F4LHfU6IUwLbmze8Pj3HhIevCAQBgeE6b+zubTRnzveoiojbQEz+L2edJ/m08AD/4nBKlrHgFtnXa3AieGMUkWRcOAADjUqcEP1GbsRK1gV74Wcyuk3wxHoCfXsjN4wQdsL1ZcyP4zihGz7pwAACYhjol9h0bBSMlagOd+lnMniX5j/EAPOtDcyEHsK3z5ibQ2vHx3NgvY104AABM2TzlcyJRmzHf+y4iagMt+1nMTpJ74wH4pevmZuXWKIAtVUmuYu340FgXDgAAPGceUZtxE7WBVj0Xs5fxvA+Al7hrblSujALYwWWsHe8z68IBAIBtzZJcNC8buRgrURtoxXMx+yrJGyMCeLE/mws4J/SAbdXNtZcPObq/EV/GunAAAGA/RG2mci+9iKgNHMhzMXuR5L0RAWzlJuWU9lejALY0SwnaNuO0w7pwAACgzfu9yyRvjYIRE7WBg3guZl8k+cOIALZ21/wOdeEG7GIRXyg8hNW68GXz562RAAAALauaez5RmzETtYG9ei5m10m+GBHAzj6nnNJ20g/Y1mnKKe1jo9jJTTZXhduWAQAA9EmVclLbYz4ZM1Eb2LowcQIAACAASURBVIvnYnaV5P+MCODVF23nEVKA7c2aGz4fbjzvLutgvfrTl4gAAIAhqFNin8dNMWaiNvAqz8XsJLk3IoC9+NBctAFsy6NfNlkXDgAAjE0dUZvxE7WBnfwqZn9NcmJMAHtxnXJK24lBYFunzc3e1K7LrAsHAACmZJ4S+zxyijETtYGt/CpmL+PbYAD7dJcStJdGAWxplvJMtbcj/v24jHXhAAAA84jajJ+oDbzIr2L2Isl7YwLYuz9TVgcDbGueErWPBv7vw7pwAACA512kfEZ/ZBSMmKgNPEvMBujOTcop7VujALY0tLXj1oUDAADsZpYStS8iajNuojbwpF/F7DrJF2MCOJi75mbERRqwi8sk73r4e20Z68IBAAD2aRW1HT5j7ERtYMOvYvZpkr+MCeDgPjU3JIIPsK3z5gavq2/oWxcOAADQniol9L01CkZO1AaS/DpmJ8m9MQG04iblWbjW7wLbqpJc5fBrx60LBwAA6M994CKiNuMnasPEvSRm3yY5NiqA1vyesjoYYFuL7G/lnHXhAAAA/Xea8jnSmVEwcqI2TNRLYvbSGyFA6z6nnNIWjoBt1SmntLddO25dOAAAwLDvBRfxWT7jJ2rDxLwkZn+MVSUAXbhLeRbu0iiALc1SgvbPPsSwLhwAAGCc6pST2idGwciJ2jARL4nZi+xvXSUA2/vQ/C4G2NYiyUWsCwcAAJiaeXNP6BGijJ2oDSP3kph9nuTfRgXQqevmJuTWKAAAAAB4oXlEbaZB1IaR+tsL/h4ndwC6d5ZymvLcKAAAAAB4oY9JTlM2/90ZByN2nORfKYeB5sYB4/GSk9lJcm9UAL3xZ8q3DH3ZCAAAAICXmqU8iuoiyZFxMHJOasNIvDRmf/fmBtArNynfMPxqFAAAAABsYZYS+d4ZBRMgasPA/e2Ff59YAtAvJ0mWKd+kBQAAAICX+p7ymdLfk3wyDkbO+nEYuJfGbKtsAfrnKMkfSa5SvlELAAAAAC91mxL3/p7ks3EwcqI2DJST2QDD96b5PX1qFAAAAABs6TbJeZJ/JLk2DkZO1IaBeWnMvjUqgN5fhP2V8vwXAAAAANjWMkkdUZtpELVhIMRsgHF539x4WDsOAAAAwC6WKVH7f5N8Mw5GTtSGnrNmHGB8zrJeDwUAAAAAu7hKUiX5Z0Rtxk/Uhp56acz+blQAg3KU5N9JLo0CAAAAgFf4mBK1f09yZxyMnKgNPfPb/f39S//er0lOjAxgcG5STmnfGgUAAAAArzBLctG8joyDCfiWZJHypQ6gA3/b4u91OhtgmE5SvpA0NwoAAAAAXuF7StirknyIk9qMn5Pa0LFtYvbSuAAG66i56PqY8g1aAAAAANjVKmqfJvlkHEyAqA0dcTIbYFreppzSPjUKAAAAAF7pNiXs/T2iNtMgakPLtonZX40LYDQXXH+lPNsIAAAAAF7rNiXs/b8k18bBBIja0JJtYvatcQGMyh9JrmLtOAAAAAD78TVJneQfEbWZBlEbDuy3+/v7bf7+eyMDGJ27JOdJlkYBAAAAwB7VSS6TnBgFE/Et5XnyH40C9uNvO/yXEIBxOUrypbnIAgAAAIB9WSY5TfLP6AtMg5PasGfbxuxbIwMYrfcpq6AqowAAAABgjz6mfOYkajMVojbsybYx+6uRAYzaSfO7/twoAAAAANizjykntT+kPPoOxk7UhlfaNmZ/NzKA0TtK8u/m5mJmHAAAAADs0feUx91VEbWZDlEbdrRtzF4aGcBkvM36uUYAAAAAsE8Po/afxsFEiNqwpb8ZAQDPOEkJ2hdGAQAAAMABfE/57OnvST4ZBxMhasML/XZ/f7/tv+be2AAm6XNzYeWREwAAAAAcSpXkMskbo2BCvqVsKvhoFLBpl5PZnl8BME1vknxNUhsFAAAAAAdym+Q8yT+SXBsHE+GkNvzELjH7q7EBTPqi6kvKtwQBAAAA4FCWKYcqRG2mRNSGR3aJ2bfGBjB575sbiplRAAAAAHBAy5So/b8pq5hhCkRtaIjZAOzqLOu1TwAAAABwSFcpz9P+Z0RtpkPUZvLEbABe4yjJv5NcGgUAAAAALfiYddS+Mw4mQtRmssRsAPbhXZKvSU6NAgAAAIAWfEyJ2h8iajMdojaT89v9/f22/5pZkv8YHQBPuEty0dxMAAAAAEAbZimfSV2kbBKEqfiWZBGfxzJiu8TsJLk3OgCe8am5efhuFAAAAAC0pEoJe2+NgokRtRmtv+34r7s2OgCe8TbWjgMAAADQrtuU1ct/TzlsAVNh/TijtWvMdtIOgJdcQP2VckIbAAAAANpym3XUdjiPKRG1GZ1dY/ZXowPghf5Iskx5dhEAAAAAtOU2SZ3kHxG1mRZRm9FwMhuANpw9uHkAAAAAgDYts47aN8bBhIjaDJ6T2QC05SjJlySXRgEAAABAB5ZJTpP8M8k342BCRG0Ga9eYfWt0AOzoXcqXoiqjAAAAAKADH1M+mxK1mRpRm8ERswHowklK0D43CgAAYGKqlA+PL5v7ovvm55nRALTuY/N7+UOSO+NgQkRtBuO3+/v7Xf+1X1NiBAC8xqckF0m+GwUAADBCdfM6bf48+snfd5dkEY9mAujKLOUzqotnflfDWH1rrkM+GgV985qYvUxyZoQA7MFNyjcAvxoFAAAwYFU2w/UuB0G+pYSUK+ME6MQsJeq9MwomSNSmd14Tsy/9Mgdgz36PUwgAAMBw1HnZqetdXKd8mLw0ZoBOVM3v4bdGwQSJ2vTGa2L2Isl7IwRgzz6nnNK2dhwAAOiTKq8/db2LTymfw936RwDQ2e//RURtpknUpnOvidl1ki9GCMCBLpLOY+04AADQnTqHO3W9rbuULVaX8cVfgC7fFxbx+FWmSdSmM6+J2adJ/jJCAPZ4QbRMCdirPwEAANpQpZtT19u6S3me9kf/yAA6U0fUZrpEbVr3mpidJPdGCMAO7rKO1svmZ6cLAACAttTpz6nrXXxLeTzT0j9KgM6cp2zMODYKJkjUpjWvjdm3flED8AI3WUfr1QsAAKANVYZx6noX1ylR+9Y/ZoDOzFOinlbCFInaHNxrY/YyVmkA8OMFzCpYL+OkAAAA0K46wz51vYtPKevHbbwC6M485aT2kVEwQaI2B/PamP0xyVtjBJi062w+5/rWSAAAgJZUGe+p623dpUSUy4jaAF2ZpXy56CKiNtMkarN3r43ZiyTvjRFgUhcjy2zGawAAgLbUmd6p613u2xbxITJAl0RtXI+4HmFPXhuzz5P82xgBRukum6vCv8a3+wEAgPZUWUfr03jU3bauUz5EXhoFQKfvZYvYcMt0idq82mtjdp3kizECjMJN1tF69QIAAGhLnc14fWwke/E55WTgrVEAdKaKqM20idrs7LUxO0nujRFgcO6yuS58aSQAAECLqjh13bY/Uz5EtnELoNv3v4/e95gwUZutidkA03Cdzedc3xoJAADQojpOXffBXZLLlA+RAej2fXERUZvpErV5sX3E7KVfuAC9uxBYZr0qfGkkAABAi6o4dT2E+8aLJFdGAdCpOuVLRidGwYSvSRYRtXnGPmL2VZI3RgnQibtsnrhexso4AACgXXWcuh6q65QPkJdGAdCpefP72HsoUyVq81P7iNmLJO+NEqAVN9mM11+NBAAAaFEVp67H6FPKZ3y3RgHQqXlEbaZN1OYH+4jZ8yT/MkqAvbvL5onrpZEAAAAtq+PU9ZR8SFl3a+MXQLcWKY+DODIKJkrU5r/2EbPrJF+MEuDVrrN56vrWSAAAgBZVceqa8sXqi/jwGKBrs+b3sajNlIna7CVmz5L8xygBtn4TXma9KnxpJAAAQMvqOHXN8/etc/erAJ1bRW2Pe2Xq1yWLiNqTtI+YnST3RgnwU3fZPHG9jJVtAABAu6o4dc1urlMiylejAOj8vXyR5K1RMGGi9gTtK2Z/TXJinABJkptsxms3/AAAQNvqOHXNfn1Kidq+nA3QrSqiNojaE7KvmL2Mb/QC03SXzRPXSyMBAABaVsWpa9q7B75sXqI2QLfqlJjnfZ8pE7UnYF8xexHPawCm4Tqbz7m+NRIAAKBldZy6pls+OAbo13XBIqI2rk1cm4zUvmL2RZI/jBMY4Rvg42ddAwAAtKmKU9f0103K54LulwG6V6eEPF9yY8pE7RHaV8yuk3wxTmDgrrMZrq1MAwAA2lbHqWuG53NK1L41CoDOzVNinmsIpkzUHpF9xezTJH8ZJzAgN9k8df3VSAAAgJZVceqacfkz5YNjXw4H6N48yWWSI6NgwkTtEdhXzE6Se+MEeuoumyeuv7qxBgAAOlDHqWumcQ9+mfLBMQDdmqVszriIqM20fWv+e3BlFMOzz5h96yYM6InrrE9bL2PNGQAA0L4qTl0zbT40BugPUZupWj1adPVigPYZs5duzICObo4fnrj2hgQAAHShjlPX8JTrlFPa7tcBujdL2Z7x1igYqZusw7Uv1I3EPmP2ZZJ3Rgq0cBO8zDpcWxcOAAC0rYpT17CtTylR+9YoAHpxLbOIqM3wPYzXy+gFo7TPmL1I8t5IgT2/ET08df3VSAAAgA7Uceoa9uVDyqEYHzYDdK9K8jG+mMdwfMvmyWvXExOwz5hdJ/lipMCO7rIO18vmZ29EAABA26o4dQ1tfAawSInaAHSvbn4vu+6hbx7G62VseJkkMRvoymr9x1dvQgAAQIfqOHUNXfmWZB7P0wbo03XRIqI23bnL+tT1MroB2W/MTpJ7IwV+cnP6cF24m1QAAKALVZy6hj66TnIRjxcD6It5StT2JT8ObRWvVy/XAvxg3zH7e5IjYwU3odl8zvWtkQAAAB14GK7r+EAW+u5TSjy5NQqAXphH1Gb/Pke8Zgv7jtnL+FYzTM1N1tHamw8AANCVWTbDtc8nYJjuUp6lfZlycAaA7i1SNmg4zMguVoffVi/Yyr5j9sckb40VRn1D+TWb35pyYwkAAHTBqWsYt28p8eSjUQD0wiwlaIva/Ip4zV7tO2Yvkrw3VhiNm2w+5/rWSAAAgA44dQ3TdZMSTpZGAdCb67KLaEFsvlcvH7wcgGOv9h2z50n+ZawwWKtnVXx1kwgAAHTIqWvgseuUzx5vjQKgF6qUA4629U6PeE2r9h2z6yRfjBUGdSP48E0HAACgbU5dA9v4MyWe+OAcoB+qiNpj9y3rhnDlPZi27Ttmz5L8x1iht24evekAAAC0zalr4LXuklymxBMA+qFufi/7YuLwPYzXy9iKQsf2HbOT5N5YoXdvOlex7gMAAGifU9fAIX1LCScfjQKgN+qI2kNzl81DcLdGQp8cImYv/ZKCTt90ruIbUwAAQDecuga6cJ0STpZGAdAbdcqXjVwP9s/DeL1M8tVI6LNDxOyrJG+MFrzpAAAAo+bUNdA3n1Ki9q1RAPTGvPndLGp36zrrg3A6AoNyiJi9SPLeaOGgbzrL5o3Hmw4AANAWp66BofiQ8kxtj1sD6I9587v5yChaseoIqxcM1iFi9kWSP4wW9uYmm8+9BgAAODSnroGhu0s5dHNpFAC9usa8aF6i9n7dZPMRpDAah4jZdZIvRguvetNZPnj5FjEAAHBoTl0DY/UtJZpcGQVAb4jar6cjMBmHiNlVkv8zWtjqpurhm86tkQAAAAfk1DUwRdcp0cQj2wD6dV16meStUfySeM1kHSJmJ8m90cJP3T14w7mKeA0AAByWU9cAa59S1o/fGgVAb1TN72ZRe80hOGgcKmZ/TXJivPBf11k/r8I3gAEAgENx6hrg1+5STgJexsk2gD6pmt/Nbyb47128hp84VMxeumFm4q4fvfEAAAAcglPXALu7S1k9/tEoAHqlTjmpPebOZIMrvNChYvZlknfGy4R4XgUAAHBoTl0DHMZNStReGgVAr9QZT9R+GK+XscEVXux/DvS/V8hj7B6u/Ljyn3kAAOAAnLoGaMdJki8pm/bmcToOoC+WzXXwPCVqD+16eLXB9SriNezsUCez6+YCEMbi7sGbztJNDQAAsGdOXQP0x6eUk9oOLwD0yzz9jtoePwoHcKiYfZrkL+NlwKz8AAAADsmpa4B+u0t5lOLCKAB656L5/XzU8f8fq8ePrg7BAQdwqJidJPfGy8D41hQAAHAITl0DDNe3/8/e3V61kaRtAL6HM/9hI0BvBDAR0BOB2QiQI7AnAuMIzESAHIFxBBYRGCIYEcFABLw/qlksA0aCltQf13WOz3jXNh+3RHdVP1VPpRRMJqIAaN0Y+339a11F7bvi9d0vHTxgDVZZzJ7FynLa7ccbz5k4AACAhth1DdA/5ylF7akoAFrlrqj9YQUf+yr3u66nUbyGjVhlMXsaq81pFzceAACgaXZdAwzL15SiyUwUAK0ySll0dPSKj3GV+Z3XrvXQAqssZk9eedGA13LjAQAAmmbXNQBJ8jHlTG2bJQDaZZTFi9pqCNABqyxmH2c1bR3gKTc/3XguRAIAALzCTu6L1lXsugZg3k3KM9ATUQC0zn59fT746bo9jRoCdMoqi9mHSb6ImBU7z/2Z1248AADAa+xnfuf1nkgAWMBVSuvxM1EAtM7d2H4aNQTopFUWs6sk30RMwy4zf+41AADAS/y863o/ybZYAHiF85SitmIJAEBDVlnMTpJbEfNKl5lv++EcIgAA4CXsugZgXT6ntB+fiQIA4HUUs2mbq8wXrw36AQCAZdl1DcCm3aSc1XoSmzMAAF5s1cXsaZIDMbOAy5Rz1meiAAAAlmTXNQBtdZPSenwiCgCA5a26mH2W5I2YWcBlykMnAACAX7HrGoAuukoyTtn8AwDAglZdzD5O8kHMLPp+FAEAAPATu64B6JPzlKL2TBQAAM/7fcUf36AMAACARdl1DUDfHST5J8nnlPbjztMGAPiFVe/MrpJ8EzML+o8BPAAADIpd1wAM2U2Sk/qXZ2IAAI9YdTF7J8m/YmZBf8a5QQAA0Fd2XQPA465SjmuciAIAYN6qi9lJcitmFqSYDQAA/WHXNQAs5zylqD0VBQBA8fsaPsdlPLRgMSMRAABAJ9l1DQCvd5ByZOPXlPO0ZyIBAIZuHcVs572wqJEIAACgE+y6BoDVeVP/+jtlp7bnqwDAYK2jmD1NWVUIAABA99h1DQCb8S7JOKWgfSIOAGCI7MymTfZFAAAArRiX23UNAO2wneRTStvx90nORAIADMk6itkXYmZBOyIAAIC1j8HtugaA9ttN8iXJecpO7alIAIAhsDMbAABgOOy6BoBuO0jyLcnnlKL2TCQAQJ/9dnt7u47PcytqFn1PigAAABph1zUA9NtNylnaJ7GhCADoqXUVs2cprXDg2fekCAAA4EXsugaAYbpJOU97IgoAoG/WVcyeprTAgWffkyIAAIBn2XUNAPzsKsk4ztMGAHrk9zV9nosoZrOYyoAbAAAesOsaAHjObsp52ucpRe2ZSACArltXMduZLQAAAIux6xoAeI2DJP8k+ZzSftyzWQCgs9bVZrxKWRUIz/lvkjMxAAAwIHZdAwCrcpPkpP6lqA0AdM7vIqBl9qOYDQBAf9l1DQCs03aSDyltx4+TTEQCAHTJuorZU1EDAAADNMp84dquawBgE3aTnKa0HX8fz2sBgI5Y587sm9hxwPNGIgAAoMOq3BeuK3MgAKBl9lKOg/yaUtSeiQQAaLN1nZmdlNV+ByLnGecpD/0AAKDtRpkvXNt1DQB0zd8p7cedpw0AtNI6d2bPopgNAAB0VxW7rgGAfnmXcp72SUpRGwCgVdZdzIbnjEQAAEBLxqVV7LoGAPpvO8mHlKL2+yRnIgEA2kIxm7bZFQEAABtQxa5rAGDYdpN8STkG8Djl2EgAgI1a55nZVZJvImeR96UIAABYoVHsugYAeM7nlKL2TBQAwKass5i9k+RfkbOAP5JciAEAgIZUsesaAOClPqacqX0tCgBg3dZZzE6SW5GzgD+jjREAAC8zil3XAABNu0k5T3siCgBgndZdzJ4mORA7z1DMBgBgUftJDmPXNQDAOlwlGcezOwBgTbZEQAtVIgAAYEGjlF1Cb6KQDQCwartJvqUUs/fFAQCs2rqL2VORAwAADTpLeZB6KQoAgLU5SPI9pe34jjgAgFVZdzH7WuQAAEDDZikF7b9FAQCwVkf1WOw4itoAwAqsu5h9IXIWUIkAAIAXeJ/kv0luRAEAsDbbST6kPPsdiwMAaNK6i9kzkQMAACuk7TgAwGbsJjlNKWpX4gAAmqCYTRtpSQQAwGvnHdqOAwBsxl6Sb0mmSUbiAABeY2sDn9MOCRYZ8AIAwGtpOw4AsDkHSf5JchKbVwCAF9pEMfta7AAAwJpoOw4AsFnvUjrnHIsCAFjWJorZF2JnASMRAADQkFm0HQcA2KTtJB/qcdlYHADAouzMpq1GIgAAoGHajgMAbNZuktOU87QrcQAAz9lEMXsqdgAAYEO0HQcA2LyDJN+STGJTCwDwC3Zm01YGsQAArMos2o4DALTBUZJ/Us7T3hEHAPAzZ2bTViMRAACwYtqOAwC0w9152u9FAQD8aGtDn9fDIgAAoA20HQcAaIftJJ9SitqVOACAZHPFbLuzec6+CAAAWJNZtB0HAGiL3ZTztKfxjBAABm9TxeyZ6HmGM3IAAFg3bccBANrjIMn3JJM4khAABksxGwAA4J624wAA7XKU0unzODbAAMDgaDNOWx2IAACADZlF23EAgDbZTvIh5bnyWBwAMBybKmZfix4AAGg5bccBANplN8lpSlG7EgcA9N9vt7e3m/rct+LnGf+JhQ8AAGzeKKX9+J4oAABa5Txlp/ZMFADQT1sioMX2RQAAQAvMou04AEAbHST5J8lJnKcNAL20yWL2ufgBAIAO0XYcAKCd3qUsQDwWBQD0yyaL2dpH8xyrKQEAaJuzlF3al6IAAGiV7SQfUoraY3EAQD9ssph9IX6eoc04AABtNIu24wAAbbWb5DTJNEklDgDotk0Ws2fiBwAAOkzbcQCA9jpI8i2ls85IHADQTYrZtJlBJgAAbaftOABAu71J8k/KedqONQSAjlHMps1GIgAAoANm0XYcAKDt7s7Tfi8KAOgOxWwAAIBmaDsOANBu20k+pTybPhQHALTf1oY/v1Z8/Mq+CAAA6BhtxwEA2m83yZck03gGCQCttuli9rWXgF/YFgEAAB00i7bjAABdcJDke5JJHHkIAK206WL21EsAAAD0lLbjAADdcJTkIslxkh1xAEB72JlN22nzAwBAl2k7DgDQDdtJPqR02RmLAwDaYdPF7AsvAc+wEhIAgK6bRdtxAICu2E5ymvLsuhIHAGyWndkAAADroe04AEB37CX5lnJU5kgcALAZdmbTdpUIAADokbOUh6HnogAA6ISDJP8kmUQXSQBYu60WfA1XXgYAAGBArlMWbX4UBQBAZxylHB9zLAoAWJ82FLNnXgZ+wWpHAAD66jjJn9F2HACgK7aTfEh5pj0WBwCsXhuK2VqN8yv7IgCgxXaSHKYUpKbxMANY3jTajgMAdM1uktN6LFeJAwBW5/cWfA3XXgYAoCOqlIVWd//d/enPD1KK22NjHGDJOVGVsjDmgzgAADrjIMm3JF+TvI8upADQuN9ub283/TUcJvnipeAJl7E7G4DNGOW+aL2f8pBiUVf1GEcHGmBZVZKzlBaWAAB0y98pCxQtbgaAhrShmF2lrF6DJ9+nIgBgxXZyv+O6qn/fRCHpryQn4gVecE06y3KLaAAAaIeblIK2uSAANKANxewkufVS8Kv3qQgAaNiPrcL3k+yt8HN9jbbjwMscR9txAICuukppPX4mCgB4ubYUs6+jjR5P+784bwaAlxtlvni9iZ2ONyltx6deDmBJVbQdBwDosvOURYrmgwDwAm0pZk+jhR5P+9NgD4AlVJnfdb3boq/tY8pDDIBlaDsOANB9n+v54EwUALC4thSzJ0mOvBw8QTEbgKfs//CrymrbhTflPGWXtrbjwLKOo+04AECX3aScpX1iTggAi2lLMfs4HsrwtL/qAR4Aw7aT+x3Xd//tatvdm5RztJ2dBiyrirbjAABdd5NynvZEFADwa1st+TpmXgp+YUcEAINU/TC5nyX5N8mXlAVwB+l2IWe7/l4s1gKWNU0ySunyAABAd+eEp/VctxIHADzt95Z8HTMvBQAM2ijz51wP5VzYd/X3fWg8BCzhur52HEeHKwCALttN8i1loeLYvBAAHmpLm/GdlN1W8JivKQ/5AeiHncy3Cq+iXa4Wc8BLVdF2HACgLz7Xc0PnaQNArS3F7CS59XLwhPNotwPQZT8WrveT7InkSR5cAC+xk1LQPhAFAEDn3aQcSXVibggA7SpmT+PhC49TzAbojlHui9aVe/uLXKa0l7sQBbCk42g7DgDQF1f1+G4iCgCGTDGbzrxXRQDQSlXmd13viqQRNykPLU5EAbzguqztOABAf5zX88OpKAAYojYVs49jFwG/eK+KAGDj9jO/61q78NX7mrJLW2s5YBnajgMA9HN++D7JTBQADEmbitnvk3zykvCE/8SDfIB12sl90bqqf2+X32ZcJTmMtuPA8o5jwTAAQN/8XY/zPCsFYBDaVMyuknzzkvCEP6OVDsCq78M/7rrWLrx9/oq248DLru/ajgMA9IujqQAYjDYVs0dJ/vGS8ATFbIBm77l3Rev9aEPbJecpu7StwAeWoe04AEA/XaV0PD0TBQB91aZidpLcekl4wtskEzEALO3HduF3/7U7r9tuUgraU1EASzqOtuMAAH10Xo/1zBMB6J22FbMvkux5WXjEx3pABsCv/dgqfN991b0R4CdVtB0HAOirz/U8cSYKAPqibcXsabS+43Ee2AM8NMp88do9dHjOk4zjQQWwHG3HAQD67WPKedqOqAKg87Za9vVceEl4wkgEAKlyfxbWLMk/Sb6ktIxVkBimg3r8dCgKYAnX9T3loygAAHrpQ8pzg7EoAOi6tu3MPo4ztCiaogAAIABJREFU3HjcecoDN4ChGGX+nGvtwnnO3ymLHQCWUUXbcQCAPrtKKWpPRQFAF7WtmF0l+eZl4RGK2UCf7eS+aF3Vv1dU4CUuU3Zpz0QBLHkf0nYcAKDfzlMWQOuOCkCntK2YvZ/ku5eFR9ykPGQD6IO7wvXdf3dFQsP3zPdJJqIAlnQcnbIAAPrucz1ndJ42AJ3QtmJ2ktx6WXjq/SoCoINGmS9e2/XGunhAAbxEFW3HAQD67ibJSf3LnBGAVmtjMfs6HpzwxPtVBEAHVJnfde2exiZdppyNpo0csAxtxwEAhuEqpTvPRBQAtFUbi9nTeGjC4/6s3x8AbbGf+V3XeyKhhW5SHk6ciAJY0nG0HQcAGILLlM5eU1EA0DZtLGZPkhx5aXiEYjawSTuZ33Ft4RVd8zVll7YWcsAyqmg7DgAwpHnj+yQzUQDQFlst/JrcKAFog6qewJ3V96Z/k3xJ2aGmkE0XvUlpN74vCmAJ0ySjJOeiAAAYxLzxn5TOXjviAKAN2ljMdqYjT6lEAKzIKGXH6kl9H7pN8i3Jp3oitysiemI3yfeUhRoAi7qux+IfRQEAMAjvUhb2H4sCgE1rY5vxKqWAAD/7aAAFNGAn963Cq/r3WqcyROdJDqPtOLD8fE3bcQCA4bjKfec6AFi7Nhazk7IjDn72d+wkA5Z3V7jer3/tiQT+5yaloD0VBbCEnZSHmY7dAAAYjvOUjUbmjwCs075iNl0bMFViAH5hlPnitYfssBjdT4CXOE7yQQwAAIPyuR4HzkQBwAqMct9V9TDJrK3F7GkUIHhIMRv42U5Kx4a7XdfOtobX3WfH8UACWE4VbccBAIboY5KTOLoKgNfZyXzx+udn/OdbLf3C3QB5zEgEwCP3i1GSN1HIhtc6SHJRDxoBFjWt78XnogAAGJQPKYuhHQsJwLKqlC4fF0n+TfIlybs8/ox/2tZi9oXXkUcoVAGPGSd5KwZoxHY9eDwRBbCE63oi+lEUAACDm0N+SilqV+IA4An7KYufzlKOmv6Wsihqb5F/3NY24+Mkp15bHnvPigD4xb3jJNqcQlMuU59LIwpgCVW0HQcAGKrzlGKFzWoAwzbKfOvw1zwj+LOtxewqpSoPP/u/eKgOPG0/pd2pB+jQjJuUBxETUQBL2EkpaB+IAgBgkD6ntI+diQJgMM8Bqjx97vVr/NHWYvYoyT9eex7xZ0qhCuAp+ykP0B1NAM35nFLUvhYFsITjlLZhAAAMz01KB70Tc0mAXqpyX7zeW+Hn+a2txeyk9EyHnylmA4vYqa8Ve6KAxlymtPPXLg5YdnKr7TgAwHBdpSxynIgCoNP2c1/AfrOmz3mTZGerxaFcel/wxA8LwHOu65vqV1FAY/ZSFom8FwWwhGlK561zUQAADNJuktOUhdGVOAA6Y5SysWWS8rz9e5JPWV8hO/W9I20uZms9wmN2RAAscR85TGmPDDRjux60nrknA0vek6skH0UBADBYe0m+5X6xIwDtspPyPP0kySzlOOjTJEfZXLe1WdLuYvbU+waABoyT/CUGaNSblJWROqYAyzhOOTboShQAAIN1kFIgOYlF0gCbVtVz9WmSf5N8SfIupatGG8wSO7Pp5g8WwLJOkrwVAzRqN6W9kLbjwDKmKQthHAUCADBs71KKFMeiAFib/ZRneWcpddhvST6kLDRqo9a3Gb/wngKgQZMkfyS5EQU06lNKccqKemBRd0eB6JwCADBs2ylFlFlKZz0AmjXK/bnXs8yfe73dga//Okl+u729besXuF+HCj+6jJamwOvvL9OO3KyhS25SilNTUQBL3pfP0p4WZgAAbM557tvdArC8nZQOx3e/9jr+/fwnyXWbi9lJcut9xyN+EwHQwE192oObObTRx2gTByx/X56krAwHAIDP9bxyJgqAZ1U//Dro2ff2W9Lundmpb1ZW6PPomxfglXZSdoIdiAIad57SwmgmCmAJ71PanQEAQFIWS5+kbjMLQJLS4az64VdfO5Ce199f64vZ0ygy8NB/DGCABk2SHIkBGneTUtA+EwWw5KRc23EAAH6cWx6nFLUBhmiU+eL1UObL/ytmb7X8C73wHuURzswGmjROWekLNGs7yZd44AAsPwfcT/JVFAAA1HPLTymdvypxAAOwk+Qw5ZnaRZJ/kpymbMga0sLv6d1v2l7MtvsWgHU4TvJWDLAS7+qB90gUwBLzwMMkf4kCAIDabpJvKcUNm52AvqlSnlFPk/ybskHkXZK9gT8bSGJnNt00EgGwApMkf6a0rwKatVeP68aiAJZwkuSPJFeiAACgdpDke8pznJE4gI7aT/I+5Zit65TFOh/i6OUf/a9GbGc2XWSQAqzKNGUVnII2NG87pSXSJKVdEsCik1dtxwEA+NlRPVY8NscEOmAnZZPHJOXYhO8pRyi8SXlmxkOzu9/8dnt72/Yv9tbrxU8+1oMUgFUOLqYZdhsXWKXLegCvCw+wjPf1ZB8AAH50U48VJ6IAWuQwZeNUFc+ZX+K3//2mA8Xs61iVwLyv9UUAYJUUtGH1/kppIwywqP2UNmy7ogAA4CeXKUXtqSiADc1X7wrY2oW/zlV+6NK81YEv2I4dfqZtDLAO1/UA5LMoYGU+pRSl3NuBZeaH2o4DAPCYvZRzZ6dxVCWweqPMn3v9Pc69bsrsx//RhWK2c7MB2KRxkr/FACvzJvfFKYBF54iHKd0dAADgZwdJ/klpO27xNNCUn8+9/ifOvV6VuY3OdmbTRR52A+v2PslbMcDK7KasXj0WBbCEkyR/pLQfAwCAnx2lFJzMNYGXOqznnhdJ/k1yWl9bHH21WnMbnbtwZva4fnPA3HtXBMCGBi+TWGkHq3Re/6zpzgMsaqe+P78RBQAAT7hKKWpPRAH8gnOv2+G/Ke3bk3SjmF2lnHMBP1LMBjY5oJlGQRtW6aaeOExFASzhfUqLNwAAeMp5SlHbfBNIyrnXd8XrKp75tsWfP16nu1DM3knZug9PvpEBNjDIOUuyJwpYqY/RDg5Yzn59j9byDQCAX/mashhyJgoYlJ3MF6/NHdtpbkNrF4rZSXLrdeMnitlAGwY+0yhow6pd1pOMmSiAJe7Rk2g7DgDA8z6mnIfrqCvorx+L157ltt9NPa//n62OfOHnXjt+siMCYMOu6wHQZ1HASu0luagnHgCL3qMPk/wlCgAAnvEhZfH0e1FAb+zXP9PTlM2yX5K8i0J2V1z8/H9syYQOX4wANu06yTgK2rBq2/XE40QUwBJOkvyR5EoUAAA8M+f8lFLUtpAaumeU8oz2LOV57ff6Z/pANJ30oFNGV4rZU68dAC02TvJWDLBy71JWZ1rUBizq7prxVRQAADxjN2Uh9dS8E1rt7tzrScoilH+SnKYcNbUtnl7M4+d0pZjtvAoeu1gBtMkkpaB9IwpYqb2UBwtjUQBLzCe1HQcAYFEHKTs7Jyk7PoHNq1K6b10k+Tdl4clRyiIU+mX28//x2+3tbVfepN+8fvzgvH5fALTNfkqhzSpAWL3PKWcgWfgILHOfPosHHgAALOamHkPORAFrn7tVKQuTtQsflj/zU8furhSzRyltAuCOYjbQ9sHWJGUHKbBalym7tC9EASxop75PvxEFAAAL+E0EsHKj3Bevq9goNGT/yU8bV7pSzE6SW68fP7iKFi9Au+2krCBT0Ib1+Cul3RTAot4n+SQGAACeoZgNzdvJfPFa9yyevOZ2qZg982bGIALo4KDsJOX8FmD1vqbs0tZ2HFiUtuMAAPzKZT1mBF6vyn3x2gYgFr7mbnXoG5h5DQHomOuUwtpnUcBavElpN+5BA7Cou2vGV1EAAPAIi6Xh5fZTOmJNU7ovf0vyLgrZLHnN7VIx2zmIPHYhBOiCcUoLZGD1dpN8T3IsCmCJyfKhezUAAE+MFYHFjFKeg57VPzvfU452OhANC5o+9n/+7qZBh+2IAOiQk/pedioKWIsPuW9fZRwJLHqvnkbbcQAA7tlkB09z7jVr0aWd2VMvFwAdN0nyR5IbUcBaHKQcVVOJAliQtuMAAACLOUvyJclRFLJpxvSx/7NLxWw7aviZNuNAF12kFNauRAFrsZ1yJtOxKIAl5p7ajgMAkNiZDb8yEgErmI8/4MxsukybcaDLE6H9JJeigLX5UP/smWgBizpJ6ahiARoAwHDZZAdPsxubpj1aC97q2DehLSsAfZoMVdHGFNZprx4UH4oCWGIire04AMBwKWbD42w2pGlPLiTvWjHb7mx+VIkA6MGE6DDJZ1HA2mynnOd0Igpgyfu1tuMAAMOjJgGPcwwsTZs99QdbfflGAKDDxkk+igHW6l3ud1wCLELbcQAAAFiN2VN/oJhNl2ljAfTJcZK3YoC12ksyTVlQArAIbccBAIbjUgTwpEoENGz21B9oM06X7YkA6JlJkj+T3IgC1mY7yWn982ehHLAIbccBAIYz7gNgPZ6sAXetmO3mAUDfTVNWNipow3od1T9/2o4Di9J2HACg39Qj4GmVCFjXNdfObLpuJAKghy7q65t2VrBee0m+J3kvCmCJe7a24wAA/R3rAbDha66d2XTdSARAT12nrHA8FwWs3ackZ9F2HFj8nq3tOAAAMCQ627GKufWjtjr4zXioD8CQbuBVks+igLV7k/sdlwCL0HYcAKBf7MyGp22LgAb9svbbxWK23dn8aCQCYADGST6KAdZuN6Xt+LEogAVpOw4A0B9qEfA4C/9Z6/W2i8Vsq6H40UgEwEAcJ3krBtiID0mm0XYcWHwSru04AEA/xnXAQ56P0LRf1n67WMyeeU0BGKhJkv8muREFrN1BPQ6tRAEsSNtxAIBus7EOHjcSAQ3r3c7smdeUH2hnAQzNWUoxTUEb1m87ybdoOw4sTttxAACgb0YiYAVz5ycpZtN12lkAQ7257ye5FAVsxIf659DkDVjEj23HLUYDAOgGz1zgaSMR0LDZr/5QMRsAunuDr0yuYGP2Ugrah6IAFnTi3g0A0BnOy4anjURAw2a/+sOtjn5TJv/cORABMPCJ1X6Sz6KAjdhO8iWlQAWwiIuUgrZ7NwBAuylmw9N0zKVJV8/9ha4Ws91IAODeOMnfYoCNeZf79v8Ai8xnx0neRttxAIC2uhABPGlPBDRo9txf6Goxe+q1BYA571MeigObm8hNUwpUAIuYRNtxAAAAhu3ZxUNbMqIHKhEAJCkPxe3ygs3ZTnJa/yxquQUsOmmvou04AEAbx2nAQ5UIaNiz3bjtzAaAfpnUg0oFbdico3q8qu04sOjEfRwL0gAA2jZGA2D1ps/9BWdm0wd2PgHMu9vlpW0pbM5eku8pRwAALGLi/g0A0BpqEPC4SgSsW1eL2Vp88CO7ngAev1dW8UAcNu1TkrNYfAcsd//WdhwAYPPjMgBWb/rcX+jymdlXXl8A+KXreCAObfAm5UGIBXjAovfvcbQdBwAA2sezDZq00Jy3y8XsmdeY2kgEAE+6eyCuoA2btZvSdvxYFMCCJtFlBQBgE4y/4Gk6z9GkhbpgbPX9G2QQRiIAeNY4ZYcXsFkfUtonmfwBi857q1iUBgCwTs7LhqfZmc3ar7dbff8GAYD/mUTLUmiDg5QuQ5UogAXnvmP3cACAtY6/gMdti4AG2ZnNYIxEALCwSUoBzcNw2Pzk71uSE1EAS97Dtb0EAFgttQd43EgENGy2yF+yM5s+2BUBwNKTsirJlShg497VP5MmhMAy93BtxwEAgHUbiYCGzRb5S10uZk+9xgDwYhcpZ9zY3QWbt1f/TB6KAliAtuMAAKtlZzY8biQCNnG93er4N2nizp19EQAs7Tpld9dXUcDGbSf5ktJ2fEccwAIm0XYcAGAVdIWFx41EwCaut10vZlshxR0PfQFePmA4jHal0BbvUjoQWagHLDonrtzHAQAapZgNj1OHoUkLL8zuejHbTQUAmjFO8pcYoBX2UgraY1EAC86Lx9F2HACgKTbRweMsvKfpuexC7MymLyoRALzaScqDcGDztpOcprQRtvIZWMQk2o4DAADQDdNF/2LXi9kzrzUANGqS5I/Y2QVtcZSygNPqZ2AR2o4DALyOhYHwtAMR0KDB7Myeea0BoHF3D8IVtKEddpN8T/JeFMCCDwTG0XYcAOClYykAVm/h7tvajNMXlQgAGr/HjmJFMrTJpyRn0XYcWMwk2o4DACxLMRseV4mATV1vt4byjQIAL7rPVknORQGt8Sb33RMAnqPtOADA8uMnAFp0vd3qwTfrATuJHUoAq3JX0PYQHNpjN8m3JMeiABa8l4+j7TgAAPBy+yKgQVfL/OUtedETeyIAWKlxko9igFb5kGQai/qAxUyi7TgAwHPszIbHefZAk2bL/OU+FLOnXnMAWIvjlF1dQHsc1BOAShTAArQdBwD4NUebwuPszKZJs2X+ch+K2W4u3BmJAGDlJkn+jDal0CbbKW3HT0QBLDiHHkfbcQCAp8ZKwEN2ZtOk2TJ/uQ/FbG0/uDMSAcBaTFN2dXkADu3yrh4bGxMBi5hE23EAgJ+pN8DjRiJgU9faPhSzZ15zANjIgGMUD8Chbfbqn89DUQAL3s+raDsOAAD82q4IaNBSXTAUs+kTZzYArH/QUUVBG9pmO8mXlLbj2oABi9zPx9F2HADA8w143EgENGy6zF/e6sk3feV1Jx7WAmzCdcpiIju6oH3e1ZMDC/6ARUxikRoAMGzOy4bHjUTAJvWlmD3zUgLARo2T/C0GaJ29lIL2WBTAArQdBwCGTDEbHmcjIU06X/Yf9KWYfeG1J3YdAWza+5QWpUC7bCc5Tdl1aQIKPEfbcQBgqNQZ4HFqLzQ951zK1lC/cXrJw1mAzZsk+W88/IY2Okp5OGMSCix6T6+i7TgAAADNWXrhUF+K2VOvPQC0xlnKw28FbWif3STfUzopADxH23EAYGhjH+ChSgQ0yM5sBu1ABACtmgDux24uaKtPKQtPdLYBFplvj6PtOAAwjHEPAKu19MKh325vb/vyzd96/UnymwgAWmUnpYPKniigla5SilRTUQAL2E9pP+6+DgD00R+xOxseo/5Gk/4vyWyZf7DVo2/eCnESu4sA2uY62pNCm+0m+ZbkWBTAArQdBwD6PtYBYLVmy/6DPhWz3WhIyk4BANrlrj2pB9/QXh9SdmdbGAgsel/XdhwAAPpPzYUmvehIyj4Vs2feAwDQauOUB99AOx3UY+pKFMACJvX14lIUAEAPGNPA4yx6p0nXL/lHitm4sAKwTpPYyQVttp3SdvxEFMACtB0HAPriWgTwKDuzaXoOuTRtxnFhBWDdJikPvhW0ob3e1ePrkSiAZ2g7DgD0ZUwDPGQDIRu/1m4NPQAAYCPudnJp4wXttVf/rB6KAljAxL0dAOgwm+XgcSMR0KDpS/6Rndm4sAKwyXt3FQ+9oc22k3xJaTtuNTaw6L1d23EAAOiHkQjYNDuzcWEFYNP37yoeekPbvUtZPetIF2CRe/s42o4DAN1isxw8biQCGjR9yT/a6lkI594HANA5dw+9FbSh3fbqScdYFMACJtGBBQDoDpvl4HG7IqAhL17s3LdithsOdgsBdNc4yV9igFbbTnKaUqTSdhx4zl3b8b9FAQC0nNoCPGTeT9PzwxfZEgQ9sy0CgE47SWlLCrTbUT32tpAQeM51kvdJ/httxwGA9lJbgIfM+WnS7KX/cEsQAEDLTJL8EQ+8oe12k3xPKVIBPOcs5WGYtuMAAADDM3vpP1TMpo+sFgLovru2pFeigNb7lFKk0n4MWGTOvh9txwGAdrHYDh5XiYCG54MvophNH3mQCtAPdy2MTSqh/d7kfhEKwHO0HQcA2sR52QCrN3vpP1TMBgDaPqGsknwVBbTebpJvSY5FASxA23EAoC0Us+FxlQho0MVL/+FWD8MwEcYFFqB/k8rDJJ9FAZ3wIck0uuUAz5tF23EAYPMuRACwci9eOLQlDACgI8ZJPooBOuEgpUhViQJYgLbjAADQPvsioCGv2ojcx2L21Hti8OwCAuiv4yRvxQCdsJ3SdvxEFMACzlIWrgEArJud2fD0vB6a8KqNyFvyo4esFgLot0mSP2P3FnTFu5SHQyNRAM/QaQ0AMAaBdlBnoUnT1/xjO7MBgK7e76soaENX7KUUtA9FAQAAtIxiNjykAy6tuc46MxsXWQC66m6n56UooBO2k3xJ6a5gvAYAALSFNuPw0EgEtOU6uyUQemhPBACDcZ2yQ/tcFNAZRyndFbQsAwAAgHYaiYAG2Zn9iCvvCwAY1GCoSvJZFNAZeykF7bEoAACADdLtDR43EgENsjP7ETPvCxdaEQAMzjjJRzFAZ2wnOU1yFm3HAQCAzXBsKTxuJAIa8uoNyH0tZms1jgstwDAdJ3krBuiUN/X4XdtxAABg3RSz4XEWndOU2Ws/QF+L2W5AADBckyT/TXIjCuiM3STfk7wXBQAAsEY2xsHj9kRAW66zdmbTV3b2AAzbWco52gra0C2fou04AAAAQF+8egOyndn0lQegANy1Lb4UBXTKm5QWVJUoAACAFbMxDh4yH6dV19m+FrOn3hsAQO4LYgra0C3bSb4lORYFAACwQjbGAbT8OrvV43C0FR22SgQA/DBg2k/yWRTQOR9SFqrqugMAAKyCYjY8VImABk1f+wH6XMzWHgQA+NE4yd9igM45SOmycCgKAACgYeoIAC3X52K2FVUAwM/eJ3krBuic7SRfkpyIAgAAAFZqXwQ05LyJD2JnNn11IAIAnjBJKWg7kgS65109zh+JAgAAeKVLEcCjHPVFUxrZeNznYvbMewQAeMIk5fwfBW3onr2Ugra24wAAwGvo7gqPszObpjSy8Vgxmz6zegiA5wZTVazEhi66azs+MeYDAABeSDEbnp5zQxNmTXwQbcbpM6uHAFhkvFBFQRu66ijJ1LgPAAB4ATUEeGgkAho0a+KD9LmYbVUVALDomKFK8lkU0El7KQXtsSgAAADgVUYioEGzJj7IVs9DssvKRRcAFnGdUghT0IZu2k5ymuQs2o4DAACLsTMbHhqJgAbNmvggfS9m253togsAyxgneSsG6Kw3KQ+ktB0HAACeo34AD41EQEMa23Dc92L21HsFAFjSJKWgfSMK6KTdJN+TvBcFAADwC4rZ8JBuZ7TuGmtnNn02EgEALzRJOUdbQRu661O0HQcAAJ6mzTg8pNMZrbvGbgmKHhuJAIBXjiOqJFeigM56k3I+UyUKAAAAgLWxM3tBM+8VAOAV7s7evRQFdNZ2km9JjkUBAADUzPPhcQcioCHTpj6QYjZ9ph0GAE24TtnV+VUU0EnnSf5KaTkOAABwN9cHoAPX2d8HENZVkl3vmUHaFgEADQ6+DlPO0j4SB7R+/H+WsgJ4Gg+pAACAx+f5wLxKBDSosaOgh1DMnkUxGwBoxrgeiH0SBbTGTUrR+q6APRMJAADwjAsRAKzMTZMfbAjF7Ivo8T9kVRrsyw8ASU5SVnCfigI25jLzu68BAACA13F0K01pdMHQEIrZ2oUAbRsQWPkJ3Tepf5ancawFrMNV5ndfG+MDAACv4fkcPLQjAhoya/KDbQ0gsKn3DNAid2fuAv2Y+FZpuG0O8D9fk/yV5I8ko5Q2/2dRyAYAAF7PvAIesjObpsya/GC/y5Oeq2JBA+1zlPJQ/tDAGTrvov55nibZEwe8ymXu24afiQMAAFghz+TgITuzacqsyQ82hGL21HsGaKGD+vpUGTxDLybAVUrx7UAcsLCbzJ97PRMJAACwJtqMw0MjEdCQWZMfbCg7s2/iPMuhspKINg+U9+qLemUADZ13V9CepHRfAB53nvud1+59AAAA0B67IqAhjT7z+X1AodkpNUzOeKBtft6FvZ37Hdoe6kP3jVMWqXwQBSRJrjK/+1o3EgAAYNMuRQAPjERAgxp9/jOUYvYsitlAe20n+Z7kbcquTqDbjuuxx6koGKCbzJ97PRMJAADQMhbZwkMjEdCQ86Y/4JCK2bgAQ9udprTGPxEFdN6kHn+cxVEn9N9l5ndfAwAAtJliNjzkyFZaa0htxhkmZzzQNtNn/vxTSnv8saigFz/vVf1fBW365Crzu689CAIAALpEvQAecmQrTZk2/QGHUsz2gA3okqOUlXBj1y/oxQR5VA/i9sRBh33NfQHbgx8AAADoFzuzaUrjNQ07sxmCUbSap3ve5H5Xp4I2dH8AV0VBm265zPzuawAAgL5QL4CH7MymtdfYrYEEpxA0bCMR0DI3C/69vZQigoEE9GMssp/ksyho8b3pc5K3Sf6vfr++j0I2AADQzzk6AB25xv4+oPDOkxx4DwEtcLHE9eiuoF3FqlHog3E9oHsnCloyPp6mFKzdYwAAgKFQzIaH1M9oSuPPmIZUzHaDGq79rODAeVij7fo9/D7JRBzQee/rQd2pKFizq5TC9bT+ZXwMAAAMkcW8AKtxtYoPOqRi9kXKGbQMz44I6IHt3Be+JuKAzpukFBIn9c83rMJN5s+9nokEAAAA+IljLmnKbBUf1M5sgM1c0F/atuU0peX4WIzQeWf1z/M0Cto05zL3xeupOAAAAB7MmYB5NgTSlJV0vvhdgAxAJQJaZvbKf39U/3csSujF+GQ/pfC4Jw5e4Crzu68t4AQAAHiaORM8ZGc2rb7GDqmYPfMeAnrkqB5kVAbh0IsxSpVSjFTQZhHnud95bcEmAADA4jxHg4fszKYpdma/0sx7yIUYemYvpZBx6BoHvZhMV0lOct99Ae7ctQ6fphSxAQAAeBkLguGhkQhoiJ3ZDbiMHU9D5DWnz4PmvfrjVQbj0IvB3rj+vYL2sN1k/tzrmUgAAACAFRmJgIZMV/FBh1bM1kIE6OO1aDv3O7Sn4oXOG9c/y6eiGJTz3BewLU4CAABYDfMteGgkAtpsaMXsaZIDL/sg7cRiBvptO8m3JG+TTMQBnXf3c3xS/3zTP1eZ331tnAIAALB65l7w0K4IaMD5qj7w77JlIPYfkDXXAAAgAElEQVRjxyrDGDSfpqykOxYzdN4kZcX4NArafXDXOnyaUsCeiQQAAGDtFLNh3o4IaPv1dWtgQU69l4AWWHU7ow+xOxv6dL2oklyKopMuk/yd5M96cniYstt+JhoAAICNzbOBe/sioO3XV2dmMxQjETAwR/X7/tC1D3oxEKxSFuXtiaPV7lqHT1N2X7v+AgAAAG1mZzZNma3qAw+tmG3V1XCNRMAAHaQUVKooqEDXXdc/yycpi1Voj/Pcn3ttrAkAANBeup7BQ3Zm05TZqj7wEM/MvorD7IHhXIv2Uoorh1Fkga67TjKuf6+gvTmXmd99DQAAQHfm1QCsxmxVH/j3gYapmD08Vhcx5GvRbu53aCtoQ/eN65/lT6JYi5vcF66ncd41wCoZqwIAq6SYDQ9VIqAhs1V94KEWsw+8pwbHuQ8M3XaS70neJpmIAzrvpJ6En4piJS5TitdnUVgBWCcPmAGAVTK/A1iNlR7jMNRiNsBQnaYs7jgRBXTepJ6IT1MWrPByV5nffa2YAgAAAAyBrrY0YaXP0oZYzLb6ygUZ2nIt2lSXiE/1z8TYywC9uJZUKUVYx6gs52vuC9gzcQAAAAxiDg3Ms0GCJkxX+cGHWMy208YFGVyLkqP6v+9dF6EXk/H9etC4J44nXWZ+9zUAAADD4hkYzLMJkE4YYjF76mUHSFIK2vspuzoN5qH7E/IqpfX4G3EkSW5yX7g+c50DAAAwdxYBzNkRAQ2ZrvKDbw001Bvvq0GqRAAP7NU3GqvwoB+T8sMknwecwXmSv5L8UU/IxikFfg8sAAAA0GYc5o1EQENW+uxtqMVsNy1g06Yt+loUtKFfxkk+DuR7vUryd5L/JvktZeHaibEeAAAAwLNGIqAhK30W9/tAQ7U7Z5i0zICnbacUtN+n7GIEuu04ySzJac++r5vMn3s981IDAACwgEsRwAMjEdCAlXfDtjObIbHrFH5tO6XwNRYF9MIkyZ/p/vEqlyk7ze9ahx/W39vMSwwAAMCCbHCDh0YioAErr7kOdWf2zHsLMIB+0mnK4o/3XibovGlK6+1pyoKVLrjK/O5rDxwAAAB4LXNLeEg3W5owW/UnUMzGhRk2o+0dIt7VPzNjLxX04nozSikM77X0a/ya+wK2cRoAAACrmBsD8/ZEQANmq/4EQy1mu3ENkzbjsJyj+uemitWr0HXX9c/yWZKDFnw9l5nffQ0AAADA+tj8R1O0GV8RRRmAxeylFJoOY7ck9GH8U6WcN3205s99k/vC9ZmxGAAAAGtmgxvMs/mPpqz8Od/vAw73MlooDM1IBLTMVZLdDnyde/WAvzLwh14YpyxO+bDiz3Oe+wK2awcAAACbZFE1wGrYme3mRYN2RUDLzDr0vtzO/Q7tqZcOOu+4vgadNvgxr3JfvJ4aawEAAAC0ViUCGmJn9gpN044zIwG6YjvJtyRvU9oUA902qQebk/rne1k3mT/3eiZSAAAAWmoqAoDGna/jk9iZzdDsR6tTeK3TlLb9x6KAzjtLWYk7zWIF7cvM774GAAAAoHucmU1nDLmYraA5TDsioGXXoa52iPiQUtAeexmhF9ei/ZQi9d5Pf3aV+d3XFgMCAADQNVcigAfUSmjCdB2fZMjF7Jn3GLBhXS8KHdWDnnEUuKAP46Iq9+3Cp/Uvi/8AAADow5wXmGdnNk1YS11AMZshXqCnYoDGvKl/pqooaEMfBp8mMgAAAAD9ty0CGrCWjTBbAw9Ze5Hh0ToDmreX+zbFAAAAANAmUxHAnJEIaMhsHZ9kS8gABtIN2K2/HwVtAAAAAID2GomAhszW8UmGXsx2DuTwVCKAldlO8j3lDG0AAAAAaIOZCGDOSAQ0YG3dr4dezHa+K0DzTqOgDQAAAEA7zEQAc0YioEvX1qEXs6fea4PjzGzapM8Lak6TTLzEAAAAAACtok5CE9bW/XpL1gzMnggY4sV+Q45SCtoGRwAAAABsylQEMGdfBDRgbZv17MwGYJWO6mutgjYAAAAAwOZ5VksT7MxeoxsRDM5IBLBWeykFbSv+AAAAAFinKxHAAzrY0gQ7s9foQgSDMxIBBtQbGSBNo6ANAAAAwPrMRACwEtN1fSLFbDczwDVoXbbrG9yhlx0AAAAAYO0qEdCAtXa9VsxWzB6ikQhgY7aTfEkyFgUAAAAAKzYVAUDj1tr1WjFbm/EhGokANu40yYkYAAAAAADWxjGQNOF6nZ9MMXvNgQP8ZMgLat4lmXgLAAAAALAiMxHAnB0R0AA7s/scOK1g5RFtMvQFNUf1ddggCgAAAICmzUQAc9RH6Ny1VTFbIWmIFM2gXfZSzi/yswkAAAAAsDqewdKE2To/mWJ2cS4CYEMsqCn26huglYEAAAAANGUqApgzEgENmK3zkylmF4pJw3IgAlrEUQf3tusJRiUKAAAAAIDG7YqABszW+ckUswvFJIB22E7yLclYFAAAAAC8wpUIYM5IBDTgct2fUDG7sDMboF1OkxyLAQAAAIAXmokA5oxEQAPWXlNVzC7szB6eSgQYVLfehyQTMQAAAAAAvNqOCGjAdN2fUDG7mIkAcP1ppaMkZwZaAAAAACxpKgKYsy8Cukgxu5iJYHAUxqA73tSTDz+3AAAAAAAv4/kqTZiu+xMqZt+7FMGgWIEE3bKXciSEn10AAAAAFjETAczxbJUmODN7SOED1CymWcxuyqovgy4AAAAAnjMTAUDjLtb9CRWz701FMCgjEdAiFtMsbru+Xo9FAQAAAACwsAMR8EpXm/ikitkM1UgE0FnbSU6joA0AAADA06YiAGjUbBOfVDHbjQ2gq06TTMQAAAAAAPBLjm6kCbNNfFLF7Hva/A7LSAS0yFQEL3aUUtDeEQUAAAAAtSsRwBzPT2nCbBOfVDH73oUIBmVXBNAbRykLAgzIAAAAAEg2VHCBFrMzmyZspJaqmD3Pai2AbtpLKWiPRAEAAAAAMMdGIJqwkS7XitnzZiIYFCuRGPQNoIf2UlaG+dkGAAAAGLapCGDOSAQ0wM7sFpiJYFCsRGLQN4Ce2q4nK4eiAAAAAABIophNM+zMboGZCAA6bzvJlyRjUQAAAAAM0kwEMGckAl7pfFOfWDF7nt2Rw1KJAHrtNMmJGAAAAAAGZyYCmLMrAl5pY8elKma35IUADK5ZiXdJJmIAAOiMKxEAAECjHLlKEza2IVgxe95UBMAGzESwUkf19d2gDQDA2BgAGIapCOB/9kVAA+zMbpEbEQxGJQIYjIMoaAMAAAAAw+OZKE2wM9uLAcCK7aXs9LESEQAAAKC/HFsC8zwPpQmzTX1ixeyHnJs9HFYj0SaXIliL7ZQd2pUoAAAAAHppJgKA/lxbFbMfsjN7OPZEQItYSLM+20m+JRmLAgAAAADouUoEvNJGO14oZj80EwHAIJwmeS8GAAAAgF6ZigCgUbNNfnLF7Ja9IKzdSAQwaJ+STMQAAAD8P3v3ely3laYL+K2u+b85EQgTATkRaGdgnghIRWB1BO2JwOoISEfQ6ggGjMBkBAeM4JAZnB/YJC1bF1z2BVjreaqmNDUey8BLCbcX3wIAQKF8M5u5TrqqtTJ7YT8Qjq4RAQvRiuBkrpJ8TnImCgAAAIDV60QAX9iIgJlO+plUZfbCfiAAnMRP6V8oUGgDAAAArFsnAnhlKpt9aE/5H1dmf92DCBzIgeqc707KjgsAAAAAQAkM77B6yuyvM53tQA6OO3VSaAMAAACsWysCeNWIgLUfV5XZTnbAMtyLYDE2u/PAtSgAAAAAgBVrRMBMz6feAGX215mQrIfpS+BrNkluotAGAAAAWJNHEcAXGhEw08kH8ZTZC/3BcDSWGQe+5ybJrRgAAAAAVqETAXyhEQEznXwAWJm90B8M4EKbxbiKQhsAAAAAWB8DfcxlMtsPhhN7LwIWohPBol3tzg0u/gAAAACWqxUBfOFcBMzUnXoDlNnf5tsaAPz5wq+NpXkAAAAAgOUzmMM+dKfeAGX2gn84OKADi3OefkL7QhQAAAAAi9OJAF55hsk+WGZ8wVoROKDDkT2IYBU2u3PEpSgAAAAAFqUTAcBePZ16A5TZ3/ZLkjsxADWdFBhsk+RfSa5FAQAAAAAs0FYEzLSIATxl9vddxqRkDSwzDkx1k/7lJwAAAABOrxUBwN4sYgBPmf3jH9I2yaMoimaZcZwYmOMfSW7FAAAAAAAsiO6DudolbIQy+8ee0k9oP4sCOLB7EazW1e7EbqUHAAAAgNMwlAZf8qySIiizh7mPbwuUrBEBsAfvo9AGAAAAOJVOBPAFk9nM1S5hI5TZw90n+SCGIjUiAPbkfHfj5EIRAAAAADiljQiYyTezV+g2Cm3gcDoRFHOR2EahDQAAAHBMrQjgVSMC9mARn0ZVZo93m+Q3MRRF4cRSdCIoxibJ70muRQEAAAAAHFkjAmZ6XMqGKLOnuY5CuySW2gAO5SbJRzEAAAAAHFwnAnjViIBSjqnK7Ok+JnkQAwA/8Gv6VT0AAAAAOJxOBPCqEQGlHFOV2dM9JdlGoV0KS42zBPciKNZVks9JzkQBAAAAAByY55DM1S1lQ5TZ8zwluUzyLAoHdtjTMYVy/ZSkdbwBAAAAOIhWBPDKAB9zLWb4Tpk9X5d+QluhDcCPnO9urFxMAgAAAACHYqCGuRYzfKfM3o/7JNdiWLWtCIAjUWgDAAAA7NejCOAL5yJgpnYpG6LM3p/PST6IAZjpTgRV2OwuBq5FAQAAADBbJwKAMimz9+s2yf+IYZUsuQEc2ybJTRTaAAAAAMD+bEXATIsaulNm798vSX4Tw+pY7hc4lZskn8QAAAAAMFkrAoC9eVrSxiizD+M6lgoGCjhJcDQ/p1/dAwAAAABgDsN7zHW/pI1RZh/OZZIHMayGZcZxkuDUrnY/f8cjAAAAgHE6EcArzxeZy2R2RT/obZJHUazCuQiAhRyL2iSNKAAAAAAG60QAr0xmM5fJ7Io8pZ/QfhYFAAOd7y4WXHQCAAAAAGOZzGaubkkbo8w+vPv0E9osXyMCnCRYiE36CW3nDwAAAIAfa0UArxoRMFO3pI1RZh/HfZIPYnCAh7WdJDipTZL/TXItCgAAAABgoHciYIaHpW2QMvt4bqPQBmC8myS/iAEAAADgqx5FAK8aETDT09I2SJl9XLdJfhPDYvk+LbBU/9idQwAAAAD4UicCeNWIgJnul7ZByuzju45Ce6nORIATBQt2lf77T45VAAAAAMDXeHbIXCazSZJ8zALXnAecKFi891FoAwAAAPxRKwJ4ZQVaijumKrNP4ynJNgrtpdmKAFiB8/QT/C5MAQAAAIA/MgRDcZTZp/OU5DLJsygAGOld+jfkFNoAAABA7ToRwCvPC5mrXdoGKbNPf5LdRqENfOlOBAywSfJ7kmtRAAAAABXrRACwF4vsK5XZp3cfRcRSvBcBsEI3ST6KAQAAAACqp+dgjvslbpQyexk+J/kgBgAm+jXJrRgAAACACrUiANiLbokbpcxejtsk/yOGkzsTAQvwJAImuNqdSxzHAAAAAKA+vpfNXN0SN0qZvSy/JPlNDA72VO9eBEx0lf5tZIU2AAAAUINHEcArzwSZq1viRimzl+c6yZ0YAJjoPH2h7eUcAAAAoHSdCOCV54EUeUxVZi/TZZIHMZxEIwKgAAptAAAAAKiLyWzmWuSqscrsZXpKso0lUk6hEQEL0ImAPdikL7SvRQEArEgrAgDAtQNM0oiAmZ6WuFHK7GX/gblM8iwKqE4nAvZkk+QmCm0AAAAAKF0jAmZY7IrRyuxlu08/oY2DPcAcN0k+iQEAAAAoTCcCeNWIgBmelrphyuzlu0/yQQwO9gAz/ZzkVgwAAABAQToRwKt3ImCGdqkbpsxeh9sotKEm9yLgQK52f77ORAHAd1zEJyoAAADWxPM+5jKZzWy3SX4Tw8FdiAAnDQp3nv4tOxe4ALxo0pfXn3fXIb9HmQ0AwDq0IoAkug3mW+yQ3X/42azK9e7XK1EczEYEQAXO0y/DtY2VAABqdbk7D1zGUnQAAABrZ3CFuRY7ZKfMXp+P6d+wORcFFO05Xq7gsDbp316+jLeYAWpwkbfy+r04AAAowKMI4It7PphjsUNPlhlfn6f0D6EeRHEwWxHgxEElNkn+N5aSBSjR2e74fpt+NY7fk/waRTYAAOXoRACwF4t+Ochk9jo9pZ+ouI/JTQDmu0n/vdRfRAGwatu8TV9byQkAAKCu+0GYqlvyximz1/0Ha5t+aViFNgBz/SN9oX0tCoDVaPJWXm/dFwAAUJlWBAB70S154ywzvm73UTocwlYEOHlQqaskn9MvTQvAMl0m+bS7Vvi/6VfX+CmKbAAAgJr5ZjZzdEveOJPZ6/c5yYf0D7EAJw+Y66f0bzZv03/WAoDTusjb9LXvXQMAwJtOBPDKC87Mcb/kjVNml+E2/UOun0WxFyYSgdqd7y5gLpd+IQNQ6LXoy7Lhl/FAAgAAvqUTASQxlc18ix5qUmaX42P6B19XonDgB9iDd3mb0FZoAxzWNm8F9rk4AAAAGMGAHnO1S944ZXZZrpM0sfwglEB5yBJskvye/nMWt+IA2Jsmb+X1NqavAQBgilYE8HqPCcVSZpfncncSN9HhwM+6+VYxS3Kz+/VWFACTnOWtuL5Mv/oFAAAA7EMjAma4W/oGKrPL85T+IVkXEx5TebgI8Fc3u/PLtSgABrnIW3lt5SQAANivRxHAq0YEzLD4wTpldrl/8LbpJ7QV2gDsy9Xu14+xegDAn53lbenwS9fhAABwUJ0I4FUjAmZY/CdPldll/+Hbpv/WKdMO/i6IOKVWBCzUVd6mDRXaQO22eSuwfeYHAACAUzgTATN0S9/Av/kZFe0+yQcxTNKIAOCbztO/cHEhCqDCa8SPST6nf6Hnf5P8HEU2AAAcWysCeOWelDm6pW+gyezy3aZ/K+dXUQCw54vkNv004r04gEKd5cvp63ciAQAAYGH3rTBHt/QNNJldh09JfhPDKKYNWYJnEbBwm/SF9qUogMKuA3/ZHd/+X5J/pf/EgiIbAACWoxMBvN7DQtHHU5PZ9bje/XolikG8zcQS3Cd5LwYWbpO+6PmQfjUQgLVp0k9db9O/nLMRCQAALF4nAoDZHtawkcrsunxM/5aO7ycAsG83u3PMR1EAK7DN29Lhro0BAABY8/0tTPW0ho1UZtf3h3KbfslED+2cAAD27ef0K1tciwJYmCZv5fVP4gAAgNVrRQAw2/0aNlKZXZ+n9CVDG0sowtJ1scw463OVfkJ7m5W82QcU6SxfTl/73jUAAAAl8s1s5jCZzWLd521CW6H9db6ZzRJ0ImClznfnmG0U2sBxb+BfymsvgwEAQLkeRQCvdBnM0a5hI5XZ9bpPP6H9L1F8lWXYAeYfR7v0pdK9OIADaPLl9LWXNAEAoA6dCOCVyWzmMJnN4n1O8iHJjSgAOIBN+rf7LuNbVsB+vBTX23j5EAAAALzYzRy+mc0q3KZ/c+dnUfzFWSyPixMJ7OOC+n/Tvzx1Kw5gpIu8ldc/iQMAAIgX5uFFIwJmeF7LhiqzSZKP6YvbK1F84cKFESfmZQpKcrM713wSBfAdZ/ly6fB3IgEAAICvakTADKsZplNm8+J6d+B7LwoADuTX9C8KXYsC+IOL9OX1ZSwdDgAA/FgnAkiizKaSY6kymz96+aaph4hOBACHcpV+8vI6Vh+Amq+xtnmbvvZ9LwAAYIxOBPB6fw3FH0uV2fzRU/oHil08VHQiYAlaEVCon3Z/vrdRaEMtXorrbbw4CQAAAPtwJgJm6Nayocps/uyl0G6j0AbgcM7Tf5flMiv6Pgsw2EXepq99xgYAANinVgTweu8NU3Vr2VBlNl9zn/7h4+9OBAAc0Lu8TWgrtGHdzvLl9PU7kQAAAMDB78VhqtU8j1Vm870/xB+S3DgRwEk9xyoJlG2TvtD+mORWHLAq27xNX1s6HAAAOIZHEcAr9+LMsZrPPyqz+Z7b9IXur6KAk7mP5Vkp3yZvL0/digMWq8lbeb2Nl60AAIDj60QAMNvdmjZWmc2PfEq/3PZVhftumXGA47qJMhuW5qW4voylwwEAAGAptiKgFspshrje/VpboW3aCACozUXeymsrgwAAAEvTigCgrmOpMpuhPqZ/uOkbDHBcXZQJ1OUi/fL6wHGc5W36ehvT1wAAALAGVpZljqc1bawymzF/sLfp39aoqdB+2Wc4lU4EVOZMBHCU65uXAtuLigAAwJp0IoAknqExz6qGiZTZjPGUfsnxNpbgBgBYiyZfTl+7jgMAANaqEwEkMZnNPCazKdp93qaVa3gQ6u0mAGCN1y/bvE1gWzocAAAAyrv3h6lMZlPFH/LrJP+qYF8vknz2I8dJBYAVXLNs05fX78UBAAAUqhUBJOlXYYMpHte2wcpspvqc5EOSG1HAQT2JAICvOMvb0uGXsXQ4AAAA1MQqbEzVrW2DldnMcZt+CujngvfRUh0Ax9WIAL5pm7cC+1wcAABAZR5FAEk8P2Oe1a0Gq8xmro/pC9+rQvfvwo8YwMU4nPDvw0t5vY3pawAAoG6dCCCJ52fMs7rVYJXZ7MP17uDp+4ywf60IAKpxlrfi+jKWDAMAAAD+yoqyzGEym2pdpi/dSlvysvGjBQAO6CJv09deDAQAAPi2VgSQxIqyzGMym6r/8G/TL/VS0hKYJqIAgH1q8uX0taXDAQAAgDFMZjNHu7YNVmazTy+FdhsPZmGfHuPFCoA12+Zt+vpcHAAAAJN0IoAkJrOpjDKbfbtP/6D298JODPd+tJz4Ql2ZTS28WUoJmryV1z+JAwAAYC86EQDMcrfGjVZmcwj3ST4kuSlkfxQrAMfjzVLWeq2wzVuB7QUkAAAA4FDei4CJnta40cpsDuU2/YPdX0UBABToIm/ltZtIgP2xKhYA8C2tCADqu99SZnNIn9I/6L1a+X5cuFBiAScYRQnAaTXpi+tt+hJ7IxKAg3gSAQAAfJNVDZmjW+NGK7M5tOvdr2sutC0zzql5oAdwGi+T19sk5+IAAAA4mUcRQBJ9BfN0a9xoZTbH8DH920IeAgMAa3CR5HcxAAAALEYnAkhiMpsKj6V/83PjCJ7STzQ9rHT7t36EAFAVbzkDAAAAS+SZBXN0a9xoZTbH8pR+yfFnUcBorQioiO/Ds5TrFgAAAJbjXgSQJGlEwERrHThVZnP0C45t1ldoe9MJAOq7ZgEAAGA5vHQMvUYE1HYcVWZzbPfpv6G9Jr71DQAAAABwOsps6DUiYKLVDm8oszmF2yQfxAAu1gEAAABgACtoQe+dCJjIZDaMdJvknyva3saPDBfrAAAAAACciE+iMke71g1XZnNKH5P8tpJtbfy4AAAAAABOwrAHJBciYAaT2TDRdZIHMQDgwpyFeRQBAADAYvgMH5jMZh7fzIYZtll+od34MXFiShVcmMNxdSIAAABYhGcRQBIDIFR6HFVmswRP6QvtJf9lavyYOLFOBAAAAABUyBLjABUfR5XZLMUaCm0AAAAAAIBT2IqAibo1b7wymyW5T3K50G2zfAcAAAAAwPGZzAaYp1vzxiuzWZo2yYcFbpfvt+KiHQAAAACO70kEkMTQHdNZZhz27DbJ38UALtqpViMCXOQDAACw47kY9DYioMbjqDKbpfqU5LcFbc97PxKAo2lEgIt8AAAAdrxsDKayqfg4qsxmya6T/FsMAAAAAABAxXwKlTlMZsMBXSd5EAOkFQEAAAAAFTKZDVYyZLq7te+AMpule0qyzTIK7a0fBwAAAADAUfkMFCizqZgym7VcrFwneRYFAAAAAEA1PBOGXiMCJmrXvgPKbNbiPv1k9CkvXnyTglPyBio1cbzFhT4AAACJJcbhRSMCJlp9t6DMZm0XLh9P+N+/8CPAhTs43gIAAADAkRn+YKrVdwvKbNbmNskHMQAAAAAAFM+AB/TORcBE3dp3QJnNGt0m+ecJ/ruN6AEAAAAAjsan98BUNvN0a98BZTZr9THJb0f+bzZi58QeRQAAAABARZTZ4JN8TFdEp6DMZs2ukzyIgYp0IgBwzAUAAKiIZcYBputK2AllNmu3zfEK7UbcAOBiHwAAAOCItiJgoiJeCFJms3ZPuwP58xH+W+/EDXAU70UAAAAAxGQ2wBxFfKpBmU0pfxm3OU6hDS7eAQAAAOA4fDMbfDOb6Uxmw8L+Ql46aeDiHQAAAACKYHgJemciYCKT2bAwbZIPThoAAAAAAKtnlULoGbJjqraEnVBmU5rbJH8XAwCwBw8iAAAAAE5sIwImKGZ1C2U2JfqU5LcD/d5b8XJCrQgAjsrnHQAAAE7HZDYkjQio/RiqzKZU10n+LQaA1bJ8EgAAANTNC8agzMYxVJlN0a6z/+VBfTMb4DgcbwEAAKBuymxQZjOdyWxYycXONvsttE0KckqdCAAAAACohGXGQZnNdF0pO6LMpnRP6Se0n0WBkw8AAAAAACti9UKm6krZEWU2NbhPP6G9j0LbiQMA6tGKAAAA4GRMZoPVYpmuK2VHlNnUdOHzcQ+/z7koAQAAAAAOzjezwYAd03Wl7Igym5rcJvkgBlbuQQRUohEBAAAAVMtnI6FnwI4piuoRlNnU5jbJP2f+Ho0YOSFvpFILx1oAAAColyXGAaYrqkdQZlOjj0l+m/HvNyIEAAAAAAAOaCsCJmpL2hllNrW6juWaAYDv60QAAABwEiazAUiizKZu20wrtC9Exwm1IgA4mk4EAAAAJ+FTe6CLYLq2pJ1RZlP7BdE2yfPIf+9MdAAAAAAAB6PMBl0EjqFJlNkwtdAGwMU6AAAAcBiWGQeT2TiGJlFmw8tf6ksnEFbCW6m4WAcAAACA8hn2YIrihjeV2dBrk3xwAmEFvJUKAAAAQOk8A4OkEQGOn8ps+KPbJH8XAwBQ6sU/AADASlidEJJ3ImCCrrQdUmbDlz4l+e0H/z/vxQQAVfDwBAAA4PieRQCmspmsKwtJEGYAACAASURBVG2HlNnwV9dJ/i0GnIgAAAAA4OiskgXKbBxDXymz4euukzx855/7bjan0okAAAAAAKBoOgimKm6lQWU2fPsv+zbJ4zf++YWIAA7KJx0AoN57MQCgbiazQQeBY+grZTZ821OSy/hGCwAAwLF4eA0AeLkNTGbjGPpKmQ3fd59+QvvZiYQFeRABwNHciQAAAOColNlgMptpinyOpcyGH7tP8tGJBBf0AAAAAHBwVmoBmKbI7kCZDcPcJvkgBgAAAAAA4MDei4AJinwZSJkNw90m+W33vzfiAAAAAADYO5PZANOYzAZynb7QbkTBCbUioBI+6QAAAAD18Yk9aueZGFOZzAaS9IW2twMBDu9MBCyAhygAAADH8ywC8EyMyboSd0qZDdN8FAEAVMELbAAAAO7B4JhMZjNVV+JOKbMB1seUIAAAAABAmUxmM8VjqTumzAZYH2+oAgAAAFAiz70gaUTABF2pO6bMBgAAAAAAlsCKhKDMZppiXwZSZgMALtwBAACAJVBmg2diOH5+QZkNsD6dCHDhDkdjiTsAAAD3YHBM70TABG2pO6bMBlifTgQAR2MqAAAAADiWMxHAl5TZAAAAAADAEpjMpnYXImCittQdU2YDAAAAAABLYHUsamcymymeS945ZTbAOj2IAAAAAICCPIsATGYzSdGrWiizAdbJW6rUwJuoAAAAUA9LjANMU3RfoMwGAJbKm6gsQSsCAAAA4Ei2ImACk9kAAAAAAAAHZDIbYJqu5J1TZgOsUysCAAAAAAris3pgpUKm6UreOWU2AAAAAABwaspsSDYiYALLjAMAAAAAAByQZcapnalspir6ZSBlNsA6dSIAOJpnEQAAAAAHdiYCJngofQeV2QDr1ImACrwXAQthOgAAAMC9FxxaIwImKP4TDcpsAAAAAADg1Hwzm9o1ImCCtvQdVGYDAAAAAACn5PNOoMyGr1JmA6yTZZcAAAAAKIVnXaDMZpq29B1UZgOsk2WXAAAAAADKcSYCJvDNbAAAqFwnAgAAgIMymQ3JuQhw/PwrZTYAsGQXImABOhEAAAAclFUIqZ2pbKZ4rGEnldkA63UnAlzIAwAAAAVQZlM7Ax1M0dWwk8psAAAAAADglCwzDjBeV8NOKrMBAAAAAADgdLYiYIKuhp1UZgOsl+WXAAAAACiByWwAx86vUmYDOFEB8H2tCAAAAA7K0Aa1881sHDu/QZkNACxZIwIAAAAo2rMIIGciYAKT2QAAJ9aIAAAAAIpm9UEwmc00JrMBWLROBAAAAAAAq7cRASPd1bKjymyA9epEAAAAAMDKmcymdo0ImOCplh1VZgMAgJsDAAAA91xwGo0ImKCaF4GU2QAA4OYAAADgVJTZ1K4RAY6d36bMBlgv5QoAAAAAa+cZF7VrRIBj57cpswHWy1ur1GArAgAAAAAKdiYCJuhq2VFlNgAAAAAAcComs6ndhQiYoKtlR5XZAAAAAADAqVh9kNqZzGash5p2VpkNsG53IgA4ikcRAAAA7N2zCCDnImCkql4CUmYDAMCPdSIAAADYO0uMAzh2fpcyGwAAAAAAAI5vKwImMJkNgJMWLMSFCAAAAKBYJrMBxmtr2lllNoALfliyjQgAAACgWAY1qJ1BDvgBZTYAAAAAAHAKymxqdyYCJmhr2lllNgAAuEkAAAA4BasOUjuT2Yz1XNsOK7MB1q0TAQAAAADAKpnMZqzqXgJSZgOsWycCAAAAAFbKZDa1a0TASF1tO6zMBgBc1AMAS3InAgCohm9mU7t3ImCkrrYdVmYDAEvXiAAAAACK8ywCKteIgAm62nZYmQ2wbpZiAjgO0wIAAAD75bkWtWtEwARdbTuszAZYN+UKwHF4yAIAAADs05kImKC6Z1TKbAAAAAAA4Ni8NEztLkTABNUNuCmzAQAAAACAY7PiILUzmc1YDzXutDIbYP3uRIALewAAAGBllNnUzmQ2jpsDKLMBABf2AAAAwLFZZhxgnLbGnVZmAwDAj3UiAAAAAPbovQgYyWQ2AE5gAHxVJwIAAIC9MpkN4Lj5Q8psACcwAAAAADg2AxrUzGf1cNwcSJkNAAAAAAAc07MIqNyZCJjAZDYAAAAAAMCBWWmQ2pnMZqzHWndcmQ3g4h+WbisCAAAAAApiMpuxulp3XJkNsH6+LwRwHA8iAAAA2AvDGdSuEQEjdbXuuDIbAACG8fIQAACA+yvYh0YEjNTVuuPKbAAAAAAA4JiU2dSuEQEjVbuihTIbYP1aEQAAAACwIpYZp3bvRMBI1b4EpMwGAAAAAACA4zgTARO0te64MhsAWLoLEbAQlsEDAADYD5PZ1MyzLhhBmQ1QhmcRULCNCFgID1sAAAD2w8vC1MxkNmPd1bzzymyAMihYAAAAAFgDQxnUzmQ2Y1X9ApAyGwAAAAAAOBZDGQCOm4MpswEAAAAAAOA4tiJgJJPZAKxeJwIAAAAAVsBkNoDj5mDKbIAydCKgcI0IcKwFAAAowpMIqJxvZjNWV/POK7MBgDVoRIAbBwAAgCIos6ndRgSM1NW888psAAAAAADgWCwzTs1MZTPWQ+0BKLMB3AQAAAAAAHB4ZyJgpOpXs1BmAzihAQAAAMCxGMqgZo0IcMwcR5kNAAAAAAAci6EMataIAMfMcZTZAMAaWIKJJTA9AAAAMM+zCKhcIwJGamsPQJkN4IQGa3AhAhbA9AAAAMA8XhKmdo0IYBxlNgAAAAAAABye1QcZq609AGU2AAAAAABwDCazqd25CBjBpxmizAZwYgMAAACA4/D5JmpmKpuxvAAUZTaAExsAAAAAHIcym5pdiICROhEoswEAYIw7EQAAAExmGANguE4EymwAYB22IgAAAABgxbYiYKROBMpsACc2AAAAADgOk9kAw3UiUGYDOLEBAAAAwHH4ZjY1881sxvICUJTZAAAAAADA4T2LgMqdiYCRvAAUZTYAAIzRiQAAAGASE4bUzmQ2Y9yJoKfMBnBDAMBwnQgAAACACTYigPGU2QDlsOQIJfPmKgAAAKybQQxq1oiAkVoR9JTZAMAaeHMVAAAA1s0gBjVrRIBj5jTKbAAAAAAA4NAUM9SsEQEjWc1iR5kNUI5WBAAAAAAslGKGmjUiYCQvAO0oswEAYDgPXwAAAICxzkTASJ5B7SizAQBgOG/FAgAATNOJgIpdiIARHkXwRpkNUJZnEVCwRgQAAACwWp0IqJjJbBwvJ1JmA5TF0iOUrBEBAAAAACt0LgJG8Jz/D5TZAAAAAADAId2JAGAwn7n7A2U2AAAAAAAAHMZWBIxkMvsPlNkATnIADNeKAAAAYLROBACDmcz+A2U2gJMcAAAsiRc0AaA8nQio2IUIGKkVwRtlNgCwFmciAIAqeEETAICSeKYFMyizAYC18BYrAAAArFMrAirmmRZj3IngS8psADcGAAAAAAAchslsxrBS1Z8oswEAYJxHEQAAAIzSiYCKNSJghHsRfEmZDQAA43QiAAAAcB8FA70TAY6X0ymzAcpiCRIAAAAAgGVoRMBInQi+pMwGKIslSAAAAABYkjsRULFGBIzUieBLymwAYC22IgAAAABgRc5EwEidCL6kzAYAAAAAAA6lEwEVuxABIzyI4K+U2QDleRQBwEH5pAMAAMBwnQiomMlsxngSwV8pswHcIADgxgIAAADYP5PZjGGA4iuU2QAAAAAAwKG0IgAYxADFVyizAQAAAAAAYP/ei4ARWhH8lTIboDyWIqFUlmUCAACA9elEADCIyeyvUGYDOOHBWmxEAAAAAKvTiYBKGcxgLINqX6HMBgCAcVoRAAAAAD9wJgJGeBbB1ymzAQAAAACAQ7gTARUzmc0YprK/QZkNUJ5WBAAAAAAAJ2UymzE6EXydMhsAAAAAADiETgRUrBEBjpfzKbMBADcBAAAAwCF0IqBijQhwvJxPmQ1QnicR4CYAHGcBAACAk2pEwAidCL5OmQ1QnnsRADjOAgAALEArAir2TgSM4HnTNyizAQAAAAAAYH/ORMBIVgL8BmU2AAAAAABwCJ0IqNSFCBjhTgTfpswGKNOjCAAAAAA4sU4EVMpkNuyJMns9bkUAuFEANwIAAAAALJ7JbMZoRfBtyuz1uEpyLQYA3AjAIjyIAAAA4LssmwswjO9lf4cyez0ektxEoQ0A4CYDAAAAWLKtCBjhXgTfpsxej5cHpgptwMkPAAAAgKXrRADgeDmXMns9/lhMfYplVoHvMzEIAAAAwCl1IqBiOhwcL/dEmb0efyymNuk/Bu9gCAAAAAAAsCwbETDQowi+T5m9Hu1XDoRtFNoAAAAAACxPKwIqpbdhjE4E36fMXrdNktskZ6IA3CxQia0IcJwFAAAAFkxnwxj3Ivg+ZfZ6tN/4v5/v/pmDIwAAAAAAS9GJgEo1ImCEJxF8nzK7DAptAAAAAACWpBMBlWpEwAgms39Amb0ud9/5Z+dJPokI2PE2FwAAAADA8TUiYATP8n9AmV2Wq/Tf0AbwNhcAAAAAp3InAirWiIARWhF8nzK7vD/QCm0AgMPz1iwAAADwNT4Jy1DPIvgxZXaZrpJ8FAMABboQAQthBQwAAIBv60RAxc5FwECeLw2gzF6XdsT/769JrkUGVXsQAQXaiAAAAAAWrxMBlTKVzRhW/htAmV22myi0wYkQAAAAAIBjsKogY5jMHkCZvS7thH/nxsETAAAAAIAjakUA8EOdCH5MmV3PhYNCGwAAAAAA4HC2ImCETgQ/psxen7sJ/84mCm2oUSsCgIOxDBQAAMC3dSIAcKzcB2V2PTZJPic5EwUAK9eIgAV4EgEAAMA3dSKgUoYKcazcM2X2+rQz/t13u39foQ3AmjUiAAAAAGCB9C8M9SCCYZTZ9TmPQhtqYWoQAAAAgGO7EwEVM5nNUJ7fD6TMXp92D7/HeZJbUULxfM8VAAAAAOB4NiJgoFYEwyiz6/VTFNoAAAAAAOxXJwIq1YgA9k+ZvT7tHn+vqyi0AQCmsnQeAADAX3UioFKNCBihFcEwymyukvwiBnDjACtyJgIAAAAAFqYRASP4ZvZAyux12vcU0D+SXIsVitOJgEJdiAAAAAAWqxUBlWpEwAj3IhhGmc2Lmyi0AQAAAAAAprCaIEM9i2A4ZfY6tQf6fW+SbMULAAAAAMBEnQiolNUEGcpU9gjKbP7sswMuFOVBBAAH49tGAI6vAMBfdSKgUiazcZw8AGX2OrUH/L03u99foQ1l8CAQ4HC8RQvg+AoAAC/ORcBAnQiGU2bzNS+FtreIAAAAAAAY6k4EAD/kBd4RlNnr1B7hv6HQBmCptiIAAAAAYEG2ImAEK6qOoMzme86j0Ia1a0UAAAAAwJF0IgD4IZPZIyiz1+tYy7WcJ/ksbgAAAAAAfqATAZW6EAEjmMweQZnNEO+T3IoBAOALnQgAAACAWOGW4e5EMI4ye73aI//3rqLQhjXyhhfA4XQiAAAA+EIrAiplMhsORJnNGFdJfhEDrIpvbwAAAAAAHJbJbIZqRTCOMtsf9rH+keRa/ACckDddAQAAYJk6EVCpRgQMZDXVkZTZTHEThTYAp7MRAQAAACxSJwIq9U4EDGQ11ZGU2evVnvi/f5Pk0o8B3EAAAAAAAFSsEQEjdCIYR5nNHLex1Cs4MQLUqxUBAADAqzsRUKlGBIzQiWAcZbaLgzk26R/iKrQBAAAAAIAanYmAgR5FMJ4ym7leCu1GFAAAAAAA1epEQKUM/OE4eUDK7HVrF7IdmySf4+0jWKoHEVCgRgQAAACwKJ0IqJRuhKHuRTCeMpt9OU9frjtow/I8iYACNSIAAAAAYAFMZjOUZ/UTKLPXrV3Y9pwvcJsAAA7pWQQAAABJPBsGcJw8AGU2+3ae5FYMAEAlLA8FAAAAdXsvAjgcZfa6tQvdrqsotMGxAgAAAICadCIA+K5WBOMpszmUqySfxAAAAAAAUIVOBFTI97IZyqfqJlJmr9/dgrft5yTXfkQAHMCZCAAAAAA4Mc+oGMqn6iZSZnNoN1Fow6k9iYACeesVAAAAluNOBFTKMyqG8px+ImX2+rUr2EaFNpyWN74ADqcTAQAAAFTLZDZDeU4/kTKbY/kUbygBAOXpRAAAAODeiGo1IsBx8rCU2evXrmQ7N7ttVWgDAAAAAJSlEwGVakSA4+RhKbM5JoU2OEkCAAAAAJSiEQEDWWZ8ImX2+rUr295Nktv4jgQcUycCAAAAAA6oFQGVeicCBnoSwTTKbE7hfHdxo9AGYKqtCAAAAAA4IR0HQz2IYDpldhnuVrjNCm0AoASWiAIAALAyIHXySVWGMpU9gzKbUzpP8kkMcBR3IgBwMwIAAHAgnQiokGE9hmpFMJ0y21+CU7tK/w1tAAAAAACAtTCZDUegzGYJFNoAAAAAAOtkRUCA72tFMJ0y21+CpbhKcu1HCQdjGVwAAAAAgP3ZioCBPJ+fQZnNktxEoQ2Hci8CCmMZJ9yMAAAALEMnAoDv8nx+BmV2GdqC9kWhDcAQGxHgZgQAAODkHpN8FgOVMmzB0OMkMyizWaJPTgIAAAAAAIv0mOSfSf47SRNlNvUybMEQnQjm+Q8RFOMuyfuCTgBt+u9NmHYCJ0wAAAAATutlAvs2ntlCYiCP4ToRzKPMZqkU2uCECQAAAMDpKLDh285EwECdCOZRZpejTTmT2S82u4uliyRPfsQAAAAAAAelwIZhGhEwkGPpTMpslu5d3ia0FdoA/PmmoRMDC/C4u2YBAABY6z2NAhvGaUTAQLqtmf4mgmK0Be/b+W7/LNsB07kRwU0DHE4nAgAAYGUek/wzyX/v7q8/xvMjGKMRAQM5ts5kMpu1OE//ZuClKGASb38BAAAA1O0h/QT25yhXYK5GBAzk2fxMyuxytBXs40/pC+1rP24AAAAAgB96SP9M9XOsKgX7ZCVZhrgTwXzKbNbmavfrtSgAAAAAAP5CgQ2Hdy4CBjCVvQe+mV2WWt7wuEr/DRfAMQIAAACAvsD+e5L/SnKR5FMU2XAoprIZyicd9sBkNmv1a/o3Wm5FAeDGARZwY/JeDAAAwJGZwIbTuBABA5nM3gOT2WVpK9vfm1huHMCNA7gxAQAA6mECG2A9TGbvgcls1u5mdzBwQIAfU7YAAAAArI8JbFiWrQgYyDF7D0xml6WteL9N58GPeekDAAAAYB1MYAOsn+P2HpjMpgSb9IX2Nso6AAAAAGCdTGDDOhiuY4hHEeyHMrssbcX7/lJoN7GUMgBwXK49AACAqf6dvrz+7N4CVuNMBAzQiWA/lNmU5I8T2i78wMkT4FisDAMAAIyhwIZ1M5nNEJ4X7Ykyuzx3Sd5XvP/nUWjDt3QioDBbEQAAALASCmwox0YEDOBYvyfKbEp0vrso3IoCAAAAADgRBTaUpxEBA7Ui2I+/icBfjkK9T3IrBgAAAADgiP6d5EOS/0xymf4ZpSIbytGIAI7LZDYlu9r9ei0KSOIbHQAArEMrAgBWxgQ21KMRAe5rjstktr8cpbtK8osYIHEzBXAwnQgAAKA6JrChTo0IGOBZBPtjMpsa/CP9Q+ZbUQAAB9CJAAAAqmACGzgTAQNYJXWPlNnlaUXwVTe7X29FAVCMCxEAAABwQM/pi+s2Cmyg53kUQzhf7JEym5rcpJ+cakVBxe6SvBcDhdiIAAAAgD17KbBf/gfgj0xmM4TJ7D1SZpdJWfVtn5NsHUgAAAAAgB0FNjDUuQgYoBPB/iizqc0m/WT2NgptAAAAAKiVAhuAQ+lEsD9/E0GRWhF810uhbTkQauRbHQCH8SACAABYvOckvyX5P+mfDV5HkQ0MtxUBAxmm3CNlNrVSaOMkCsA+eVkIAACWSYENwLF5TrRHyuwytSIY5DwKbYC1a0QAAADAnyiwgUO4EAEDWL1vz3wzm9q9FNpOQgDr1MQ3aAAAAPANbODwDMYxhKnsPVNml6kVwSjnSW7Tv6EJpetEAAAAABRCgQ0ck6E4hmhFsF/K7LIv5DZiGOxq9+u1KChcJwIAAABgxR7TF9e3Se7FARyRyWyGMJm9Z76ZXS4XcuNdJfkkBgBgglYEAABwMI9J/pnkv9N/bupjPP8Ejq8RAQM4P+2ZyexyefNjmp93B5pbUQAAAADAyZjABpbmnQgYQD+3Z8rsct0n+UkMk9zsfr0VBQVqRQAAAAAslAIbWKpGBAzk/LVnyuxyefNjnptdhp9FAbBo23hJAwAAYM0U2MAaNCJg4DmNPVNml8uF33y36UsSWQIAAADA/iiwgbU5EwEDdCLYP2V2uUxmz7dJP+23dVFNYZ53f74BcLMCAADHosAG1uxCBAzQiWD/lNnlckG4Hy+F9oWDEIUdH96LAcDNCgAAHJgCGyiFyWyG6ESwf8rsspm+3I/N7qJ7GxPvAAAAAPA9D+mHQ26jwAbKYTKbIZz3DkCZXf5fGtOX+3GetyXHFdoAAAAA8OYhfXn9OabSAKiX/ugAlNn+0jCcQptSdPGiC+XwViwAAMBpKLCBmnieyhCtCPbvbyIomuUM9u88yScxsHJuMCmJ7xUBAAAcz0OSvyf5r/QvF3+K5wwAwAGZzC6b6eHDuNr9ei0KAGDHS4QAAJTKBDZQOysDMsSdCA5DmV02D1UPR6ENAPyRlwgBACiJAhvgjZUBGcKzoQNRZvuLw3RX6b9/cCsKVsaLLgAAAMCfKbABvs5kNkN47n4gymx/cZjnZvfrrShYES+6AAAAAIkCG2AIk9kM4bn7gSizy/ecZCOGg1JoA5xOIwIAAIBRFNgA4zQiYAADpgeizK7jL897MRzcp13WDlYAx/VOBAAAAD/07/TldRsFNsBYjQgYwPn1QJTZ5bOswXFsdjcD2yi0Wb5WBAAHcRcvEQIAsBwvBfbneEYIMEcjAgboRHAYfxNB8RSrx/NSaF+IAgAAAIAT+HeSD0n+M8ll+uXEFdkA81gZkB95EMHhmMwun4vV49rsbhK2sgcAAADgCExgAxzOmQgYwPn3gJTZ5TOZfXzneVty/P+zd4fHbVvruoDf6zn/xVRgngqkVCCeCsxdgegKrFRgpwIrFYipIHIFoSswVcGGKohUwb4/FrilOLZFSSSxADzPjEYzd+7ZgV+KJIAX61s+wKjVXcrDFwAAAED/KLABDsMkVrahi9sjY8aHz8lsNzaFtqe28OUK++ezFgAAGAMjxAEOz30ntuH7eI+U2cOnsOrOcZILMQDsnSdkceECAMBQKbABuuW+E9tYiWB/jBkfB+OEu3PW/l6IAgAGb53kjRgAAHghI8QBAFrK7HFYJzkVQ2cU2tSo8bkAAAAAVbhLWdGlwAaoz0wEbGElgv1RZo+DE+DunaU8VGDsOLVoRAAAAACduct9eX0lDgDo9Xc6e6TMHgcjL+vwMeXBgqUoAAAAAEZHgQ3QP/bM5jFrEeyXMnscrMyux2X7eykKAAAAgMFTYAP025EIeEQjgv1SZo+Dp0Lqctm+Jl4XfC7AbsxiXxp8tgIAUA8FNsAwWJXNNhoR7JcyexyszK7PKqV8cdMbnwsAPlsBAOg/BTbA8ExEwBYaEeyXMnscFKb1OYpCGwAAAKDPFNgAwzYVAVtoRLBfyuxxnVzb26EuR+2Fzkms5AIAAADoAwU2wHhMRcAWLFjcM2X2uN5Mp2Kozuvcr9BWaHNIKxEAAADAVhTYAOM0FQFb0O3smTLbm4nuHUehDQAAAFCTm9yX1ytxAIzSVAQ84loE+/dKBKNhzEHdjpMsxQDwLCcioBIrEQAA9NpNkt+S/JxSYJw7xwMYtYkIeIQFigdgZbY3FPV4k1JoL0TBgdyl7N0OLiwAAICx2qzAXsZiEAD+7lgEPGIlgv1TZo+Hk/F+OGt/L0TBgT4XTsUAAADAyCiwAXiMxRNsw0LSA1Bme0NRn7MkTZIPogAAAADYCQU2AE9hWzu24ZziAJTZ3lDU6X1Kob0UBQAAAMCzKLABgH2ykPQAlNnjYn/cfrlsfy9FwZ40MWYcwPkWAMCwKLAB2IWZCNiCc40DeCUCbyqqdulLkz1qRMBATEWA8y0AgFG7SfJbkp/b64Nz52UAwAHOPzgAK7PHxbiDfrpKKbRdhAF822sRAADA6FwnWcUKbAD2w57ZPKYRwWFYmT0uTuz76ai9OPPlCQAAjIVVDsC3XCf5Jcn/ptwnsQIbgH2ZiIBHOAc5EGX2uFiZ3V+bQtsXKLu0EgEAAJVqRAC0vi6wL3xGAHAAFpfxGJ3bgRgzPi6eEum3TaE98yEJAAAADNh1yvjwqyiuAejGkQh4hM7tQJTZ46IA7b/jKLQBoPYLmVMxAAA8mQIbgFpMRcAWdDQHosweF0+JDMNxe2E3EwW+bOG/Jv6m8dkKANA7CmwAajQVAVtYieAw7Jk9PnciGITT9mIPXsIDLgyJfYwAAKAf7IENQO2mIoB6WJk9PkZfDsdZ+3shCgAAAKBiVmAD0CdTEfCIzyI4HGX2+Bh9OSxn7UXgB1EAAAAAFVFgA9BXExHwCF3bASmzx2ed5I0YBuV9e1G4FAXPcJPktRgAAADYgU8p5fUqCmwA+st2djzGFp4HZM/s8fG0yDBdxrhxnqcRAcBOrUQAAIzMpyRvk/yUZJ7ysL1rTQD6zMpsHuNc54CszB4fT4sM12XKwwpXogAAAAD2aLMC+yoWTgAwPMci4BGNCA5HmT0+LjCGbZlkFg8tAOMzixWxAACwTwpsAICiEcHhKLPHR8k5bEcpZc7Ma80TPhNOxQAAAMA3KLABGJuZCNhCI4LDUWaP011K6ckwbQrtEx+obMHNCAAAAB5SYAMAfN+1CA5LmT1OVmIO31F70Tlz4QkAB+V7FwDoIwU2ABQnIuARzpUOTJntjcZwHed+5LjXHAAOwzYfAEBfKLAB4J8mIuAR7v0c2CsReKMxaJtCG77H3wcAAMA43KUU2G+T/JRknmQZRTYAPGRlNo9x7nRgVmZ7ozF8x+3F6UIUgAsNAAAYlbvcr76+EgcAPMrKbB6zK/xArQAAIABJREFUEsFhKbPHycrs8Tlrfy9EAbjQAACAQVNgA8DzTUXAIywYPTBltjca43HWvvbnosDnAQAAwKAosAFgN16LgEdYMHpgymxvNMblXfv6L0WBzwOAvblx8QsAHIACGwB2ayoCtjj/4sCU2eN+wx2JYZQu299LUQDAXjRRZgMA+6HABoD9mYqAR1gc1gFl9rjfcKdiGC2FNgAAAPSDAhsADmMiAh7RiODwlNnjZZ9cLlIeavAkEcbhMgRTEQAAMCAKbAA4vBMR8IhGBIf3SgSjpcDkKMnKFzS+gBkID2QAANB3d0l+T/KvlJVhiyiyAeCQrMzmMY0IDs/K7PGyMpvkvtCexQMOAAAAcGg3uV99vRIHAHTKwi8e04jg8JTZ46W4ZOMoZe/sWTzkAAC7sEpyKgYA4Ds2BfYy7s8AAPSJc7cOKLPHS2nJQ8e5X6Htb2OcX8BKFwAAgP1RYANA/dwj5TH6kw4os8fLhRNfU2j7AgYAAGB3FNgAAMPxWQTdUGaP213KiGnYOE5ykWQhCqCHJvFwBgAA3VJgA0A/2S8bKqXMHjejhfmWs/b3QhRADy86VmIAAODAFNgA0H8TEfCIlQi6ocweN6vX+B6F9vi+hN+LAcA5FgCwNQU2AAyLldk8xv2ejrwSwai52OJHzqLMBgDnWADAxk2S35L8nGSa5Nz3PgAMhpXZPMZ5X0eszB43T5HwmMv291IUAAAAjNB1yjSrZdzABIAhm4qAR+jUOqLMHjcXYWxDoe1LGAAAYEyu22vgqySNOABgFKYi4BE6tY4os8dNgcW2LtoPah/WvoQBAACGSIENAOM2FQE/cCOC7iizx02BxbaOUsaqzfzdABWbtZ9VAACwDQU2ALDxWgT8gHPFDimzuUspKuExCm0AcIEDAH2nwAYAvjYRAY/QiXTolQi8AUXAExy1F/y+3IfHmBSA3WlEAABVuU7yS5L/TXKSspWW72sAYONEBDzCtr0dsjIbb0Ce6nXuV2j7+xmOJkbpAAAAw2EFNgCwLYu3eIyFoR2yMhtvQJ7jOKXQ9iUPAABALazABgCew8psHmNhX4eszMYbkOc6TnnKfS4KAAAAOmIFNgAA+7YSQXeszMbKbF7iTcpNA3wZQw08RQsAMA6fkryNFdgAwG7MRMAP3ImgW1ZmY2U2L3XW/l6IAuiYrQ+oyeckp2IAgJ35lLL6+iruZQAAcDgWhXZMmY03Ibtw1v4tXYgCAACAHVFgAwCHYNofP+I8tGPKbJIyIuFIDLzQx/ZDfSkKX8gAAADPpMAGAA5NP8KPWBTaMWU2mzeiMZjswmX7eykKX8gAAABbUmADAF2xKpvHNCLoljKbuFBkxy5TilHlKAAAAN+jwAYAajARAY9oRNCtVyIgSkd2bxVPtAGHNxUBFXFTHgD+6VOSt0l+SjJPmerlOxMA6NJUBDyiEUG3lNnEhSN7cBSFti9kOLzXIqAiHhYEgEKBDQDUbCoCHtGIoFvGjJO42cp+bArtadyo8IUMAACMiRHiAEBfTEXAD1yLoHvKbBIl1hjcpJsVi5tCexY3MAAAAIbqLvfl9ZU4AIAemYqAH9BrVMCYcRJl9hjMU24udOE4pdCeeBkAAAAG4y7J70n+1V7vLaLIBgD6x31rfmQlgu4ps9m4EcGgrVNuLHTlOG5q9IGRKQAAwI8osAGAoTkWAdRNmc1GI4JBm6bcYHjb4TGcJll6KapmZApD4GlanFsBwG4psAGAoXIficesRNA9ZTYbjQgGbdr+XqbchOjKWRTawH6diADnVgCD4EHLbimwAYAxcB8J1yU9oMxmoxHBaCySfO7wv3+W5IOXAQAA+IG1CA5OgQ0AAK5LqqPMZqMRwajM0+3+yO/T7R7efNtKBAAAMCoKbABgzGYi4JFzZSrwPyKg1YhgVG5TCu11kqOOjuGy/b30cgAAABzMXUphvfkBAAD+yarsSiiz2WhEMMrXfJbkS4fHcNkex8rLAQAAsDc3KcX1KgpsAIANe2bzI40I6mDMON6U4zD7zv/7Osnbjo/tyklDNW5FALAznt4FoGs3SX5L8nOSaZLzKLIBAB6aiIAfaERQB2U2X1/oMj7LlBscXTlKWR2g0O6e4oUhmImASnhACICuruu/LrCd5wMAfJt70vyI8+hKGDPOQ02S12IYpfOUp9DOOvrvbwrtadz8BwAAeIrNCPFl3HADAHiKIxHwA7qKSliZzUONCEbtPMl1xycOqxjtAgAA8BgrsAEAXmYqAh7h/LoSVmbzUCOCUbtNGc/bpLsn0o5TCu1ZPPXkMwAAAHjICmwAgN2YJ1mIgUfoKCqhzOahRgSDNX3Ch/MspVDuutC2X4nPAIC+u4uRZQC8jAIbAGA35g9+XKvzmM8iqIcym4caEQzW9An/f9cpT6X90eHxHqfcrFl46QDosXWSUzEA8EQKbACA3ThJucc8T/JaHNBPymweakRA6yrJL0k+dngMZ+3vhZcDeOJFCgBA3yiwAQB2Q4HNLqxEUA9lNg81IuCBi/aL/6zDYzhLGX1+7uU4mOuUlfHQVxMRAAA9OvdeppTYrscBAJ5Pgc2u2S+7Ispsvnbjw54HFu2JQJfl5ruUlQlLL4cvaQAA6DkFNgDAbkxTFkEpsNkH05Iqoszma40Pfr4ySxmp0WWhfdn+Xno5AACAnlFgAwDsxjSlvF7EdEn2y3l7RZTZfOsNeiqGwXnJa3rbnhyskhx1+G+4bI/lyssJgPMqACqnwAYA2I1pFNgcnnP4iiiz8QZlG+v2hOHPjo9jmbJS3IiP/VlF8QLgvAqA51BgAwDsxjQKbLpzI4K6KLP5mgtuvmeV5G3uR3534ag9jlkU2sD3L3YAAA5FgQ0AsBuT3BfYFtvQJef1lVFm403KUyyTnCR51+ExbArtE3+vwDe8FgEAsGcKbACA3dgU2PMkb8RBJSykq4wym6+5EOcx5ykrH7s8uThKuXE0S9lHm92RJwAA/JMCGwBgNxTY1M498soos/mai/Lhmu7w9V2krI7ucr+S49yPHPflsjueOgMAgOJTe82hwAYAeBkFNn3iHnlllNl8y02MaR2iaXZ3A+a2PfFYp6yS7opCGwAXPwDs0qeU8vrKNQYAwIvNH/wciYOecB1QGWU239JEmc12fyezlDK560L7ImW1OAC4+AHgqRTYAAC7o8Cm71YiqIsym29pkpyKgS2sU/bQvuz4OM7a3wsvyU7e/9B3k7gRDQD8mAIbAGB3FNgMxZ0I6qPM5lsaEfAEy5QR5u87Pg6Ftvc/bJzEE5QAwD8psAEAdmeWci9Wgc2Q2DKuQspsvqURAU/0IaXQPuv4OM5SCqyllwQAAIgCGwBgl05yX2DbqpQhcs1QIWU239KIYJBm2e9KxUV7MnPc8b9zM/J86SUHAIBRUmADAOyOApsxsTK7QspsvqURAc80az/suz6pUWi/zHW6fygBYAhWIgA4GAU2AMDuKLAZq0YE9VFm483KLt22JzirdL9PykVKse5Jque9jgAAUDsFNgDA7kxTCuxFFNiMVyOC+iiz+Z4bX1g807o94fmj4+M4SinVZ1FoAwDAENzlvry+EgcAwItNUxYnLWJSIyS6hCops/meJspsnu8qydvcj/vuikL7eaxqoe9mMd4ZAIZCgQ0AsFvTKLDhe9wbr5Aym+9pkpyKYXAnKYe0TCmUzjr+dx89OBZfRNtZJ3kjBgAAOrRqz0sV2AAALzeNAhsecy2COimz+Z5GBIM8YTm0Rfvf7frBiOPcr9BWaANwSLZuAXielQgAAF5kklJgz2PhCmxDd1CpVyLgOxoRsCPz1PFE06bQnnhJAHBOBQAAwABNUhYYXSX5K2UbSEU2bGclgjops/meRgTsyG1KoX1XwbEcJ7nwknj/AwAAAMBAKLCBQTNmnO9pRMCO/55mSb5UcCybPbwXXhbvfwAAAADoqUWMEIddWomgTspsvqcRATu2TvI25cnArim0YdhORAAAAAAM0PzBz5E4YKfsmV0pZTY/cpPktRgG47SCY1imlEzvKjiWs5SC3dhxGJ6JCAAAAICBUGDDYaxFUCdlNj/SRJnN7p2nFE1nFRzLx5SnrZZeFl/aAHv8TD0VAwAAAE+gwIbDuhFBvV6JgB9oRMCenCe5ruRYLmPc+NeMUwHwmQoAAMBhnaQsurlN8kfKYiBFNhxGI4J6WZmNNy9duE0ya//Gajghu0xZOWdFMgAAAABwKCcpC23mMSUVutSIoF5WZuPNS1c2hfZdJcezak8eAQAAAAD25STJRcr99y9J3kWRDV1rRFAvZTbevOMyrex41qlnxPdRFNoPfRYBPusAAAAAdkKBDXUztbViymx+pBHB4EwrPKarJL9UcixH7fFM/KlAr7kYBAAAALo2TXIeBTb0wa0I6qXM5kcaEXAgF0l+r+RYXqes0FZoA7ALKxEAAACMxjSlwF4n+XeSj1FgQx9YmV0xZTaPuREBB7JIcl3JsRxHoe1JNAAAAAB43DT/LLCPxQK94n54xZTZPKYRAQc0S12F9nLEr4Un0QAAAADg2yZRYMNQfBZB3ZTZPKYRAQd0m7JC+66S43mTcRfaAAAAAEAxSbl3eZXkryiwYSisyq6cMpvHNCIYlFkPjnGdZF7R8ZxFoQ19vcAEAAAAeImvC+zLlAUwwHCYUlo5ZTaPaURAB1ZJ3lZ0PGdJPnjvQ6+ciACfpwAAADyDAhvGxcrsyv2PCHhEIwI6skwpo95Vcjzv2/fD0nsfAJ+nAAAAgzNPKbEV1zAuVmZXTpnNYxoR0KHzJNOKTiAv299LLw0AAAAA9N78wc+ROGCUGhHUTZmNNzG1W6SMHT+u5Hgu2/fFyksDAAAAAL2jwAYeakRQN2U227hJ8loMgzDt4THfJpm1Xyi1nFxetcc05PEjRqsAAAAAMBQKbOBbbkRQv1ciYAuNCAZj2tPj3hTad5Ucz1HKyuyTAf+t3Hq7AAAAANBjJ0kuUu5z/ZHkLIps4O8aEdRPmY03M32xTtlDuxabQnvipYEqzURARa5FAAAAcBCbArtJ8iXJuyiwge8zobQHjBlnG40IqMQyZXX5+0qOZ1Noz2IlMwDf5zsCAABgf06SLFJGiNsuE3gK92x6wMpsttGIgIp8SPJ7RcdznOGu0P7szw0AAACACn1rBbYiG3iqlQjqZ2U222hEQGUW7QnrcSXHc5zkKsYaAwAAAMC+TFNWXy9Sz31BAPbMymy20YhgME4H9G+ZJbmpLNulPzEAAAAA2JlpkvOUfW3/neRjFNnA7qxEUD8rs9lGIwIqdJvyJOYqZe/qGpy1vxcDyhgAAAAADmkaK7CB/bsTQT9Ymc22bkRAhdbtiW1NzlL29R5KvtBXJyKgIisRAAAA/NAkpby2Ahs4FPe/e0KZzbYaEVCpVZK3lR3T+wxndTb0+SIYAAAAqPvafZHkKslfSS6jwAYOx2TSnjBmnG01GdZ+ywzLMmUP7bOKjunywbEBAAAAAKXAnrc/b8QBdMjK7J5QZrOtRgSDMR3o67lo/201PXRxmfJ015X3PQAAAAAjpcAGatSIoB+MGcebenymA/63zZNcV3ZMy/R3717vewAAAACea55yb2wzQlyRDdSkEUE/WJmNNzVDctueJK+THFVyTEcp+3rPYmwJwJi/nwAAAMZg/uDnSBxAxdyv7wllNttqRECP/lZnSb5UdEybQvvEewkOZioCXBwBAAAchAIb6COLD3rCmHG21YiAHlkneVvZMR2l7J096VmO0FevRQAAAAB7sxkhfpvkjyRnUWQD/XEtgv6wMpunuIlygP5YpqzMfF/RMR3nfuR4H5768mQaAAAAABsnSRYpRbb7xECfuffdI1Zm8xSNCAZhNqJ/64ckv1d2TJtCGwAAAABqd5LkIuXe8Jck76LIBvpvJYL+UGbzFI0I6KHz1Dcy5Dhl5Xgf3PkTAgAAABgVBTYA1TBmnKdoREAP3aasRm9S1749Z+3vReX5rZOc+jMCePFnKQAAQM2mKYtCjBAHxmAlgv5QZvMUjQjoqU2hvUp9hfZte6EA7N4k9r+hnu8hAACA2kxTyutFyiRBgLFwr6ZHjBnnKRoR0GPr1LkK+l3qX50NfXUiAgAAAPibacrCinWSfyf5GEU2MD6m6PWIMpunaEQwmBPWsbpK8kuFx3WZegtt73sAAACAfptGgQ2wcSOCfjFmnKdoRDCYk9cxu0hZrXlW2XFdtr+X3vcAAAAAvNAk9yPET8UB8F+NCPpFmc1T3SR5LQZ6bpFS6td2In+R8oSsEScAAAAAPNWmwJ4neSMOgG9qRNAvxozjTc5YzZNcV3ZMR0lWsc8vwBB9FgEAALAHk5SFG1dJ/kqZ/qfIBvi+RgT9oszGm5yxum1P9O8qO67aCm2rxAEAAADqosAGeD73vHtGmc1TNSJgYF9a8wqP6yhl7+xJBcdy68+EHpuJAAAAgAGZp9wzaqLABngu97x7RpnNUzUi6L1TEfzNKsnbCo/ruD22iZcIAAAAYLQ2BfZtkj+SnKUshADgeVYi6Jf/EQFP1IiAAVqmjPV+V9lxbQrtWTwtBgAAADAW8wc/imsARs3KbJ6qEQEDdZ7kU4XHdZzkosP//sqfBsBOeCgJAAD4kVmswAbYt88i6B9lNk/ViIABWyS5rvC4ztqLGQD6ay0CAADgKycpixiaJH9GgQ2wbxYb9JAx4zzHTZLXYmCgX2Sz9gKitguHs/b3wssEAAAA0FsnKfd35nGPFeDQLDboISuzeY5GBL03FcF3bQrtuwqP7SzdlNl3/izo8Q0CAAAAqOH6dLMC+0uSd1FkA3TByuweUmbzHI0Iem8qgh9ap+yhXaPLHL7Q9rQafTURAQAAAB2ZJvkQBTZATdzr7iFjxnmORgSMwLK96Hhf4bFdPjhGAAAAAOowTRkfvkhyLA6A6jQi6B9lNs/hyRXG4kN7EXJW4bFdtO9F70cAF0sAAEB3plFgA/RFI4L+MWac57CnAGOySHJd4XEdJVnlMHsC+4IH8FkKAADcm6ZsUbdO8u8kH6PIBqjdtQj6ycpsnsNKUMZm1v7d17av0abQnu35fdn4EwAAAABGbpKyAnue5I04AHrHQs2esjIbb/hxmongyX/z8yR3FR7bUZKr9oIK+DvvCwAAAF56XblIuffyV5LLKLIB+uZzkrcp9/jpISuzea7rGJ3DuKzbL7s/Kzy217lfoe1hE7jnewoAAICnsgIboP9ukizbn0Yc/abM5rkUZozRKuUJrssKj+04+yu0bS0AAAAADN0iCmyAvvs9ZZrGlSiGw5hxnku5xVgt2y/EGh23x7drHl4BeLmVCAAAoDrzlHsptzFCHKCvrlMWof2U+60hGBArs3ku5RZjtkgyTXJa4bG9aS/CFl4mAAAAgH+YP/g5EgdAL92klNYXMUZ88JTZPJeV2f02FcFOLnxWqXNP3rP298LLBAAAAKDABhgIY8RHSJnNc1mZ3W9TEezkPTBPebCjxougs/bYLnbwv7XycgMAAAA9c5LkPApsgL67TrnPfRXd1Cgps3kuK7OhjC+ZJflS6fF9bL/cl14qRmwWD2QAAACMxUnKpLp5ktfiAOgtY8T5L2U2z+XpFyjWSd4muaz0+DbHtfRSAXTuLlaEAADArimwAYbDGHH+QZnNS1ynzv2C4dCWKaPb31d6fJcppftLJiooYABebp3kVAwAAPBiCmyA4TBGnB9SZvMSPlTg3oeUQvus0uNbpYxbfm6hrYABAAAAujRNKa/Po8AG6Lu7lEVixojzKGU2L6Hc6i+v236cpzwZXOPEgqO8vNAGAAAAOKRpSoG9iAmRAEPwKaXENkacrSmzeQkrs+Gf74lZypNkNY7k3hTaU+9fAAAAoFLTKLABhuQ6pcBexn1pnuGVCHgBqzvhnzaF9l2lx7cptCdP/L9rvLT01IkIAAAAqjdJmXi3TvLvJB+jyAbos7skvyX5OeX+3EUU2TyTMpuX8MED37ZOeXq4Vsd5eqHdeFnpqYkIqIjPUgAA+Pv12iJl1OxfUWADDMGnJP/K3x9SghcxZpyX8CEE33eV5Jf2QqxGx+0xzrxUAAfTiAAAgJGbpIwQnyd5Iw6AQTBGnL1SZvMSPpT6bRo31fftImWEylmlx3fanmAsvFQAAADAniiwAYbnLvcFtoWP7JUym5e6jvE/fTWNMvsQFm3Wp5Ue39mD4/wRJyQAAADAU8xT7jcosAGG41NKgX0lCg5Fmc1LWZ0N2128rVLvgx9nKQ82fPBeBwAAAF5g/uDnSBwAg2CMOJ1SZvNS69S74hRqcZvyJPKq4gu59ymF9tLLxcBMRQAAALBXCmyA4TFGnGoos3kpT+HAdtbtRd2fFR/jZft76b3OgExFQEVWKQ8PAQBA3ymwAYbpU8oI8aUoqIUym5fyRA5sb5Xkbe5L4xpdpqzQXnmvAwAAAA+cpEyeW0SBDTAkN0kuUkrsRhzURpnNS1mt2V+z/LOwZP+W7cXfu4qP8ar9+1BgAwAAwLhtCux5ktfiABiMu5T7wBdxH5jKKbN5KR9y8HTnKaOP31R6fEcpDzrMvMcBAABgdBTYAMNljDi9o8zmpazMhudZpBTGx5Ue36bQnj54n9+4iAUAAIBBUmADDJcx4vSaMptduE69hRzU6jZl5XOTeveZerhC+7Y9Vhe09M1EBFT22Q8AALWYppTXi7i3BzA0xogzGMpsdsGNWXj+e2eWUhjXWmgf577Qhj5yQ4aauHgEAKBr0yiwAYbMGHEGR5nNLqyTnIqhlxcv1PH+OU9yWfExbgptD64AAABA/0yjwAYYMmPEGTRlNrug4OrvhQx1WKaMQv5Y8TG62AUAAID+mKQU2Oeu6QEGyRhxRkOZzS74oISXu0hykuRMFAAAAMAzbArseZI34gAYpM8pi6OuYqEhI6HMZhd8YMJuLFIKbU9MAwAAANtQYAMM301Kgb2MMeKMkDKbXbAyG3Zn1r6nXosCYLAXoD7jAQB4CQU2wPBtxogvk6zEwZgps9kFK7Nht++neXuCciQO2ImZk34q0kSZDQDA82wKbFuUAQyXMeLwFWU2u3Ido5H75lQE1Vq3F6d/igIAAABGbf7gx0PvAMNkjDj8gDKbXfGEEOzWKsnbJJeiAAAAgFFRYAMMnzHisCVlNruyjpW+sGvLlPHIxocBAADAsCmwAcbBGHF4ImU2u+JDF/ZjkWSS5I0oAAAAYFBO2uv+eZLX4gAYLGPE4QWU2ezKWgSwN4uUUTP2pQcYxjmTaTYAAOOlwAYYB2PEYUeU2eyKldn9NI0nwfry/pqnFCBGjcHTnbhowDkTAAAdX5MsosAGGIPrJBcxRhx2RpnNrliZ3U/TKLP7oknZP/uLKODJJiIAAAAObJrkPApsgDG4SSmvL+J+O+ycMptd8YQR7N86ydskl6IAAACA6kxTyutFbBUGMAa/p5TYV6KA/VFms0vXTtRh75btxfF7UQAAAEDnplFgA4yJMeJwYMpsdskHNxzGh/Zi+UwUAM6XAAA4uGkU2ABjYow4dEiZzS6tk5yKAQ7iPMmJi2aAXp4vAQDQP5PcF9jufwGMgzHiUAFlNrtkpVH/zJKsxNDb99sspRR5LQ74oakIAACAZ9gU2PMkb8QBMArGiENllNnskpVGcFi37QX1KsmROOC7piIAAAC2pMAGGB9jxKFiymx2yVNKcHjrlBFnf4gCAAAAnkWBDTBOxohDDyiz2SUrs6EbV0l+SfJRFAAAALC1+YMfE88AxuE6ybL9sUAPekCZzS754IfuXCQ5SXImCoCqNSIAAOiUAhtgfO5yX2BblAc9o8xm16wO7ZepCAZl0b6mp6IAqFYjAgCAg1NgA4zTp5QC2xhx6DFlNrtmdWi/TEUwyAv0VZJjUcB/TUQAAACjM0t56FuBDTAuxojDwCiz2YfzlEJbmQaHd9terK9crMN/+T4CAIBxOMl9gf1aHACjYYw4DJgym31QpkG31ilPoH8RBQAAAAOnwAYYL2PEYQSU2ezLOmWF9qUooLP34FvvQQAAAAZIgQ0wXsaIw8gos9mnZXtx8U4U4D0IwN8uvI2/BwB4mmlKgb2IAhtgbIwRhxH7f//5z3+kwL6t44Zt1Z8DIhi8qyRvxIDPOqjGKsmpGKjc55RtSwCgS9OU1deLuLcEMEbGiANWZnMQ85RC2/7Z0I1FSnHiwh8AAIDaTaPABhizmyQXMUYcaCmzOYSmvQj5UxTQiduUlVVNPFTCeM1SHuoAAADqM40CG2DM7lJWX1/EGHHgK8psDmWV5Nck70UBndgU2qsotAEAAOjeJKXAnsfWWABj9SmlxF6KAvgeZTaH9CGlTLNHJHRjneQ8yaUoADplTBoAMFYKbAA2Y8SvUiZJAvyQMptD2+yf/VoU1Zg6aRiVZcrNg4+iAOjMOm7eAgDjocAGwBhx4NmU2RzabXvx8kUU1ZhGmT02F0lOkpyJAgAAgD1ZRIENMHbGiAMvpsymC+skv8TKUOjSIqXQPhYFAAAAOzJ/8HMkDoBRMkYc2CllNl2xMhS6N4ux/4zHSZKVGAAAYOcU2AAYIw7sjTKbLp3HylDo0mbs/ypuODB8ExEAAMDOKLABSIwRBw5AmU2XblNGHa9c+EBn1ik3H/4UBcDBNCIAAHroJGVhggIbYNxuUsrrpetb4BBeiYCOrdsLIbozE8HorZK8FQPAwbjYBwD64iRlZGyT5EvKdnGKbIDxuUvye5L/SzJN8sG1LXAoVmZTg2V7cfROFNDp+3AW+9gDAACM3UnKJL15ktfiABi1zyn3Da9SJq0CHJwym1qcpxRp9s+G7ixS9hV+IwoAAIBRUWADsGGMOFAVZTY1maeMHTeuCrqzSBk77sEShmYqAgAA+Mc58jxlgYECG2Dc7lJWXy9T7g0CVEOZTU2a9iLqT1FAZ27jwRKGaSoCAAD4b4G9iIeYATBGHOgBZTa1WSX5NcnvsRsxAAAgAElEQVR7URz0QhYealLG/n8RBcBerEUAABz4ul+BDcCGMeJAryizqdGHlCLtVBQHu6iFr62TvE1yKQqAnfO0OwCwb5OU8noRBTYAxogDPabMplabMcf2bILuLFMedjApAQAAoH6TlPsp8yRvxAFAjBEHBkCZTa02+/Yacwzd+pBSaJ+JAgAAoDoKbAC+Zow4MCjKbGq2TvJLko+igE6dJzmJ0XT020QEAAAM6NxWgQ3A135PWYF9JQpgSJTZ1O4ipUSzKhS6c5uyj73R//SZhzEAAOi7ecoe2ApsADauU+6hGyMODNb/+89//iMFajdJsooiYq+fBSJgCyfte/FIFPisgxdbJTkVAxX7nPIwGwDdmj/4cS0GQFLGiF+llNiNOIChszKbPrhNefJ45cINOrVu34t/iAIAAGBvFNgAfIsx4sAovRIBPbFO2bcX6NZVyl72AAAA7M48yTLlgf4/UrZbU2QDcJ3kbZKfUhaZKLKB0bEymz5Zpow5ficK6JS97AEAAF7uJKWYWERxDcA9Y8QBHlBm0zfnKXv32T8burVIMo39XgEAAJ5iU2DPk7wWBwAPGCMO8A3GjNNH8yR3YtipiQh45nvxWgz0yEwEVKQRAQCMxknuV9d9SZk4p8gGIDFGHOBRymz6qEkp0djthTU81W17ku3hEoDnnc8AAMO+zlZgA/Atd0l+S/K/7ffFMuU+GwDfYMw4fbVK8muS96KATq1TVrt+EQUAADBy05SH7xexPRoA//Qppbi2+hrgCZTZ9NmHlBLNnr3QrXXKOKRLUQAAACMzjQIbgO+7Timwl7H6GuBZlNn03TylSDOqC7q1TBmL9E4UAADAwE2jwAbg++5yX2CvxQHwMsps+u62vYA04hi6d55yU+eNKAAAgIGZpNx/OI8CG4BvM0YcYA9eiYABWCf5RQwvciICdmSRMj4JfNbB4+cvAEDdJu01zlWSv1K2VlJkA/DQdcq96Z9SHnpSZAPsmJXZDMVFSklxJopnX6DDLtym7GXfJDkSBz7r4IeflwBAneeM8/bH1CkAvsUYcYADUmYzJOcphbanpKFbm0J7FYU2AABQPwU2ANswRhygA8pshuQ2ZfzXKgo06No65QGTS1EAAACV2hTYprwB8D3XuV+FbcIWQAeU2QyNAg3qsUxZ4fBRFAAAQCXmD348CA/At9ylrL6+iDHiAJ1TZjNEy5Rx4+9EsTX7yLIv9rMHAAC6psAGYBufUkrspSgA6qHMZqjOU/bstX/2dk5EwB4tYj976jAVARVZiQAA9kqBDcA2blIWY1wlacQBUB9lNkO/cF27aIUqzFKKG4U2XZqKAABg0E5SHqadJ3ktDgC+wxhxgB5RZjNkTXsB+6cooHO3KTeVVvGACQAAsDsKbAC2ZYw4QA8psxm6VZJfk7wXBXRuHQ+YAAAAL6fABmBbxogD9JwymzH4kDLi+FQU0LlVkrdJLkUBAAA8wTTJeRTYADzOGHGAAVFmMxab/bNd8H7biQg4oGXKAyZnogBG7i62XgCAH5m21/OLJMfiAOARxogDDJAym7G4bS+Av4jim9xI59AWSSZJ3oiCA5qIgMqsY3IMAHxtGgU2ANszRhxg4JTZjMk6yS9JPooCqrBIGTvuBhWH4m8NAKBO0yiwAdieMeIAI6LMZmwuUkZqG28M3dtMTFjHdAAAABibSe4LbJNKANjG55QR4lcp95UAGAFlNmN0nlJoe9obutek7J+9ikIbAACGblNgz2PLIQC2c5NSYC9jjDjAKCmzGaPb3I83Vp7dm8QTjXRjnfKQyaUoAABgkNeaCmwAnmIzRnyZcg8XgBF7JQJGalOece9EBHRomeRXMQAjPB8BgCGapDxEfpXkr5QHVxXZADzmc5K3Saa5X4wEwMhZmc2YLVMK3HeigCp8aC9W7GkPjIWJKAAMzfzBj0loAGzDGHEAfkiZzdidp+zXa/9sqOc9aU979mkWT3YDAOySAhuApzJGHICtKbOhXHCvXXRDFW5TysZ1ktfiAACAaq+jFdgAPNXnlAL7KiZVAbAlZTaU8TXzJH+KAqpw274nV3FjDAAAajFL2b9UgQ3AUxgjDsCLvBIBJCml2a8jz+DEnwEVWafcKAMAALq9TrxIKR/+THIWRTYA2/k9yf8lmSb5EEU2AM+kzIZ7H1JG3YzVxJ8AlblK8lYMwICtRABAhR4W2F+SvIstgADYznXKvZyfUhYpuOYB4MWMGYe/2+yf7UId6rBMGWd4JgoAANibk9yPEHc9DMBT3KQsSNg8CAUAO6XMhr/b7NX7RRRQjUXKSKpTUbADJ/FkOABA2nPsRfujwAbgqX5PKbGvRAHAPimz4Z/WSX5J8lEUUI15SgF5LApeyJYKAMCYTdtz64VzawCe4TplBfZVyqIgANg7ZTZ820XK6r0xjTZW8FCz29zvtXQkDgAA2No0CmwAns8YcQA6pcyG7ztPKbTHcrF/4iWncuuU/bNtAwAMhZUMAOzLNApsAF7GGHEAqqDMhu+zEhTqs07yNsmlKICBfKYBwK5MUgrseZI34gDgGYwRB6A6ymz4sXXKCm3FGdRjmTJJ4J0oAAAYOQU2AC9ljDgAVVNmw+OWUZxBbc5TbtydiYInmooAAOg5BTYAu2CMOAC9oMyG7Zyn7NVrrzGo63154n3JE01FAAD01CIKbABe5jpl4c4yxogD0BPKbNjePGXs+FD3zz7xEtMztykPmTSxrz0AAMO9Dt38OOcF4Dnucl9gr8UBQN8os2F7TcoNhD8H+u9zY4Q+2hTaK3/DQE9dx4QJAP5OgQ3ALnxKKbCNEQeg116JAJ5kleRXMUBV1ikjxwH6yGg/AJJSXC/b74U/kpxFkQ3A010n+SXJT+13iyIbgN6zMhue7kPKStBTUUA1lkkmST6KAgCAnjhJeSjTCmwAXsIYcQAGTZkNz7PZP/u1KKAaFyk3BM9EwQ9MRAAAdOgkyaK9pnQ9CcBLGCMOwCgos+F5blNuPnwZ2L9rEuNO6bdFyg1C+8/yPf42AIBDU2ADsCvXuV+F7R4eAKNgz2x4vnXKHjRDcuJlZQBm7cUdAAB0eW11kaRJeQj6XRTZADzPXZLfkvz84PtFkQ3AaFiZDS9jrDHU5zZl5csq9h4E6rdKcioGgEGYpqy+Po/iGoCXM0YcAKLMhl04j7HGUJt1yo3EP0UBAMAeTdvzzoVrQgB24CZl8cxVynQPABg9ZTa8nFWgUKdVkrdJLkUBAMAOTaPABmB37lLK64uUh/MBgAeU2bAb65QV2kozqMsyZQ9tWwEAAPASk5TyehEFNgC78SmlxF6KAgC+T5kNu7NMGTf+rsf/hpOU1awwJIuUm49vREFr5rMOANjCJGUF9ty5JAA7Yow4ADyRMht26zylJOnrk/oTLyEDtUgpL62iAWpzKwKA6q6JFNgA7JIx4gDwAsps2L15e2Jq/2yox633JlApN7MAuqfABmAfjBEHgB1QZsPuNSk3Qf4UBVT33pylrNBWaAMAME+Z4KPABmBXjBEHgB17JQLYi1WSX8UA1VmnbAcAAMA4zVNWyN0m+SOKbABe7i7J70l+TjJNKbMbsQDAbliZDfvzIWUV6GmPjtme2YzBsr24fC8KAIBRmD/4MaEHgF0xRhwADkCZDfu12aP3dU+O98RLxkh8SCm0z0QxSicpEzQAgGFfiymwAdi1m5TyehmrrwHgIJTZsF+3KTdPvogCqnOeUmoei2J0TKGgJo0IAHbmJGUP7EUU2ADszl3uV2CvxAEAh6XMhv1bJ/klyUdRQFVuU7YC6NP0BGB4GhEAvMimwJ47pwNgxz6nFNhXKfcQAIAOKLPhMC5SbrIYaQx12UxPWMXqHQCAvlBgA7AvxogDQGWU2XA4RhpDndYpN0P/EAUAQLUU2ADsizHiAFAxZTYczm3KzZdV6l0BeuJlYqSukrxNcikKAIBqTFPK60U8FAzA7hkjDgA9oMyGw1qnrNCutTAzZpkxW6bsoW07gOGbigAAqv6eVmADsC/GiANAzyiz4fCWKSug34kCqrNIuYF6KopBm4qAynz2uQP4blZgA7A3xogDQI8ps6Eb5ykrQN2ogfrM24tb708AgP2ZtOdd5867ANgTY8QBYACU2dCdecrYcaO9oS592N8eAKCPNgX2PMkbcQCwBzcp5fVFjBEHgEFQZkN3mpSbOH9WdlyTeFoV1inTE76IAgDgxdcXCmwA9u33lBL7ShQAMCyvRACdWiX5tbJjOvGyQJJSaL8VAwDAk01SJt1cJfkryWUU2QDs3nV73f7Tg+8dAGBgrMyG7n1IWQF6KgqozjLlAY93ohiUiQiojIkowFBsVmCfiQKAPTFGHABGRpkNddjsn/1aFFCd85Ty003Z4TgWAZVZx4pFoN/XMpufI3EAsCfGiAPASCmzoQ63KTd/7M8LdTpPWaGtBAUAUGADcBjXKSuwr2KaEQCMljIb6rFO8kuSj6KA6tymbAfQxA1bAGCcFNgAHIIx4gDA3yizoS4XKas/uxxnfJJk5aWAf9gU2qu4gQsAjMNJkkVKgW1LJAD2yRhxAOCblNlQn67HGU+8BPBd65Qbun+IAgAYKAU2AIdijDgA8ChlNtTnNuXm0SpWf0KNrmJLAGC3GhEAHVNgA3Aod0mW7c9aHADAY16JAKq0TlmhDdTpImUEGv01EwEVaUQAdGCa+/1IvyR5F0U2APvzKcm/UiYCnkeRDQBsycpsqNcyZYXEO1FAlRbpdksAAICnmqasvl44hwHgAK5zvwrbGHEA4FmU2VC385TVg4e80WTPbNjeLGVLADeDAYBaTaPABuBwjBEHAHZKmQ31m7cn/4faP/tE5LA1e9wDADWaRoENwGF9Simwr0QBAOySMhvq16TciPpTFFCltfcoAFCBSe4L7FNxAHAAxogDAHv3SgTQC6skv4oBqn6PvhUD8EzGLwLPNUkpr6+S/JXkMopsAPbrLslvSX5Ome53EUU2ALBHVmZDf3xI2Z/XzSmo07K9kH8nil44SXkIAWrg5h/wFJsV2PMkb8QBwIEYIw4AdEKZDf2y2T/7tSigSucpe1S6sVy/iQgA6Nn3lgIbgEMzRhwA6JwyG/rlNuUG1pc9/jdOxAwvskhZ8XssCgDgheYPfo7EAcAB3KWsvr6I7XAAgAoos6F/1kl+SfJxT//7bpLBy2weOll7PwEAz6DABqALn1JK7KUoAICaKLOhny5SVlCfiQKq1KTscb+Km9DAdu58XsCoKbAB6MJNyj2mq/Y6FgCgOq9EAL11nrJ3EVCndfs+Bdj2MwMYl1nu9yD9I+VBVUU2APt2l+T3JD8nmaaU2Y1YAIBaWZkN/XWb+7153fSCOi1Tbg68F0V1piIAoAMn7Tn8PMlrcQBwQMaIAwC9pMyGftus/Lzc8f/uJKUsB17uQ0pxaluAukxFAMCBKLAB6Iox4gBA7ymzof+WKTfI3u3wf/MkZcU3sBuL9n11LAoAGAUFNgBduUspry9iKxsAYACU2TAM5yl77inKoF6zlBsJbmgDwDBNUwrshe97ADpgjDgAMEjKbBiOeUpRZv9sqNNt+z5deZ8C39AkORUD9M60/X5fxIOlAByeMeIAwOAps2E4mpQbaX+KAqq1TrnZ/YcogG98jwP9MI0CG4DubMaIL2OLOABgBJTZMCyrJL8meS8KqNZVkrdJLkXRqYkIAHiCaRTYAHTrc0qBfZUy+QsAYBSU2TA8H1L25n3JqNKTeLoX9mnZvk/PRNEZRQQAj5mkFNjzJG/EAUAHbtrrx2VM8gEARkqZDcO02T/79TP/761YhP1bpKzyskcuANRDgQ1A14wRBwB4QJkNw3SbcgPuiyigavOUmxNWCQNAdxTYANTAGHEAgG9QZsNwrZP8kuSjKKBamwdP1kmOxAGj/94GDmsRBTYA3TJGHADgEcpsGLaLlP2v7csL9WpS9s82SQHGzeobOIz5gx8PkgHQBWPEAQCeQJkNw3eeUmg/ZYyxPbPhsNZJ3ia5FAUA7JwCG4AaGCMOAPAMymwYvtuUEYr/n727PW7kSrMEfGpj/4trgbgWiLKAlAVTbQFRFlTJAlVbILQFBC0QaUGBFhRgwQAWDGEB98cFl/VBAiCIj5s3nydC0RM9My3mi1bxIk++J8fZ/ObdmbHBwY2W/+x9NIqDuYhNCIBWCbABqIEacQCANxJmQz9MUja0bX1C3T6lNCN4NQAAvN7Z8nepABuAY7uOGnEAWOc0HvZiA8Js6I9RbH1CF2zzagCg+1RNwnbOUlqI3if51TgAOKJpkmHUiAPAKifL73CD5e/LCyNhHWE29Mun5S8HIRnU6/EQN4utMuiTiRHAxgTYANRinhJeD2OzDABWeb/8Hvdf3/x718bCJoTZ0M9fGpMIyaBmj4H22D+rAJBEgA1AXa5TQuwbowCAtd/jBnn+HufMiNiEMBv6Z5ZyE/DLml8ywHFNlge9f4wCgJ46XZ5bP0WADcDxqREHgPW+rRFf1xA7Ni428b+MAHppnOTfK/73NkGhDjdJ/jSGvfHgDkB9TlPC60mS/07ydwTZABzPPMl/kvzf5feHUQTZAPCc9yn3Mv9n+T1uk1edzoyNTdjMhv76nFJjfG4UULVhyk2TS6PYuRMjAKjCaZ7en/abcQBQATXiALDeuhrxdWZGyCaE2dBvj+/Ptu0CdRssD4du8EPb5n4n0yOnEWADUBc14gCw3mtqxFe5M0o2JcyGfrtPuYn41Sigehcprwhwwx/aNYswm7adLM+e75P8l3EAUIF5Sng9jO0wAFjl8WHkXX2X8+AYGxNmA5OUd/L+/cO/f+IXClTlfnlgHMd77QHoDgE2ADW6TXn/tRpxAHjZW2vEV5kYL5sSZgPJ8+/kPUsJzYB6TFLCgC9GAUDFBNgA1GiaEmCP4uF9AFj1fW6Q/b8SSpjNxoTZwKNP8U5e6IJxkg9JroxiJ4dzAHZn17VzAPBWizwF2G6aA0A93+dmRs6mhNnAIxXG0B2jlIdPPhrFm5wZAcCbvf/mL2dIAGqhRhwA1ttnjfg6HjJjY8Js4MdfIJ9i4xO64FOS09h+g9Z+D58bAx0gwAagRmrEAWC9Q9WIr/udDRsTZgM/GsW2InTFIKVNwesBoA1uulIzATYANVIjDgCbf6cbpI7FmJmPg9cQZgPPedz4BOp2vzyITiJYAGD3jlk5BwCrqBEHgO5+p/MAGq8izAZeMjMC6Mw/qxfxvnsAdus8yVdjAKAiasQBYL0aasTXmfmYeA1hNgB0n/fdAwAALVIjDgCbqalGfJ2Zj4vXEGYDQBtGKa8H+MsoNnZuBAAAUCU14gCwXldfDTX20fEa7x4eHkwBANoxSnJpDJufhYyAilwk+WIMAEBPzZMMUwLsmXEAwLO6UCO+7vf9qY+R17CZDQBtGaQ8lfmbUQAAAJVbpITXw6gRB4BVulQjvsrMR8lrCbMBoD0XKTeCfjUKAACgQrcpIfbIKADgRV2tEV9l7GPltYTZANCe+5SnNccNHXQBAIBuUyMOAOt1vUZ8HWcAXk2YDQBtmiwPvf8YBQAAcCRqxAFgM63UiK8z81HzWu8eHh5MAQDaNUhyZQwv+j1uqlGP0yT/bQwAQAPUiAPAei3WiK/zf1JaJWFjNrMBoG2jlHdoXxrFs06MgIrMjAAA6DA14gCwXus14qssIshmC8JsAGjfIGXj89woAACAHVIjDgCb6UuN+CrOCmxFmA0A/Tkwj9O/Jz4BAIDdu0tpgRoZBQC8qI814qsIs9mKMBsA+uE+JdCeODwDAABbmOcpwJ4ZBwA8q8814us4P7AVYTYA9OvAeJHkq1EAAAAbeKwRH6U0PQEAz1Mjvp7NbLYizAaA/h0aPyS5Mook5V3iUJNpPLkNABzfY434TUrLEwDwMzXirzMzArYhzAaA/hktD9sfjUKYTXXcLAYAjkWNOACsp0Z8e84XbEWYDQD99Gl5+L40CgAA6C014gCwGTXib3NnBGxLmA0A/fUpZUPbU6QAANAvasQBYD014rszMwK2JcwGgP66T3KxPEw6kAMAQNvUiAPAemrE98PZg60JswGg3x4D7XEE2gAA0Bo14gCwGTXi++UcwtaE2QDAZHlY/6eH137i46fCL3fnxgAAvJEacQBYT4344cyMgG0JswGApNzk+jPJ3z380gIAAC2YL8/1w7hhDAAvUSN+HM4mbE2YDQA8GqaEu5dGAQAAnXGdEmLfGAUAvEiN+PFMjYC3EGYDAN8aJDmNmmMAAKjZNOVhVDXiAPAyNeJ1mBkBbyHMBgB+9D7lvb2qlgAAoB5qxAFgPTXi9ZkYAW8hzAYAfnS/PPCP46lVOLSZEQAAP1AjDgDrqRGvlzCbNxFmAwAvHTLfJ/liFHBQMyMAAKJGHAA2oUa8G2ZGwFu8e3h4MAUA4CWDJFetn4d8zFTkIh4iAYC+UiMOAOupEe8e9954E5vZAMAqo5SnXD8aBQAA7IUacQBYT414N02NgLcSZgMA63xKcurLAgAA7IwacQBYT4149znn8GbCbABgE4Mk46hvAgCAbS1Smo9GSSbGAQDPUiPelrER8FbCbABgE/cp7/KdxZOwsE9ubANAe25TAmw14gDwMjXibZoZAW8lzAYANvUYaI8j0IZ9/nMGAHTfNE9b2H6/A8Dz1Ii3b2YEvNW7h4cHUwAAXmOQ5Kqh6/k9tmGpiwM6AHSTGnEAWE+NeL+8MwLeymY2APBaoySnSf5q6EsUAABsS404AKynRrx/5kbALgizAYBtfE4JtC+NAgCAHlIjDgDrqRHvt5kRsAvCbABgW4PllxKVUAAA9IEacQBYT404j5yX2AlhNgDwFhfLg+mvRgE7c5fk3BgAoBpqxAFgPTXi/GhmBOyCMBsAeIv75ZeVcdRFAQDQjnmSYdSIA8AqasRZxWY2OyHMBgB2cTB9n+RLR3/+Ux8hAAApNeI3KSG2m68A8Dw14mzKeYqdEGYDALswTvIhyVUHf/ZTHx8AQK/dpoTYI6MAgBepEec1FtFuw44IswGAXRmlvEP70igAAKjcY434TbzPEQBeokacbdnKZmeE2QDALg1SNp3PjQK25sllANgPNeIAsJ4acXbBWYudEWYDALv2PqV23Bce2P4Ln9o2ANgdNeIAsJ4acXbJg/rsjDAbANjHYfV9SiCnggoAgGNQIw4A66kRZ1/GRsCuCLMBgH2Ypbw/+2sHftYTHxcAQBPUiAPAemrEOYSZEbArwmwAYF8mST4kuar85zzzUQEAdJoacQBYT404hzQzAnZFmA0A7NMoyWmSv4wCAIAdUiMOAOupEecY7oyAXRJmAwD79jkl0L40CtiIWlQAeN5jjfgo3sMIAC9RI86xzYyAXRJmAwCH8CnlaWBfomC9eyMAgO/cpQTYN35PAsCL1IhTi5kRsEvCbADgEO6TXCwPs2qtAABYZ54SYI/ihigAvESNODUaGwG7JMwGAA7lMdAe+4IFAMAz1IgDwHpqxKmdJh126t3Dw4MpAACH9D7JP7WdiXwsVOQiyRdjAKBH1IgDwHpqxOkK99nYKZvZAMCh3ST5M8nfRgEA0FtqxAFgPTXidM3UCNg1YTYAcAzD5ReyS6OAn4yNAIBGqREHgPXUiNNlMyNg14TZAMCxDJKcJjk3CgCApqkRB4D11IjTgokRsGvCbADg2F/UxvGkMQBAa9SIA8B6asRpjTCbnRNmAwDHdL/8wjb2pQ0AoAnXKRvYN0YBAM9SI07LtPCwc+8eHh5MAQA4toskX4749/89nhylLg7pAHTJNMkwasQBYBU14vTBOyNg12xmAwA1GCf5kOTqSH//Ex8BlVlEWwEAdZunhNfDqBEHgJeoEadv50PYOWE2AFCL0fJL3kejgEySnBsDABVSIw4Aq6kRp69mRsA+CLMBgJp8SnIalVsAADVRIw4A66kRp+/GRsA+CLMBgNoMlodfTy8DAByPGnEAWE+NODxxZmQvhNkAQG3uk1wsD8C+CAIAHJYacQBYTY04PG9mBOyDMBsAqNFjoD3OYQLtUyMHAHpMjTgArKdGHFYbGwH7IMwGAGo1SXmH9tUB/l6nxk1lZknOjQGAPVIjDgDrqRGHzSyMgH0RZgMANRulBM1/GQU9MzMCAPbkdnnGUiMOAM9TIw6vNzEC9kWYDQDU7nNKoH1pFAAAW5mmBNijqBEHgJeoEYftCbPZG2E2ANAFg5RqL09EAwBsZpGnANvNRQB4nhpx2I2ZEbAvwmwAoCsuUm7E/moUAAAvUiMOAKupEYfd8/AkeyPMBgC64j6l8muc3T8tfWK8AECHqREHgPXUiMP+CLPZm3cPDw+mAAB0yUWSLzv+z7xb/udCy/89B6AtasQBYD014nCYc6lFEfbGZjYA0DXjJB+SXBkFANBDasQBYDU14nBYHqxkr4TZAEAXjVI2Vy+NAgDoATXiALCeGnE4jpkRsE/CbACgqwZJTpOcGwUA0CA14gCwnhpxOL6ZEbBPwmwAoMvep9SOqw0DAFpxm1IhPjIKAHiWGnGoy9gI2CdhNgDQZfcpgfYknsCmvf9uA9Af8yTDlBB7ZhwA8Cw14lAn51f26t3Dw4MpAABdd5bk61vPRcZIZRzUAdq2SAmvh1EjDgCrvu8PokYcauaeGntlMxsAaMEkyYckV0YBAFROjTgArKZGHLrjzgjYN2E2ANCKUZLTJH8ZBQBQGTXiALCeGnHoHmdb9k6YDQC05HNKoH1pFADAkakRB4D11IhDt82MgH0TZgMArfm0/DKsigwAOAY14gCwmhpxaIeHNtk7YTYA0Jr7JBfLw/SvxkGHzf13GKBTf2arEQeA1dSIQ3ucfdm7dw8PD6YAALToLMk4m9eU/R5Pk1KXcZJzYwColhpxANjsu/kgasShVe+MgH2zmQ0AtGqy/LL8z4b/9ydGBgBs4C6lQnxkFADw4vfrQdSIQ+umRsAhCLMBgDVtZ8AAACAASURBVJbdJPkzyd9GAQC8wTxPAfbMOADgWWrEoV+cizkIYTYA0LphSq3ZpVEAAK/wWCM+Snn1AwDwMzXi0F9etcNBCLMBgD4YJDmN9w8DAOs91ojfJLk3DgD4iRpxILGZzYEIswGAvnifslXlizZdMY4HMAAORY04AGz2vXoQNeJA4dzMQQizAYC+uF9+6R7n+eqzUyMCgF5RIw4A66kRB17iDM1BCLMBgD6ZJLlI8vWZ/92p8QBAL6gRB4DV1IgD68yNgEMRZgMAfTNJ8iHJlVEAQG+oEQeA9dSIA5typuZghNkAQB+NUqrSPhoFADRLjTgArKdGHNiG8zUHI8wGAPrqU0q1uCfOqZXqW4DtTJMMo0YcAF6iRhx4q5kRcCjCbACgzwYpT5L68k6NJkYAsLF5Sng9jBtrAPASNeLArjhzczDCbACgz+6TXCwP4CfGAQCdc50SYt8YBQA8S404sA8ewOdghNkAQN89BtqfjQIAOkGNOACspkYc2KeFcziHJMwGAChPk34yBgColhpxAFhPjThwCLayOShhNgBAMTMCAKiOGnEAWE2NOHAoizw9YAoHI8wGAIA6zYwA6Ck14gCwmhpx4JDmy/P5yPmcY3j38PBgCgAAUCeHdaAv1IgDwHpqxIFDuk4JsMdGwTHZzAYAAACORY04AKymRhw4JFvYVEeYDQAAABzSNOXm2ChukAHAc9SIA4dmC5tqCbMBAACAfVvkKcCeGAcAPEuNOHBI82/O6DPjoFbCbAAAAGBfblNujqkRB4DnqREHnNFhBWE2AADUaxq1gkA3/+waRY04ALxEjThwaLaw6SxhNgAA1EsIBHSFGnEAWE+NOHBod0mGsYVNhwmzAQAAgG2pKASA1dSIA4f2+KDpMLawaYAwGwAAAHgNNeIAsJoaceAY7r45p0MzhNkAAADAOmrEAWA9NeLAsc7ptrBpljAbAADqZeMRODY14gCwmhpx4BhsYdMbwmwAAKjXJLY6gMObp2x2jOKhGgB4jhpx4BgWKQ+ZDqMtiR4RZgMAAABujAHAemrEgWOYLs/pN/GwKT0kzAYAAID+uk25KTYyCgB4lhpx4Bg8bApLwmwAAADol8ca8ZskM+MAgJ+oEQeOeVb/HFvY8P8JswEAAKB9NjsAYD014sCxXKe0JY2NAr4nzAYAgHrNjAB4IzXiALCaGnHgWB4bk0axhQ0vEmYDAEC9ZkYAbEGNOACspkYcOCZb2PAKwmwAAADoPjXiALCeGnHgWGxhw5aE2QAAANBdasQBYDU14sCxz+uj5Zkd2IIwGwAAALplnnJDbBQ14gDwHDXigPM6NEKYDQAAAPV7rBEfxbv1AOAlasSBY7KFDXvw7uHhwRQAAKBOJ0n+xxig1+7ydEPMu/UA4GdqxIFjWuTpXdgz44DdE2YDAEDdHNihf9QSAsBqasSBY7v75swO7JGacQAAADg+NeIAsJ4aceDYZ/ZRyib2zDjgMITZAAAAcDxqxAFgNTXiQC1n9pFRwOEJswEAAOCw1IgDwGpqxIFje2xO+uzMDsclzAYAAID9UyMOAOupEQeObZpSI645CSohzAYAgLrdJTk3Buj0P8OjuBkGAC9RIw4c2+ODp8MkE+OAugizAQAAYLfUiAPAamrEgRrYwoYOEGYDAADAblyn3Ai7MQoAeJYacaCWc7stbOgIYTYAAABszzYHAKymRhyowXx5bh85t0O3CLMBAADgdeZ5eqfezDgA4CdqxIFaXKcE2GOjgG4SZgMAQN1mSc6NAaqgRhwAVlMjDtTAFjY0RJgNAAB1mxkBHJUacQBYTY04UIvb5dl9bBTQDmE2AAAAfE+NOACspkYcqOnsPlr+5ewODRJmAwAAQKFGHABWUyMO1OI2JcB2dofGCbMBAADoMzXiALCaGnGgFrawoYeE2QAAAPTNIuUGmBpxAHieGnGgJnd5egAV6BlhNgAA1G1iBLAzqggBYDU14kAtPIAKJBFmAwBA7dQew9tM81RF6J8nAPiZGnGgJnffnN8BhNkAAAA053GLYxTtBgDwHDXiQI3nd1vYwE+E2QAAALRCjTgArKZGHKjJNCXAHhkF8BJhNgAAAF2mRhwAVlMjDtRkkfLw6TBalIANCLMBAADoGjXiALCaGnGgNo9b2DfxECrwCu8eHh5MAQAA6ubQDoUacQBYTY04UBNb2MCb2cwGAACgZmrEAWA1NeJAbeZ5ehe2MzzwJsJsAAAAaqNGHABWUyMO1Oh6eYYfGwWwK8JsAAAAanGbUkM4MgoAeJYacaA2trCBvRJmAwAAcEyPN79uksyMAwB+okYcqJEtbOAghNkAAFC/eZJfjYGGLFLC62HUiAPAc9SIA7V+Nx0tz/G2sIGDEGYDAED9ZhFm0wY14gCwmhpxoNZz/Gh5lgc4KGE2AAAA+6RGHABWUyMO1HqOHy3/co4HjkaYDQAAwK6pEQeA1dSIA7WyhQ1URZgNAADArqgRB4DV1IgDNVrk6V3YM+MAaiLMBgAA4C3UiAPAamrEgVrd5alKHKBKwmwAAKjfJMm5MVARNeIAsJoacaDms/wotrCBjhBmAwBA/e6NgEo8bm7c+O8lADxLjThQ+1l+ZBRAlwizAQAAWGWep5teM+MAgJ+oEQdq9dio9NlZHugqYTYAAAA/erzpNUoyNg4A+IkacaBm05QacY1KQOcJswEAAHikRhwAVlMjDtTq8YHUYZKJcQCtEGYDAAD0mxpxAFhNjThQM1vYQNPePTw8mAIAANTtIskXY2CH1IgDwGpqxIHaXTvPA31gMxsAAKA/1IgDwGpqxIGazVO2sEfO80BfCLMBAADapkYcAFZTIw7UzhY20FvCbAAAgDa54QUAL1MjDtTOFjZAhNkAAAAtmabc8FIjDgDPUyMO1O42T68GAug9YTYAANRPKMkq85QbXcOoEQeA56gRB7pwph/Fq4EAfvLu4eHBFAAAoH4O7vzoOiXEtrEBAD9TIw50gS1sgDVsZgMAAHSHGnEAWE2NOFA7W9gAryDMBgAAqJsacQBYTY040AV3eQqxAdiQMBuALjtZ/qvNNABapEYcAFZ/HxxEjThQt0VKeO3BVIAtCbMB6LJvn74HgBaoEQeA1dSIA11gCxtgR4TZAHTZfZLL5b9+Mg6gcdPYOmqVGnEAWE2NONAFtrAB9kCYDUCXTZb/+nH5P4+MBGiYLd32qBEHgJepEQe6QrsSwB4JswFoxVXKU69jowCgYtM81Q260QUAP1MjDnTBIk/tShPjANgfYTYALblJcuFLBACVeawbHPkdBQDPUiMOdIUtbIADE2YD0JJfUoKCC18oAKjA7fL3khpxAPiZGnGgK2xhAxyRMBuAFr5QfPvk/m8pVeNnRgPAEagRB4DV1IgDXTFPCbCd7QGOSJgNQNdNkpz/8O/9tvyiMTAeoCHjZ/68ow5qxAFgNTXiQJdcL8/2Y6MAOD5hNgCtukwyS/LZKADYEzXiAPAyNeJAl9jCBqiUMBuAlv2VEmiPjAKAHVEjDgCrqREHusQWNkDlhNkAtG6YUvmq9hWAbakRB4DV1IgDXTL/5nw/Mw6AugmzAei6dVtxv6Q8XXvmCwoAr6RGHABepkYccL4HYO+E2QB03STr6+t+WX5RuYhKWKC7/Pl1GI/vyruJh6AA4DlqxIGune9HsYUN0FnCbAD64rc8BdoAXaTeen8Wy98RQ3MGgGepEQe65i5PD6kC0GHCbAD65DzlSdyBUQCQUjN4s/zdAAB8T4040DWL5dl+GFvYAM0QZgPQN5cp79AeGQVAL6kRB4DV1IgDXXOXpypxABojzAag67Z5h+zV8v9P1RRAP6gRB4DV1IgDXTzjj2ILG6B5wmwAum7bUGKU8v5soQZAu9SIA8DL1IgDXWQLG6BnhNkA9NUvKXXjp9luuxvg0Dx8sxk14gCwmhpxoGs0LQH0mDAbgD57DLQvItAG6ufPqZe5uQUAq6kRB7pomqcHVX0fAugpYTYAfffb8ovRwCgAOkeNOAC8TI040EUeVAXgO8JsALpuF0/mXi7/cz4ZJ0D15nl6R97MOADgJ2rEga6e8z/HFjYAP3j38PBgCgB03a5+mX2I7T6gH3/edc3jdsYo5fUQAMD31IgDXXXtnA/AKsJsAFqwy19mf/gCBfTkz7suuEu5sWU7AwB+pkYc6Kp5So34yDkfgHWE2QC0YJe/zBZJLuK9TECdxknOG79GNeIAsJoacaCrbGED8GremQ0A3/tl+cXqIp4OBjgUNeIAsJoacaCrbGED8CbCbABasMhub+j8lhKmnBktwF6pEQeAl6kRB7rs9puzPgBsTZgNQAsm2X3t7m/LL10D4wXYKTXiALCaGnHAWR8AloTZAPCyy+WXr89GAfAmasQBYDU14kCX2cIGYG+E2QCw2l8pgfbIKIAKdK2KW404ALxMjTjQZYs8vQt7ZhwA7IswGwDWG6ZUmU+MAjiySeqvHJ2nhNfDuKkFAM9RIw502eMDqyOjAOAQhNkAtGDf236/pNTinkUwA/CS65QQW7UgAPxMjTjQZYuU8NoDqwAcnDAbgBYcYlPxl5SA5iKqcgEeTVNuaKkRB4CfqREHus4WNgBHJ8wGgM39lqdAG6Cv1IgDwGpqxIEuWyzP+5+d9wGogTAbAF7nPOWJ5IFRAD2jRhwAXqZGHOg6rUsAVEmYDQCvd5nyDu2RUQAHNjvw388NLQB4mRpxoOset7CHKa9wA4DqCLMBaMExApar5d/XhiJwSLMD/D3UiAPAamrEga7z0CoAnSHMBqAFx3p6eJTy/mxPLwMtUCMOAC9TIw60cua3hQ1ApwizAWB7v6TUjZ/Gk8xAN9nIAICXqREHWjBfnvlHzvwAdJEwGwDe5jHQvvClEOiIRcqNLDXiAPA8NeJAC66X5/6xUQDQZcJsAHi731JCoYFRABW7TbmZpUYcAH6mRhxogS1sAJojzAagBTV8Qbtc/hyffBzAHo1f+X8/TbmRNYqbWQDwIzXiQCtuU0LssVEA0Jp3Dw8PpgBAC2r5hfYhJTQCONafd4814qMkE+MCgJ+oEQdaMP/m3D8zDgBaJcwGoBU1/UL7I56GBg7/550acQB4mRpxoBXO/QD0ijAbgFbU9AttkeQiNiKB/f95p0YcAF6mRhxohS1sAHpLmA1AK2r7hTZNCbSFS8Cu3UeNOACsokYcaMVdyruwbWED0FvCbABacZ/66gKnKXWGAADAfqkRB1qxSHlwdRhb2AAgzAagGeMk5xX+XNcpN9QAAIDdUiMOtOQuTw1MAMDS/zYCANiry5QnqT8bBQAA7IQacaAVtrABYA1hNgDs31/LL6UjowAAgK2oEQdaMk0JsEdGAQCrCbMB4DCGSSbLvwAAgPXUiAMtWSS5ydP9AQBgA8JsAFpxX/nP90vKe73PojoMAABWUSMOtORxC/sm9d+7AIDqCLMBaMUk9d/s+mX55fXCF1gAAPiOGnGgJbawAWBHhNkAcFi/5SnQBgCAPlMjDrRmnqd3YXuIHQB2QJgNAId3vvxiOzAKAAB6SI040Jrr5ff8sVEAwG4JswHgOC6XX3JHRgEAQA+oEQdaYwsbAA5AmA1AK7r4xfFq+XPf+PgAAGiQGnGgRbawAeCA3j08PJgCAC04S/K1gz/3IuX92RMfIQAAjVAjDrRmnhJgD2MLGwAOSpgNQEuGST528OdeJDn1hRgAgA5TIw606DYlxNaoBgBHIswGoDXjJOcd/LmnKRvaAm0AALpCjTjQosct7FGSmXEAwHEJswFozUlKZfevHfzZb1MqGQEAoGZqxIEW2cIGgAoJswFoUVffn50k/0nyyUcIAECFZ+xB1IgDbVnk6V3YM+MAgPoIswFo1SDJVUd/9g/LL9MAAHBMasSBVt3lqUocAKiYMBuAlo2SXHb0Z/8j5f3fAABwaGrEgRbZwgaADhJmA9C6Sbq5RbJIcrH8+QEAYN/UiAOtsoUNAB0mzAagdScpT1x38YbcPOWm4r2PEQCAPZ2VB1EjDrRnkeQmyefYwgaAThNmA9AHZ0m+dvRnny5/fgAA2BU14kCrpik14jfxYDgANEGYDUBfDJJcdfRnv17+/AAAsC014kCrHrewh/GqLgBojjAbgD4ZJbns6M/+75R6NAAA2JQacaBltrABoAeE2QD0yUmScbp7I+9DSiAPAACrqBEHWna9/G48NgoAaJ8wG4C+OU2pHetqteLvUZsGAMDP1IgDLZunbGGPYgsbAHpFmA1AH10k+dLRn32RcqNy5mMEAOg9NeJA62xhA0DPCbMB6KtPSf7u6M8+TQnkPY0OANBPasSBltnCBgD+P2E2AH02SnLZ0Z/9LiXQBgCgH9SIA627XX5PvzEKAOCRMBuAPjtJqSrraiXjdcrNTAAA2j2vDqJGHGjXPCXAHsXrtACAZwizAei7s5RAu6vbLX+m1K8BANAONeJA62xhAwAbEWYDQLlZ+E+Hf/5/uQEAANB5asSB1tnCBgBeTZgNAMXnJH919GdfpLw/e+JjBADoFDXiQB/c5SnEBgB4FWE2ADy5SXerHBdJTpPc+xgBAKqnRhxo3SIlvB7GFjYA8AbCbAB4cpLy/uyubsVMUza0BdoAAPVRIw70gS1sAGCnhNkA8L2zlEC7qzcYb1M2fQAAOD414kAf2MIGAPZGmA0APxskuerwz/+fJJ98jAAAR6NGHOiDaUqAfRMNYQDAngizAeB5wyQfO/zzf4haNwCAQ1IjDvTBIiW8HiaZGAcAsG/CbAB42TjJeYd//j+W1wAAwH6oEQf6whY2AHAUwmwAeNlJypPmv3b0518kuYin5QEAdk2NONAHtrABgKMTZgPAamcp281drYqcL6/Bk/MAAG8/Fw6iRhxo3zwlwB75LgkAHJswGwDWGyS56vDPP025+QoAwOuoEQf65DolwB4bBQBQC2E2AGxmmORjh3/+65SbsAAArKdGHOgLW9gAQNWE2QCwuUm6vZHz7ySffYwAAM9SIw70iS1sAKAThNkAsLmTJLN0++bmh5QbFgAAqBEH+mW+/D44Wn63BQConjAbAF7nLMnXjl/D7ylb5gAAfaVGHOiT25QA+8YoAICuEWYDwOsNklx1+OdfpITyMx8lANAjasSBPrGFDQA0QZgNANsZJbns8M8/TXKR5N5HCQA0TI040Dd3SYaxhQ0ANEKYDQDbm6TbN0XvUgJtAIDWqBEH+mSR8sD1MLawAYDGCLMBYHunKYF2l2sqr1Nu9AIAdJ0acaBv7vJUJQ4A0CRhNgC8zUWSLx2/hj9TnuAHAOgaNeJA39jCBgB6RZgNAG/3KcnfHb+Gf8U71QCA7lAjDvSNLWwAoJeE2QCwG6Mklx3++RcpW+YTHyUAUCk14kDfLFIeOh76rgYA9JUwGwB24yTJON2ut1ykvAf83scJAFR0xhpEjTjQL9OUAPvG9zMAoO+E2QCwO6cpT8t3eVNomrKh7YYJAHBMasSBvrGFDQDwDGE2AOzW+yT/dPwabpfXAQBwSGrEgT6aJ/kcW9gAAM8SZgPA7n1O8lfHr+E/ST75KAGAPVMjDvTVdZJRyuuqAAB4gTAbAPbjJt2vxfyQcnMFAGDX1IgDfTRPqREfxRY2AMBGhNkAsB8nKU/Yd33D6I/YFAAAdkONONBXtrABALYkzAaA/TlLuVnR5Zu1iyQXSSY+TgBgC2rEgb6yhQ0AsAPCbADYr/dJ/un4NcxTgnk3YACA15yBBlEjDvTPbUqAfWMUAABvJ8wGgP37nOSvjl/DNCXQBgB4iRpxoK/mKQH2KMnMOAAAdkeYDQCHMU5y3vFruE65OQ0A8EiNONBntrABAPZMmA0Ah3GS8t7pXzt+Hf9O2TQHAPpNjTjQV4s8vQt7ZhwAAPslzAaAwzlL2dDueu3mh5QbNwBA/84yg6gRB/rpLk9V4gAAHIgwGwAOa5DkqoHr+D1l0xwAaJsacaDPFinh9TC2sAEAjkKYDQCHN0zysePXsEjZzpr5OAGgSWrEgT6zhQ0AUAlhNgAcxzjJecevYZrkIsm9jxMAmqBGHOizRZKbJJ/joV0AgGoIswHgOE5SbpB0/UbxXUqgDQB090wyiBpxoL+mKe1ZN/GgLgBAdYTZAHA8Z0m+NnAd1yk3wAGA7lAjDvTZ4xb2MMnEOAAA6iXMBoDjGiS5auA6/ky5EQQA1EuNONB3trABADpGmA0AxzdKctnAdfwr5aYQAFAPNeIApU3KFjYAQAcJswGgDpN0/wbzIuX92W4QAcDxqREH+m6eEmCPYgsbAKCzhNkAUIeTJLN0v/JzkeQ0bhYBwDGoEQcoW9ijJGOjAADoPmE2ANTjLMnXBq5jmrKhLdAGgP1TIw5gCxsAoFnCbACoy6ckfzdwHbcp9aYAwH6oEQco3zuGsYUNANAsYTYA1GeU5LKB67hOuckOAOyGGnGAsoU9Wv41Mw4AgLYJswGgPicpmwUtVIV+SLnJBABsfy4YRI04wO3yu8WNUQAA9IcwGwDqdJpkkja2rv6I2j8AeC014gC2sAEAek+YDQD1ukjypYHrWCyvZeIjBYCV1IgDFHcp78K2hQ0A0HPCbACo26ckfzdwHfOUG/T3PlIA+I4acYBikbKBPYwtbAAAloTZAFC/m7RRMTpN2dAWaAOAGnGAR3d5qhIHAIDvCLMBoH4nKe+cbmFb6zrlxj0A9JEacYDCFjYAABsRZgNAN5ylBNot3Pj+d5LPPlIAekKNOMCTaUqAPTIKAAA2IcwGgO54n+SfRq7lQ9zAAqD939uDqBEHWKS8OmmYZGIcAAC8hjAbALrlc5K/GrmW3+NmFgBtUSMO8ORxC/smyb1xAACwDWE2AHTPTdrY8lokuYhAG4BuUyMO8P0Z3xY2AAA7I8wGgO45Sbkx9GsD1zJNCbRtagDQNWrEAZ7M8/QubGd7AAB2RpgNAN10lmScNipM71ICbQDowu/fQdSIAzy6Tgmwx0YBAMA+CLMBoLsGSa4auZbr5fUAQG3UiAN8zxY2AAAHI8wGgG4bJvnYyLX8ubweAKiBGnGA79nCBgDg4ITZANB94yTnjVzLh5QbZABwDGrEAb43X57Ph7GFDQDAEQizAaD7TpJMkvzawLUsUt6fPfGxAnDA36ODqBEH+NZtSoh9YxQAAByTMBsA2nCWsqHdwhbZIslpbH4AsF9qxAG+97iFPUoyMw4AAGogzAaAdgySXDVyLdOUDW2BNgC7pEYc4Ge2sAEAqJYwGwDaMkpy2ci13KZszQHAW6gRB/jZIk/vwp4ZBwAAtRJmA0B7JmnnZv11SvgAAK+lRhzgZ3d5qhIHAIDqCbMBoD0nKdsVrdSnfoibbQBsRo04wM9sYQMA0FnCbABo01mSrw1dzx9Jxj5WAJ6hRhzgebawAQDoPGE2ALRrkOSqkWtZJLlIqVAHgESNOMBL5+abJJ9jCxsAgAYIswGgbaMkl41cyzxl4/zexwrQW2rEAZ43TakRv3FeBgCgJcJsAGjbSUo9dyu1q9OUDW036AD69btsEDXiAD963MIeRoMRAACNEmYDQPtOU25utbLBdp0SaADQNjXiAM+zhQ0AQG8IswGgHy6SfGnoev6d8h5AANqiRhzgZdcprxEaGwUAAH0hzAaA/viU5O+GrudDys08ALpNjTjAy+YpW9ij2MIGAKCHhNkA0C+jJJcNXc/v8X5AgK5SIw7wMlvYAAAQYTYA9M1Jyg2xVjbfFikV6gJtgG5QIw7wMlvYAADwA2E2APTPWUqg3UqIME0JtN3wA6iTGnGA1W5TAuwbowAAgO8JswGgn94n+aeh67lLCbQBqOt3zSBqxAGeM08JsEdJZsYBAADPE2YDQH99TvJXQ9dznRKaAHA8asQBVrOFDQAAryDMBoB+u0lbG3N/prxnEIDDUSMOsJotbAAA2JIwGwD67STl/dkthQ8fUm4UArBfasQBVrvLU4gNAABsQZgNAJylBNqt1MEuUt6fPfHRAuzld8YgasQBVp1FRyltQTPjAACAtxFmAwBJ2a77p6HrWSQ5TXLvowV4MzXiAOvZwgYAgD0QZgMAj4ZJPjZ0PdOUDW2BNsB21IgDrGYLGwAA9kyYDQB8a5zkvKHruU0JYwDYjBpxgPWmKQH2TTw4CQAAeyXMBgC+dZLyrulfG7qm65RQBoCX/+wfRI04wCqLlPB6uDwvAwAAByDMBgB+dJayod3SRt6HeH8hwI/UiAOsZwsbAACOSJgNADxnkOSqsWv6IyWkB+gzNeIA69nCBgCASgizAYCXDJN8bOh6Fkku4oYk0D9qxAE2M1+egUexhQ0AAFUQZgMAq0zSVvAxT9lKdHMS6AM14gCbuU4JsMdGAQAAdRFmAwCrnCSZpa0q2mnKhrZAG2iRGnGAzdjCBgCADhBmAwDrnCX52tg1XacEPQAtUCMO8Lpz4Ci2sAEAoBOE2QDAJgZJrhq7pn8n+eyjBTpMjTjAZuYpAfYopXUIAADoCGE2ALCpUZLLxq7pw/K6ALpCjTjA5m6XZ70bowAAgG4SZgMArzFJexW2vy+vC6BWasQBNmcLGwAAGiLMBgBe4zQl+G1pG3CR5CICbaA+asQBNneXZBhb2AAA0BRhNgDwWhdJvjR2TdPldd37eIEjUyMOsLlFygb2MLawAQCgScJsAGAbn5L83dg13aUE2gCHpkYc4PXnttHyLwAAoGHCbABgW6Mkl41d03VKmARwCGrEATZnCxsAAHpImA0AbOskyTjtbRH+mXKTFGAf1IgDvI4tbAAA6DFhNgDwFqdJJmkvkPkQN0yB3VEjDvA6iyQ3KQ8YTowDAAD6S5gNALzVRZIvjV3TYnldbp4Cb6FGHOB1pikB9k2Se+MAAACE2QDALnxO8ldj17RIqQOe+XiBV1AjDvD6M5ctbAAA4FnCbABgV27S3vbhNGVD22YQsIoacYDXm6c8EGkLGwAAeJEwGwDYlZMk47QX5NymsHvB4AAAFSJJREFUVAUD/EiNOMDrXScZLc+NAAAAKwmzAYBdOku5Mdlate51SmAFoEYc4PXmKTXio9jCBgAAXkGYDQDs2vsk/zR4XR9SbsAC/aNGHGA7trABAIA3EWYDAPvwOclfDV7Xv1Le6wj0gxpxgNezhQ0AAOyMMBsA2JdxkvPGrmmR5CLJxMcLzVIjDrCd25QA24N/AADAzgizAYB9OUkJfX9t7LrmKWGXTSNo68+rQdSIA2xzLhot/5oZBwAAsGvCbABgn85SNrRb226cpmxoC7Sh29SIA2zHFjYAAHAQwmwAYN8GSa4avK7r5bUB3aJGHGA7izy9C3tmHAAAwCEIswGAQxgm+djgdf0nyScfL1RPjTjA9u7yVCUOAABwUMJsAOBQxknOG7yuD3FzF2qlRhxgO4vl+WYYW9gAAMARCbMBgEM5SbkZ2mKt7+9JJj5iqIIacYDt2cIGAACqIswGAA7pLMnXBq9rkeQiAm04FjXiAG87x9wk+Rxb2AAAQGWE2QDAoQ2SXDV4XdOUQPveRwwHo0Yc4G1nl2FKkO38AgAAVEmYDQAcwyjJZYPXNU3ZPgf2R404wPYet7CH0SgDAAB0gDAbADiWSdqsA75OCdmA3VEjDvA2trABAIBOEmYDAMdykvJexhY3K/9MuWEMvI0acYC3uY4tbAAAoMOE2QDAMZ0l+drotX1IqVMHXv/nwiBqxAG2NU8JsEexhQ0AAHScMBsAOLZPSf5u8LoWSS5iEwo2oUYc4O2uUwLssVEAAACtEGYDADUYJbls8LoWKVumMx8xPEuNOMDb2MIGAACaJswGAGpwkrJF1OJG5jRlQ9sNZijUiAO83W1KiD02CgAAoGXCbACgFqcpldwthlu3KRuo0FdqxAHebp6ygT2K1hcAAKAnhNkAQE0uknxp9NquU4I86BM14gBvd5sSYN8YBQAA0DfCbACgNp+S/N3otX1IuRkNLVMjDvy/9u73vIkz7wLwuWjA6gDeCqxUgN8KQiqwqACoAG8FUSrwqALkCpArQOrA6sDqYD88NkqyBvxnRpp55r4/7XVtssscQZzLx+c3vJwVNgAAQJTZAEA/LVPvkvOPWFZRH2fEAdpxnfIubP+uAAAAEGU2ANBPkySr1FmK7VLOqa99zFTAGXGAdv7doEkpsW/EAQAAsKfMBgD6appSaNd4pnh793y3PmYG+mdzFmfEAV7qOvtT4gAAADxAmQ0A9Nm7JF8qfbZNykJboc0QOCMO0A4rbAAAgCdQZgMAfXeR5HOlz7ZIKQehr5wRB2jHJqXAbkQBAADweMpsAGAIlqm3TPsryUcfMT3ijDhAO3Z3/w4zT7IWBwAAwNMpswGAIZikfBP4daXP9z6WWhz/z9gszogDtOF+hb2M14kAAAC8iDIbABiKaZJV6l2K/harLQ7PGXGAdlhhAwAAdECZDQAMySzJZaXPtktyFt8Ap3vOiAO0Z5v9u7CtsAEAAFqmzAYAhmae5EOlz7ZJKbR9M5y2OSMO0K5FSoG9EgUAAEB3lNkAwBCtkryt9Nk2KctZaIMz4gDtscIGAAA4MGU2ADBEk5Rz3K8rfb5FSgEJz+GMOED7X5ebWGEDAAAcnDIbABiqaco3lWst6z6lrL/gMZwRB2jXNqXAnscKGwAA4GiU2QDAkM2SXFb8fO9TvpEOP+KMOEC7ru6+9i5FAQAAcHzKbABg6Jok55U+2y7JWcpJdbjnjDhAu+5X2E2SG3EAAAD0hzIbAKjBOvWeVt6llJc3PuZRc0YcoH1W2AAAAD2nzAYAajBJKXtrXaluUhba3tk5Ps6IA7Rrl/27sG/EAQAA0G/KbACgFtMk3yp+vquUYpNx/F6exRlxgDZdZ39KHAAAgIFQZgMANZkluaz4+RZ3z0h9nBEHaJ8VNgAAwMApswGA2jRJzit+vvexKquJM+IA7bPCBgAAqIQyGwCozSTJKnWvW/9IsvRRD5Yz4gDt2919bbyIFTYAAEA1lNkAQI3eJFmn3qJwl+Ts7hkZBmfEAbqxSTkjvkxyKw4AAIC6KLMBgFqdJfla8fNtUxa+vnHfb86IA7TvfoU9jx/sAgAAqJoyGwCo2cckf1b8fJuU0l6h3S/OiAN093XPChsAAGBElNkAQO2aJOcVP98ipTTluJwRB+j2a12TZCUKAACAcVFmAwC1m6R887vmgvGvlBU6h+eMOEA3tikr7CZW2AAAAKOlzAYAxmCaUmjXfPL5fco3/DnM76dZnBEH6IIVNgAAAN8pswGAsXiX5Evlz/hbkrWPuhPOiAN0xwobAACABymzAYAxuUjyueLn2yU5i0K7Tc6IA3TnKqXAXooCAACAhyizAYCxWabuYnKTUmhbtj2fM+IA3dmmFNhNkhtxAAAA8DPKbABgbCYp7+Gs+VT0JqWQ5Wm/L2ZxRhygK1bYAAAAPJkyGwAYo2lKoV3z6naRUszyc86IA3THChsAAIAXUWYDAGP1LsmXyp/xU5K5j/p/OCMO0K3r7EtsAAAAeDZlNgAwZvMkHyp/xvdRJiTOiAN0bXf39WYeK2wAAABaoswGAMZuleRtxc+3S3KWZD3Sz9cZcYBuWWEDAADQGWU2ADB2k5Si93XFz7hLOa19M5LP1BlxgO6/rjSxwgYAAKBjymwAgFJ+rlJ38blJWWjfVvp8zogDHOZryTzJsuKvJwAAAPSIMhsAoJgluaz8Ga9TCu2aOCMO0K1dSnk9z3hfWQEAAMCRKLMBAPbmST5U/oyLlPJ3yJwRB+ieFTYAAABHp8wGAPindeo/U/0+5V2nQ+KMOED3rLABAADoFWU2AMA/TZLcpP7F7x8phUXfOSMO0L1tSoHdxAobAACAHlFmAwD8r2mSb5U/4y7l/dnrnuY/izPiAF1bpBTYK1EAAADQR8psAICHzZJcVv6MuyRv0o8VnjPiAIdhhQ0AAMBgKLMBAH6sSXJe+TNuUhbaxyo0nBEHOAwrbAAAAAZHmQ0A8HPr1L8UXqQUyofijDjAYWxTCuwmyY04AAAAGBplNgDAz01SCoDaS9e/knzsOMdZnBEHOISrlAJ7KQoAAACGTJkNAPBrZ0m+juA536eUH21yRhzgMKywAQAAqI4yGwDgcT4m+XMEz/n/efn7VJ0RBzic6yTzWGEDAABQIWU2AMDjNUnOK3/GXcoSff3Ev88ZcYDD/rO6SSmxb8QBAABArZTZAACPN0lZLdde1m5SCu3bR/y1zogDHM519qfEAQAAoHrKbACAp3mTslqu/Xz2JuVc+EOcEQc4HCtsAAAARkuZDQDwdGdJvo7gORcphXXijDjAoVlhAwAAMHrKbACA57lI8nkEz7lIKbKdEQfo3i7JMmWFvRYHAAAAY6fMBgB4vmWUvAC83CalwF4muRUHAAAAFMpsAIDnmyRZxdltAJ7OChsAAAB+QZkNAPAy05RC+0QUADzCNuVVFVbYAAAA8AvKbACAl3uX5IsYAPiJRZIm5QegAAAAgEdQZgMAtOMiyWcxAPA325Qz4k2ssAEAAODJlNkAAO1ZJXkrBoDRs8IGAACAFiizAQDaM0myTvJaFACjY4UNAAAALVNmAwC0a5qyxDsRBcAoXKUU2EtRAAAAQLuU2QAA7ZsluRQDQLW2KQV2k+RGHAAAANANZTYAQDfmST6IAaAqVtgAAABwQMpsAIDurJK8FQPAoO2yfxf2jTgAAADgcJTZAADdmSRZJ3ktCoDBuc7+lDgAAABwBMpsAIBuTZN8EwPAIOxSyut5rLABAADg6JTZAADdmyW5FANAb1lhAwAAQA8pswEADqNJci4GgN7YJVkmuYgVNgAAAPSSMhsA4HDWSU7FAHBUm5Qz4sskt+IAAACA/lJmAwAcziRl/XciCoCDul9hz1N+sAgAAAAYAGU2AMBhTZN8EwPAQVhhAwAAwIC9EgEAwEGtk3wSA0CnFkl+S/kBoiaKbAAAABgky2wAgONokpyLAaA125QVdhPlNQAAAFRBmQ0AcByTJKskp6IAeJFFSoG9EgUAAADURZkNAHA8b1LOjp+IAuBJrLABAABgBJTZAADHdZbkqxgAHuUqpcReiQIAAADqp8wGADi+j0n+FAPAg7YpC+wmyY04AAAAYDyU2QAA/bBM8rsYAL67Simwl6IAAACAcVJmAwD0wyTlbO6pKIARs8IGAAAAvlNmAwD0xzSl0D4RBTAy1ynvwrbCBgAAAL5TZgMA9Mu7JF/EAIzALmWBPY8VNgAAAPAAZTYAQP9cJPksBqBS19mfEgcAAAD4IWU2AEA/LZP8LgagElbYAAAAwJMpswEA+mmS8v7sU1EAA7ZJKbAbUQAAAABPpcwGAOivaUqhfSIKYEB2Kdcl5knW4gAAAACeS5kNANBvsySXYgAG4H6FvUxyKw4AAADgpZTZAAD9N0/yQQxAD1lhAwAAAJ1RZgMADMMqyVsxAD2xzf5d2FbYAAAAQCeU2QAAwzBJWT2+FgVwRIuUAnslCgAAAKBrymwAgOGYphRIJ6IADsgKGwAAADgKZTYAwLDMklyKATgAK2wAAADgqJTZAADD0yQ5FwPQge3dP2PmscIGAAAAjkyZDQAwTOskp2IAWnKVUmIvRQEAAAD0hTIbAGCYJklu4v3ZwPPdr7Cbu3+eAAAAAPSKMhsAYLimSb6JAXgiK2wAAABgEJTZAADDNktyKQbgF3bZvwv7RhwAAADAECizAQCGr0lyLgbgAdfZnxIHAAAAGBRlNgDA8E2SrJKcigKIFTYAAABQCWU2AEAd3iRZJzkRBYyWFTYAAABQFWU2AEA9zpJ8FQOMyi7JMslFrLABAACAyrwSAQBANVZJPokBRmGT5H3KVYZZFNkAAABAhSyzAQDq0yQ5FwNU536FPU95rQAAAABA1ZTZAAD1maSstE9FAVXYpBTYyyS34gAAAADGQpkNAFCnNynLzRNRwGAtUi4trEQBAAAAjJEyGwCgXu+SfBEDDMo2ZYXdxAobAAAAGDllNgBA3S6SfBYD9J4VNgAAAMC/KLMBAOq3TPK7GKB3rLABAAAAfkKZDQBQv0nK2vNUFNALVykF9lIUAAAAAD+mzAYAGIdpSqF9Igo4im1Kgd0kuREHAAAAwK8pswEAxuNdki9igIOywgYAAAB4JmU2AMC4zJN8EAN0ygobAAAAoAXKbACA8VkleSsGaN119iU2AAAAAC+kzAYAGJ9JknWS16KAF9ullNfzWGEDAAAAtEqZDQAwTtOUhfaJKOBZrLABAAAAOqbMBgAYr1mSSzHAo1lhAwAAAByQMhsAYNzmST6IAX5qc/dnZZnkVhwAAAAAh6HMBgBgneRUDPAPu5Tyen73ZwQAAACAA1NmAwAwSTmZ7P3ZYIUNAAAA0BvKbAAAkmSa5JsYGCkrbAAAAIAeUmYDAHBvluRSDIzINqXAbmKFDQAAANA7ymwAAP6uSXIuBiq3uPu9vhIFAAAAQH8pswEA+Ld1klMxUBkrbAAAAICBUWYDAPBvkyQ3SU5EQQWssAEAAAAGSpkNAMBDzpJ8FQMDtU0psJuUH8wAAAAAYICU2QAA/MjHJH+KgQG5Simwl6IAAAAAGD5lNgAAP9MkORcDPWaFDQAAAFApZTYAAD8zSXnX8Kko6JnrJPNYYQMAAABUS5kNAMCvvEmyTnIiCo5sl7LAnscKGwAAAKB6ymwAAB7jLMlXMXAk19mfEgcAAABgJF6JAACAR1gl+Y8YOKBdkr+S/F/KD1M0IgEAAAAYF8tsAACeYpnkdzHQIStsAAAAAJIoswEAeJpJykr7VBS0aJfygxLzlPezAwAAAIAyGwCAJ5umFNonouCFNikF9jLJrTgAAAAA+DtlNgAAz/EuyRcx8AxW2AAAAAA8yisRAADwDMsk/xEDT7BN8j7JmySzKLIBAAAA+AXLbAAAXmKV5K0Y+IlFkubu9woAAAAAPJoyGwCAl5ikLGxfi4K/2aacEW/iXdgAAAAAPJMyGwCAl5qmrG5PRDF6VtgAAAAAtEaZDQBAG2ZJLsUwSlbYAAAAAHRCmQ0AQFvmST6IYTSuUgrspSgAAAAA6IIyGwCANq2SvBVDtbYpBXaT5EYcAAAAAHRJmQ0AQJsmSdZJXouiKlbYAAAAABycMhsAgLZNk3wTw+Dtsn8X9o04AAAAADg0ZTYAAF2YJbkUwyBdZ39KHAAAAACORpkNAEBXmiTnYhiE3d3nNY8VNgAAAAA9ocwGAKBL6ySnYugtK2wAAAAAekuZDQBAlyYpS98TUfTGLskyyUWssAEAAADoMWU2AABdmyb5Joaj26ScEV8muRUHAAAAAH33SgQAAHRsneSTGI5il2SR5LeUHypoosgGAAAAYCAsswEAOJQmybkYDsIKGwAAAIDBU2YDAHAokySrJKei6MwipcReiwIAAACAoVNmAwBwSG9SitYTUbRmm1JgN7HCBgAAAKAiymwAAA7tLMlXMbzYIqXAXokCAAAAgBopswEAOIaPSf4Uw5NZYQMAAAAwGspsAACOpUlyLoZHuUopsVeiAAAAAGAslNkAABzLJKWcPRXFg7YphX+T5EYcAAAAAIyNMhsAgGOaphTaJ6L47iqlwF6KAgAAAIAxU2YDAHBs75J8GXkGVtgAAAAA8C/KbAAA+uAiyecRPvd1yruwrbABAAAA4F+U2QAA9MUyye8jeM5dygJ7HitsAAAAAPghZTYAAH0xSXl/9mmlz3ed/SlxAAAAAOAXlNkAAPTJNKXQPqnkeaywAQAAAOCZlNkAAPTNLMnlwJ9hk1JgNz5OAAAAAHgeZTYAAH00T/JhYL/mXcp7v+dJ1j5CAAAAAHgZZTYAAH21SvJ2AL/O+xX2Msmtjw0AAAAA2qHMBgCgryYpC+fXPfy1WWEDAAAAQMeU2QAA9Nk0ZaF90pNfzzb7d2FbYQMAAABAh5TZAAD03SzJ5ZF/DYuUAnvl4wAAAACAw1BmAwAwBE2S8wP/f1phAwAAAMARKbMBABiKdZLTA/z/WGEDAAAAQA8oswEAGIpJkpt08/7sbUqBPY8VNgAAAAD0gjIbAIAhmSb51uL/3lVKib0ULQAAAAD0izIbAIChmSW5fMHff7/CblKW3gAAAABADymzAQAYoibJ+RP/HitsAAAAABgQZTYAAEO1TnL6i79ml/27sG9EBgAAAADDocwGAGCo3qQU2icP/HfX2Z8SBwAAAAAGSJkNAMCQnSX5evefrbABAAAAoCLKbAAAhu5dkkmssAEAAACgKv8F3qtfY+YVvDIAAAAASUVORK5CYII="
  110214. /***/ }),
  110215. /* 45 */
  110216. /***/ (function(module, exports) {
  110217. module.exports = "HELP";
  110218. /***/ }),
  110219. /* 46 */
  110220. /***/ (function(module, exports) {
  110221. module.exports = "SHARE";
  110222. /***/ }),
  110223. /* 47 */
  110224. /***/ (function(module, exports, __webpack_require__) {
  110225. "use strict";
  110226. Object.defineProperty(exports, "__esModule", { value: true });
  110227. var babylonjs_1 = __webpack_require__(0);
  110228. /**
  110229. * The viewer's "extended" configuration.
  110230. * This configuration defines specific obejcts and parameters that we think make any model look good.
  110231. */
  110232. exports.extendedConfiguration = {
  110233. version: "3.2.0",
  110234. extends: "default",
  110235. camera: {
  110236. exposure: 3.034578,
  110237. fov: 0.7853981633974483,
  110238. contrast: 1.6,
  110239. toneMappingEnabled: true,
  110240. upperBetaLimit: 1.3962634015954636 + Math.PI / 2,
  110241. lowerBetaLimit: -1.4835298641951802 + Math.PI / 2,
  110242. behaviors: {
  110243. framing: {
  110244. type: 2,
  110245. mode: 0,
  110246. positionScale: 0.5,
  110247. defaultElevation: 0.2617993877991494,
  110248. elevationReturnWaitTime: 3000,
  110249. elevationReturnTime: 2000,
  110250. framingTime: 500,
  110251. zoomStopsAnimation: false,
  110252. radiusScale: 0.866
  110253. },
  110254. autoRotate: {
  110255. type: 0,
  110256. idleRotationWaitTime: 4000,
  110257. idleRotationSpeed: 0.17453292519943295,
  110258. idleRotationSpinupTime: 2500,
  110259. zoomStopsAnimation: false
  110260. },
  110261. bouncing: {
  110262. type: 1,
  110263. lowerRadiusTransitionRange: 0.05,
  110264. upperRadiusTransitionRange: -0.2
  110265. }
  110266. },
  110267. upperRadiusLimit: 5,
  110268. lowerRadiusLimit: 0.5,
  110269. frameOnModelLoad: true,
  110270. framingElevation: 0.2617993877991494,
  110271. framingRotation: 1.5707963267948966,
  110272. radius: 2,
  110273. alpha: 1.5708,
  110274. beta: Math.PI * 0.5 - 0.2618,
  110275. wheelPrecision: 300,
  110276. minZ: 0.1,
  110277. maxZ: 50,
  110278. fovMode: 0,
  110279. pinchPrecision: 1500,
  110280. panningSensibility: 3000
  110281. },
  110282. lights: {
  110283. light0: {
  110284. type: 0,
  110285. frustumEdgeFalloff: 0,
  110286. intensity: 7,
  110287. intensityMode: 0,
  110288. radius: 0.6,
  110289. range: 0.6,
  110290. spotAngle: 60,
  110291. diffuse: {
  110292. r: 1,
  110293. g: 1,
  110294. b: 1
  110295. },
  110296. position: {
  110297. x: -2,
  110298. y: 2.5,
  110299. z: 2
  110300. },
  110301. target: {
  110302. x: 0,
  110303. y: 0,
  110304. z: 0
  110305. },
  110306. enabled: true,
  110307. shadowEnabled: true,
  110308. shadowBufferSize: 512,
  110309. shadowMinZ: 1,
  110310. shadowMaxZ: 10,
  110311. shadowFieldOfView: 60,
  110312. shadowFrustumSize: 2,
  110313. shadowConfig: {
  110314. useBlurCloseExponentialShadowMap: true,
  110315. useKernelBlur: true,
  110316. blurScale: 1.0,
  110317. bias: 0.001,
  110318. depthScale: 50 * (10 - 1),
  110319. frustumEdgeFalloff: 0
  110320. }
  110321. },
  110322. light1: {
  110323. type: 0,
  110324. frustumEdgeFalloff: 0,
  110325. intensity: 7,
  110326. intensityMode: 0,
  110327. radius: 0.4,
  110328. range: 0.4,
  110329. spotAngle: 57,
  110330. diffuse: {
  110331. r: 1,
  110332. g: 1,
  110333. b: 1
  110334. },
  110335. position: {
  110336. x: 4,
  110337. y: 3,
  110338. z: -0.5
  110339. },
  110340. target: {
  110341. x: 0,
  110342. y: 0,
  110343. z: 0
  110344. },
  110345. enabled: true,
  110346. shadowEnabled: false,
  110347. shadowBufferSize: 512,
  110348. shadowMinZ: 0.2,
  110349. shadowMaxZ: 10,
  110350. shadowFieldOfView: 28,
  110351. shadowFrustumSize: 2
  110352. },
  110353. light2: {
  110354. type: 0,
  110355. frustumEdgeFalloff: 0,
  110356. intensity: 1,
  110357. intensityMode: 0,
  110358. radius: 0.5,
  110359. range: 0.5,
  110360. spotAngle: 42.85,
  110361. diffuse: {
  110362. r: 0.8,
  110363. g: 0.8,
  110364. b: 0.8
  110365. },
  110366. position: {
  110367. x: -1,
  110368. y: 3,
  110369. z: -3
  110370. },
  110371. target: {
  110372. x: 0,
  110373. y: 0,
  110374. z: 0
  110375. },
  110376. enabled: true,
  110377. shadowEnabled: false,
  110378. shadowBufferSize: 512,
  110379. shadowMinZ: 0.2,
  110380. shadowMaxZ: 10,
  110381. shadowFieldOfView: 45,
  110382. shadowFrustumSize: 2
  110383. }
  110384. },
  110385. ground: {
  110386. shadowLevel: 0.9,
  110387. texture: "Ground_2.0-1024.png",
  110388. material: {
  110389. primaryColorHighlightLevel: 0.035,
  110390. primaryColorShadowLevel: 0,
  110391. enableNoise: true,
  110392. useRGBColor: false,
  110393. maxSimultaneousLights: 1,
  110394. diffuseTexture: {
  110395. gammaSpace: true
  110396. }
  110397. },
  110398. opacity: 1,
  110399. mirror: false,
  110400. receiveShadows: true,
  110401. size: 5
  110402. },
  110403. skybox: {
  110404. scale: 11,
  110405. cubeTexture: {
  110406. url: "Skybox_2.0-256.dds"
  110407. },
  110408. material: {
  110409. primaryColorHighlightLevel: 0.03,
  110410. primaryColorShadowLevel: 0.03,
  110411. enableNoise: true,
  110412. useRGBColor: false,
  110413. reflectionTexture: {
  110414. gammaSpace: true
  110415. }
  110416. }
  110417. },
  110418. engine: {
  110419. renderInBackground: true
  110420. },
  110421. scene: {
  110422. flags: {
  110423. shadowsEnabled: true,
  110424. particlesEnabled: false,
  110425. collisionsEnabled: false,
  110426. lightsEnabled: true,
  110427. texturesEnabled: true,
  110428. lensFlaresEnabled: false,
  110429. proceduralTexturesEnabled: false,
  110430. renderTargetsEnabled: true,
  110431. spritesEnabled: false,
  110432. skeletonsEnabled: true,
  110433. audioEnabled: false,
  110434. },
  110435. defaultMaterial: {
  110436. materialType: 'pbr',
  110437. reflectivityColor: {
  110438. r: 0.1,
  110439. g: 0.1,
  110440. b: 0.1
  110441. },
  110442. microSurface: 0.6
  110443. },
  110444. clearColor: {
  110445. r: 0.9,
  110446. g: 0.9,
  110447. b: 0.9,
  110448. a: 1.0
  110449. },
  110450. imageProcessingConfiguration: {
  110451. vignetteCentreX: 0,
  110452. vignetteCentreY: 0,
  110453. vignetteColor: {
  110454. r: 0.086,
  110455. g: 0.184,
  110456. b: 0.259,
  110457. a: 1
  110458. },
  110459. vignetteWeight: 0.855,
  110460. vignetteStretch: 0.5,
  110461. vignetteBlendMode: 0,
  110462. vignetteCameraFov: 0.7853981633974483,
  110463. isEnabled: true,
  110464. colorCurves: {
  110465. shadowsHue: 0,
  110466. shadowsDensity: 0,
  110467. shadowsSaturation: 0,
  110468. shadowsExposure: 0,
  110469. midtonesHue: 0,
  110470. midtonesDensity: 0,
  110471. midtonesExposure: 0,
  110472. midtonesSaturation: 0,
  110473. highlightsHue: 0,
  110474. highlightsDensity: 0,
  110475. highlightsExposure: 0,
  110476. highlightsSaturation: 0
  110477. }
  110478. },
  110479. mainColor: {
  110480. r: 0.8823529411764706,
  110481. g: 0.8823529411764706,
  110482. b: 0.8823529411764706
  110483. }
  110484. },
  110485. loaderPlugins: {
  110486. extendedMaterial: true,
  110487. applyMaterialConfig: true,
  110488. msftLod: true,
  110489. telemetry: true
  110490. },
  110491. model: {
  110492. rotationOffsetAxis: {
  110493. x: 0,
  110494. y: -1,
  110495. z: 0
  110496. },
  110497. rotationOffsetAngle: babylonjs_1.Tools.ToRadians(210),
  110498. material: {
  110499. directEnabled: true,
  110500. directIntensity: 0.884,
  110501. emissiveIntensity: 1.04,
  110502. environmentIntensity: 0.6
  110503. },
  110504. entryAnimation: {
  110505. scaling: {
  110506. x: 0,
  110507. y: 0,
  110508. z: 0
  110509. },
  110510. time: 0.5,
  110511. easingFunction: 4,
  110512. easingMode: 1
  110513. },
  110514. exitAnimation: {
  110515. scaling: {
  110516. x: 0,
  110517. y: 0,
  110518. z: 0
  110519. },
  110520. time: 0.5,
  110521. easingFunction: 4,
  110522. easingMode: 1
  110523. },
  110524. normalize: true,
  110525. castShadow: true,
  110526. receiveShadows: true
  110527. },
  110528. lab: {
  110529. assetsRootURL: 'https://viewer.babylonjs.com/assets/environment/',
  110530. environmentMap: {
  110531. texture: "EnvMap_2.0-256.env",
  110532. rotationY: 3,
  110533. tintLevel: 0.4
  110534. },
  110535. defaultRenderingPipelines: {
  110536. bloomEnabled: true,
  110537. bloomThreshold: 1.0,
  110538. fxaaEnabled: true,
  110539. bloomWeight: 0.05
  110540. }
  110541. }
  110542. };
  110543. /***/ }),
  110544. /* 48 */
  110545. /***/ (function(module, exports, __webpack_require__) {
  110546. "use strict";
  110547. Object.defineProperty(exports, "__esModule", { value: true });
  110548. /**
  110549. * Defines a default directional shadow light for normalized objects (!)
  110550. */
  110551. exports.shadowDirectionalLightConfiguration = {
  110552. model: {
  110553. receiveShadows: true,
  110554. castShadow: true
  110555. },
  110556. ground: {
  110557. receiveShadows: true
  110558. },
  110559. lights: {
  110560. shadowDirectionalLight: {
  110561. type: 1,
  110562. shadowEnabled: true,
  110563. target: { x: 0, y: 0, z: 0.5 },
  110564. position: { x: 1.49, y: 2.39, z: -1.33 },
  110565. diffuse: { r: 0.867, g: 0.816, b: 0.788 },
  110566. intensity: 4.887,
  110567. intensityMode: 0,
  110568. shadowBufferSize: 1024,
  110569. shadowFrustumSize: 6.0,
  110570. shadowFieldOfView: 50.977,
  110571. shadowMinZ: 0.1,
  110572. shadowMaxZ: 10.0,
  110573. shadowConfig: {
  110574. blurKernel: 32,
  110575. useBlurCloseExponentialShadowMap: true
  110576. }
  110577. }
  110578. }
  110579. };
  110580. /**
  110581. * Defines a default shadow-enabled spot light for normalized objects.
  110582. */
  110583. exports.shadowSpotlLightConfiguration = {
  110584. model: {
  110585. receiveShadows: true,
  110586. castShadow: true
  110587. },
  110588. ground: {
  110589. receiveShadows: true
  110590. },
  110591. lights: {
  110592. shadowSpotLight: {
  110593. type: 2,
  110594. intensity: 2,
  110595. shadowEnabled: true,
  110596. target: { x: 0, y: 0, z: 0.5 },
  110597. position: { x: 0, y: 3.5, z: 3.7 },
  110598. angle: 1,
  110599. shadowOrthoScale: 0.5,
  110600. shadowBufferSize: 1024,
  110601. shadowMinZ: 0.1,
  110602. shadowMaxZ: 50.0,
  110603. shadowConfig: {
  110604. frustumEdgeFalloff: 0.5,
  110605. blurKernel: 32,
  110606. useBlurExponentialShadowMap: true
  110607. }
  110608. }
  110609. }
  110610. };
  110611. /***/ }),
  110612. /* 49 */
  110613. /***/ (function(module, exports, __webpack_require__) {
  110614. "use strict";
  110615. Object.defineProperty(exports, "__esModule", { value: true });
  110616. /**
  110617. * Lab-oriented default .env support
  110618. */
  110619. exports.environmentMapConfiguration = {
  110620. lab: {
  110621. assetsRootURL: '/assets/environment/',
  110622. environmentMap: {
  110623. texture: 'EnvMap_2.0-256.env',
  110624. rotationY: 0,
  110625. tintLevel: 0.4
  110626. }
  110627. }
  110628. };
  110629. /***/ }),
  110630. /* 50 */
  110631. /***/ (function(module, exports, __webpack_require__) {
  110632. "use strict";
  110633. Object.defineProperty(exports, "__esModule", { value: true });
  110634. var _1 = __webpack_require__(21);
  110635. /**
  110636. * This function will make sure the configuration file is taking deprecated fields into account
  110637. * and is setting them to the correct keys and values.
  110638. *
  110639. * @param configuration The configuration to process. Mutable!
  110640. */
  110641. function processConfigurationCompatibility(configuration) {
  110642. if (configuration.camera) {
  110643. // camera contrast -> image processing contrast
  110644. if (configuration.camera.contrast !== undefined) {
  110645. setKeyInObject(configuration, "scene.imageProcessingConfiguration.contrast", configuration.camera.contrast);
  110646. }
  110647. // camera exposure -> image processing exposure
  110648. if (configuration.camera.exposure !== undefined) {
  110649. setKeyInObject(configuration, "scene.imageProcessingConfiguration.exposure", configuration.camera.exposure);
  110650. }
  110651. }
  110652. if (configuration.scene) {
  110653. //glow
  110654. if (configuration.scene.glow) {
  110655. setKeyInObject(configuration, "lab.defaultRenderingPipelines.glowLayerEnabled", true);
  110656. var enabledProcessing = _1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", configuration);
  110657. if (enabledProcessing !== false) {
  110658. setKeyInObject(configuration, "scene.imageProcessingConfiguration.isEnabled", true);
  110659. }
  110660. }
  110661. }
  110662. }
  110663. exports.processConfigurationCompatibility = processConfigurationCompatibility;
  110664. function setKeyInObject(object, keys, value, shouldOverwrite) {
  110665. var keySplit = keys.split(".");
  110666. if (keySplit.length === 0)
  110667. return;
  110668. var lastKey = keySplit.pop();
  110669. if (!lastKey)
  110670. return;
  110671. var curObj = object;
  110672. keySplit.forEach(function (key) {
  110673. curObj[key] = curObj[key] || {};
  110674. curObj = curObj[key];
  110675. });
  110676. if (curObj[lastKey] !== undefined && !shouldOverwrite)
  110677. return;
  110678. curObj[lastKey] = value;
  110679. }
  110680. /***/ }),
  110681. /* 51 */
  110682. /***/ (function(module, exports, __webpack_require__) {
  110683. "use strict";
  110684. Object.defineProperty(exports, "__esModule", { value: true });
  110685. var telemetryLoaderPlugin_1 = __webpack_require__(52);
  110686. var msftLodLoaderPlugin_1 = __webpack_require__(53);
  110687. var applyMaterialConfig_1 = __webpack_require__(54);
  110688. var extendedMaterialLoaderPlugin_1 = __webpack_require__(55);
  110689. var pluginCache = {};
  110690. /**
  110691. * Get a loader plugin according to its name.
  110692. * The plugin will be cached and will be reused if called for again.
  110693. *
  110694. * @param name the name of the plugin
  110695. */
  110696. function getLoaderPluginByName(name) {
  110697. if (!pluginCache[name]) {
  110698. switch (name) {
  110699. case 'telemetry':
  110700. pluginCache[name] = new telemetryLoaderPlugin_1.TelemetryLoaderPlugin();
  110701. break;
  110702. case 'msftLod':
  110703. pluginCache[name] = new msftLodLoaderPlugin_1.MSFTLodLoaderPlugin();
  110704. break;
  110705. case 'applyMaterialConfig':
  110706. pluginCache[name] = new applyMaterialConfig_1.ApplyMaterialConfigPlugin();
  110707. break;
  110708. case 'extendedMaterial':
  110709. pluginCache[name] = new extendedMaterialLoaderPlugin_1.ExtendedMaterialLoaderPlugin();
  110710. break;
  110711. }
  110712. }
  110713. return pluginCache[name];
  110714. }
  110715. exports.getLoaderPluginByName = getLoaderPluginByName;
  110716. /***/ }),
  110717. /* 52 */
  110718. /***/ (function(module, exports, __webpack_require__) {
  110719. "use strict";
  110720. Object.defineProperty(exports, "__esModule", { value: true });
  110721. var telemetryManager_1 = __webpack_require__(5);
  110722. var babylonjs_1 = __webpack_require__(0);
  110723. var TelemetryLoaderPlugin = /** @class */ (function () {
  110724. function TelemetryLoaderPlugin() {
  110725. }
  110726. TelemetryLoaderPlugin.prototype.onInit = function (loader, model) {
  110727. this._model = model;
  110728. this._loadStart = babylonjs_1.Tools.Now;
  110729. };
  110730. TelemetryLoaderPlugin.prototype.onLoaded = function (model) {
  110731. telemetryManager_1.telemetryManager.broadcast("Model Loaded", model.getViewer(), {
  110732. model: model,
  110733. loadTime: babylonjs_1.Tools.Now - this._loadStart
  110734. });
  110735. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.getViewer());
  110736. };
  110737. TelemetryLoaderPlugin.prototype.onError = function (message, exception) {
  110738. this._loadEnd = babylonjs_1.Tools.Now;
  110739. telemetryManager_1.telemetryManager.broadcast("Load Error", this._model.getViewer(), {
  110740. model: this._model,
  110741. loadTime: this._loadEnd - this._loadStart
  110742. });
  110743. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.getViewer());
  110744. };
  110745. TelemetryLoaderPlugin.prototype.onComplete = function () {
  110746. this._loadEnd = babylonjs_1.Tools.Now;
  110747. telemetryManager_1.telemetryManager.broadcast("Load Complete", this._model.getViewer(), {
  110748. model: this._model,
  110749. loadTime: this._loadEnd - this._loadStart
  110750. });
  110751. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.getViewer());
  110752. };
  110753. return TelemetryLoaderPlugin;
  110754. }());
  110755. exports.TelemetryLoaderPlugin = TelemetryLoaderPlugin;
  110756. /***/ }),
  110757. /* 53 */
  110758. /***/ (function(module, exports, __webpack_require__) {
  110759. "use strict";
  110760. Object.defineProperty(exports, "__esModule", { value: true });
  110761. /**
  110762. * A loder plugin to use MSFT_lod extension correctly (glTF)
  110763. */
  110764. var MSFTLodLoaderPlugin = /** @class */ (function () {
  110765. function MSFTLodLoaderPlugin() {
  110766. }
  110767. MSFTLodLoaderPlugin.prototype.onInit = function (loader, model) {
  110768. this._model = model;
  110769. };
  110770. MSFTLodLoaderPlugin.prototype.onExtensionLoaded = function (extension) {
  110771. if (extension.name === "MSFT_lod" && this._model.configuration.loaderConfiguration) {
  110772. var MSFT_lod = extension;
  110773. MSFT_lod.enabled = !!this._model.configuration.loaderConfiguration.progressiveLoading;
  110774. MSFT_lod.maxLODsToLoad = this._model.configuration.loaderConfiguration.maxLODsToLoad || Number.MAX_VALUE;
  110775. }
  110776. };
  110777. return MSFTLodLoaderPlugin;
  110778. }());
  110779. exports.MSFTLodLoaderPlugin = MSFTLodLoaderPlugin;
  110780. /***/ }),
  110781. /* 54 */
  110782. /***/ (function(module, exports, __webpack_require__) {
  110783. "use strict";
  110784. Object.defineProperty(exports, "__esModule", { value: true });
  110785. /**
  110786. * Force-apply material configuration right after a material was loaded.
  110787. */
  110788. var ApplyMaterialConfigPlugin = /** @class */ (function () {
  110789. function ApplyMaterialConfigPlugin() {
  110790. }
  110791. ApplyMaterialConfigPlugin.prototype.onInit = function (loader, model) {
  110792. this._model = model;
  110793. };
  110794. ApplyMaterialConfigPlugin.prototype.onMaterialLoaded = function (material) {
  110795. this._model && this._model._applyModelMaterialConfiguration(material);
  110796. };
  110797. return ApplyMaterialConfigPlugin;
  110798. }());
  110799. exports.ApplyMaterialConfigPlugin = ApplyMaterialConfigPlugin;
  110800. /***/ }),
  110801. /* 55 */
  110802. /***/ (function(module, exports, __webpack_require__) {
  110803. "use strict";
  110804. Object.defineProperty(exports, "__esModule", { value: true });
  110805. var babylonjs_1 = __webpack_require__(0);
  110806. /**
  110807. * A (PBR) material will be extended using this function.
  110808. * This function will hold extra default configuration for the viewer, if not implemented in Babylon itself.
  110809. */
  110810. var ExtendedMaterialLoaderPlugin = /** @class */ (function () {
  110811. function ExtendedMaterialLoaderPlugin() {
  110812. }
  110813. ExtendedMaterialLoaderPlugin.prototype.onMaterialLoaded = function (baseMaterial) {
  110814. var material = baseMaterial;
  110815. material.alphaMode = babylonjs_1.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  110816. };
  110817. return ExtendedMaterialLoaderPlugin;
  110818. }());
  110819. exports.ExtendedMaterialLoaderPlugin = ExtendedMaterialLoaderPlugin;
  110820. /***/ }),
  110821. /* 56 */
  110822. /***/ (function(module, exports, __webpack_require__) {
  110823. /*!
  110824. * PEP v0.4.3 | https://github.com/jquery/PEP
  110825. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  110826. */
  110827. !function(a,b){ true?module.exports=b():"function"==typeof define&&define.amd?define(b):a.PointerEventsPolyfill=b()}(this,function(){"use strict";function a(a,b){b=b||Object.create(null);var c=document.createEvent("Event");c.initEvent(a,b.bubbles||!1,b.cancelable||!1);
  110828. // define inherited MouseEvent properties
  110829. // skip bubbles and cancelable since they're set above in initEvent()
  110830. for(var d,e=2;e<m.length;e++)d=m[e],c[d]=b[d]||n[e];c.buttons=b.buttons||0;
  110831. // Spec requires that pointers without pressure specified use 0.5 for down
  110832. // state and 0 for up state.
  110833. var f=0;
  110834. // add x/y properties aliased to clientX/Y
  110835. // define the properties of the PointerEvent interface
  110836. return f=b.pressure&&c.buttons?b.pressure:c.buttons?.5:0,c.x=c.clientX,c.y=c.clientY,c.pointerId=b.pointerId||0,c.width=b.width||0,c.height=b.height||0,c.pressure=f,c.tiltX=b.tiltX||0,c.tiltY=b.tiltY||0,c.twist=b.twist||0,c.tangentialPressure=b.tangentialPressure||0,c.pointerType=b.pointerType||"",c.hwTimestamp=b.hwTimestamp||0,c.isPrimary=b.isPrimary||!1,c}function b(){this.array=[],this.size=0}function c(a,b,c,d){this.addCallback=a.bind(d),this.removeCallback=b.bind(d),this.changedCallback=c.bind(d),A&&(this.observer=new A(this.mutationWatcher.bind(this)))}function d(a){return"body /shadow-deep/ "+e(a)}function e(a){return'[touch-action="'+a+'"]'}function f(a){return"{ -ms-touch-action: "+a+"; touch-action: "+a+"; }"}function g(){if(F){D.forEach(function(a){String(a)===a?(E+=e(a)+f(a)+"\n",G&&(E+=d(a)+f(a)+"\n")):(E+=a.selectors.map(e)+f(a.rule)+"\n",G&&(E+=a.selectors.map(d)+f(a.rule)+"\n"))});var a=document.createElement("style");a.textContent=E,document.head.appendChild(a)}}function h(){
  110837. // only activate if this platform does not have pointer events
  110838. if(!window.PointerEvent){if(window.PointerEvent=a,window.navigator.msPointerEnabled){var b=window.navigator.msMaxTouchPoints;Object.defineProperty(window.navigator,"maxTouchPoints",{value:b,enumerable:!0}),u.registerSource("ms",_)}else Object.defineProperty(window.navigator,"maxTouchPoints",{value:0,enumerable:!0}),u.registerSource("mouse",N),void 0!==window.ontouchstart&&u.registerSource("touch",V);u.register(document)}}function i(a){if(!u.pointermap.has(a)){var b=new Error("InvalidPointerId");throw b.name="InvalidPointerId",b}}function j(a){for(var b=a.parentNode;b&&b!==a.ownerDocument;)b=b.parentNode;if(!b){var c=new Error("InvalidStateError");throw c.name="InvalidStateError",c}}function k(a){var b=u.pointermap.get(a);return 0!==b.buttons}function l(){window.Element&&!Element.prototype.setPointerCapture&&Object.defineProperties(Element.prototype,{setPointerCapture:{value:W},releasePointerCapture:{value:X},hasPointerCapture:{value:Y}})}/**
  110839. * This is the constructor for new PointerEvents.
  110840. *
  110841. * New Pointer Events must be given a type, and an optional dictionary of
  110842. * initialization properties.
  110843. *
  110844. * Due to certain platform requirements, events returned from the constructor
  110845. * identify as MouseEvents.
  110846. *
  110847. * @constructor
  110848. * @param {String} inType The type of the event to create.
  110849. * @param {Object} [inDict] An optional dictionary of initial event properties.
  110850. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  110851. */
  110852. var m=["bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget","pageX","pageY"],n=[!1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,0,0],o=window.Map&&window.Map.prototype.forEach,p=o?Map:b;b.prototype={set:function(a,b){return void 0===b?this["delete"](a):(this.has(a)||this.size++,void(this.array[a]=b))},has:function(a){return void 0!==this.array[a]},"delete":function(a){this.has(a)&&(delete this.array[a],this.size--)},get:function(a){return this.array[a]},clear:function(){this.array.length=0,this.size=0},
  110853. // return value, key, map
  110854. forEach:function(a,b){return this.array.forEach(function(c,d){a.call(b,c,d,this)},this)}};var q=[
  110855. // MouseEvent
  110856. "bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget",
  110857. // DOM Level 3
  110858. "buttons",
  110859. // PointerEvent
  110860. "pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary",
  110861. // event instance
  110862. "type","target","currentTarget","which","pageX","pageY","timeStamp"],r=[
  110863. // MouseEvent
  110864. !1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,
  110865. // DOM Level 3
  110866. 0,
  110867. // PointerEvent
  110868. 0,0,0,0,0,0,"",0,!1,
  110869. // event instance
  110870. "",null,null,0,0,0,0],s={pointerover:1,pointerout:1,pointerenter:1,pointerleave:1},t="undefined"!=typeof SVGElementInstance,u={pointermap:new p,eventMap:Object.create(null),captureInfo:Object.create(null),
  110871. // Scope objects for native events.
  110872. // This exists for ease of testing.
  110873. eventSources:Object.create(null),eventSourceList:[],/**
  110874. * Add a new event source that will generate pointer events.
  110875. *
  110876. * `inSource` must contain an array of event names named `events`, and
  110877. * functions with the names specified in the `events` array.
  110878. * @param {string} name A name for the event source
  110879. * @param {Object} source A new source of platform events.
  110880. */
  110881. registerSource:function(a,b){var c=b,d=c.events;d&&(d.forEach(function(a){c[a]&&(this.eventMap[a]=c[a].bind(c))},this),this.eventSources[a]=c,this.eventSourceList.push(c))},register:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  110882. // call eventsource register
  110883. b.register.call(b,a)},unregister:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  110884. // call eventsource register
  110885. b.unregister.call(b,a)},contains:/*scope.external.contains || */function(a,b){try{return a.contains(b)}catch(c){
  110886. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  110887. return!1}},
  110888. // EVENTS
  110889. down:function(a){a.bubbles=!0,this.fireEvent("pointerdown",a)},move:function(a){a.bubbles=!0,this.fireEvent("pointermove",a)},up:function(a){a.bubbles=!0,this.fireEvent("pointerup",a)},enter:function(a){a.bubbles=!1,this.fireEvent("pointerenter",a)},leave:function(a){a.bubbles=!1,this.fireEvent("pointerleave",a)},over:function(a){a.bubbles=!0,this.fireEvent("pointerover",a)},out:function(a){a.bubbles=!0,this.fireEvent("pointerout",a)},cancel:function(a){a.bubbles=!0,this.fireEvent("pointercancel",a)},leaveOut:function(a){this.out(a),this.propagate(a,this.leave,!1)},enterOver:function(a){this.over(a),this.propagate(a,this.enter,!0)},
  110890. // LISTENER LOGIC
  110891. eventHandler:function(a){
  110892. // This is used to prevent multiple dispatch of pointerevents from
  110893. // platform events. This can happen when two elements in different scopes
  110894. // are set up to create pointer events, which is relevant to Shadow DOM.
  110895. if(!a._handledByPE){var b=a.type,c=this.eventMap&&this.eventMap[b];c&&c(a),a._handledByPE=!0}},
  110896. // set up event listeners
  110897. listen:function(a,b){b.forEach(function(b){this.addEvent(a,b)},this)},
  110898. // remove event listeners
  110899. unlisten:function(a,b){b.forEach(function(b){this.removeEvent(a,b)},this)},addEvent:/*scope.external.addEvent || */function(a,b){a.addEventListener(b,this.boundHandler)},removeEvent:/*scope.external.removeEvent || */function(a,b){a.removeEventListener(b,this.boundHandler)},
  110900. // EVENT CREATION AND TRACKING
  110901. /**
  110902. * Creates a new Event of type `inType`, based on the information in
  110903. * `inEvent`.
  110904. *
  110905. * @param {string} inType A string representing the type of event to create
  110906. * @param {Event} inEvent A platform event with a target
  110907. * @return {Event} A PointerEvent of type `inType`
  110908. */
  110909. makeEvent:function(b,c){
  110910. // relatedTarget must be null if pointer is captured
  110911. this.captureInfo[c.pointerId]&&(c.relatedTarget=null);var d=new a(b,c);return c.preventDefault&&(d.preventDefault=c.preventDefault),d._target=d._target||c.target,d},
  110912. // make and dispatch an event in one call
  110913. fireEvent:function(a,b){var c=this.makeEvent(a,b);return this.dispatchEvent(c)},/**
  110914. * Returns a snapshot of inEvent, with writable properties.
  110915. *
  110916. * @param {Event} inEvent An event that contains properties to copy.
  110917. * @return {Object} An object containing shallow copies of `inEvent`'s
  110918. * properties.
  110919. */
  110920. cloneEvent:function(a){for(var b,c=Object.create(null),d=0;d<q.length;d++)b=q[d],c[b]=a[b]||r[d],
  110921. // Work around SVGInstanceElement shadow tree
  110922. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  110923. // This is the behavior implemented by Firefox.
  110924. !t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement);
  110925. // keep the semantics of preventDefault
  110926. return a.preventDefault&&(c.preventDefault=function(){a.preventDefault()}),c},getTarget:function(a){var b=this.captureInfo[a.pointerId];return b?a._target!==b&&a.type in s?void 0:b:a._target},propagate:function(a,b,c){
  110927. // Order of conditions due to document.contains() missing in IE.
  110928. for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);)
  110929. // Touch: Do not propagate if node is detached.
  110930. if(e.push(d),d=d.parentNode,!d)return;c&&e.reverse(),e.forEach(function(c){a.target=c,b.call(this,a)},this)},setCapture:function(b,c,d){this.captureInfo[b]&&this.releaseCapture(b,d),this.captureInfo[b]=c,this.implicitRelease=this.releaseCapture.bind(this,b,d),document.addEventListener("pointerup",this.implicitRelease),document.addEventListener("pointercancel",this.implicitRelease);var e=new a("gotpointercapture");e.pointerId=b,e._target=c,d||this.asyncDispatchEvent(e)},releaseCapture:function(b,c){var d=this.captureInfo[b];if(d){this.captureInfo[b]=void 0,document.removeEventListener("pointerup",this.implicitRelease),document.removeEventListener("pointercancel",this.implicitRelease);var e=new a("lostpointercapture");e.pointerId=b,e._target=d,c||this.asyncDispatchEvent(e)}},/**
  110931. * Dispatches the event to its target.
  110932. *
  110933. * @param {Event} inEvent The event to be dispatched.
  110934. * @return {Boolean} True if an event handler returns true, false otherwise.
  110935. */
  110936. dispatchEvent:/*scope.external.dispatchEvent || */function(a){var b=this.getTarget(a);if(b)return b.dispatchEvent(a)},asyncDispatchEvent:function(a){requestAnimationFrame(this.dispatchEvent.bind(this,a))}};u.boundHandler=u.eventHandler.bind(u);var v={shadow:function(a){if(a)return a.shadowRoot||a.webkitShadowRoot},canTarget:function(a){return a&&Boolean(a.elementFromPoint)},targetingShadow:function(a){var b=this.shadow(a);if(this.canTarget(b))return b},olderShadow:function(a){var b=a.olderShadowRoot;if(!b){var c=a.querySelector("shadow");c&&(b=c.olderShadowRoot)}return b},allShadows:function(a){for(var b=[],c=this.shadow(a);c;)b.push(c),c=this.olderShadow(c);return b},searchRoot:function(a,b,c){if(a){var d,e,f=a.elementFromPoint(b,c);for(
  110937. // is element a shadow host?
  110938. e=this.targetingShadow(f);e;){if(
  110939. // find the the element inside the shadow root
  110940. d=e.elementFromPoint(b,c)){
  110941. // shadowed element may contain a shadow root
  110942. var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d}
  110943. // check for older shadows
  110944. e=this.olderShadow(e)}
  110945. // light dom element is the target
  110946. return f}},owner:function(a){
  110947. // walk up until you hit the shadow root or document
  110948. for(var b=a;b.parentNode;)b=b.parentNode;
  110949. // the owner element is expected to be a Document or ShadowRoot
  110950. return b.nodeType!==Node.DOCUMENT_NODE&&b.nodeType!==Node.DOCUMENT_FRAGMENT_NODE&&(b=document),b},findTarget:function(a){var b=a.clientX,c=a.clientY,d=this.owner(a.target);
  110951. // if x, y is not in this root, fall back to document search
  110952. return d.elementFromPoint(b,c)||(d=document),this.searchRoot(d,b,c)}},w=Array.prototype.forEach.call.bind(Array.prototype.forEach),x=Array.prototype.map.call.bind(Array.prototype.map),y=Array.prototype.slice.call.bind(Array.prototype.slice),z=Array.prototype.filter.call.bind(Array.prototype.filter),A=window.MutationObserver||window.WebKitMutationObserver,B="[touch-action]",C={subtree:!0,childList:!0,attributes:!0,attributeOldValue:!0,attributeFilter:["touch-action"]};c.prototype={watchSubtree:function(a){
  110953. // Only watch scopes that can target find, as these are top-level.
  110954. // Otherwise we can see duplicate additions and removals that add noise.
  110955. //
  110956. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  110957. // a removal without an insertion when a node is redistributed among
  110958. // shadows. Since it all ends up correct in the document, watching only
  110959. // the document will yield the correct mutations to watch.
  110960. this.observer&&v.canTarget(a)&&this.observer.observe(a,C)},enableOnSubtree:function(a){this.watchSubtree(a),a===document&&"complete"!==document.readyState?this.installOnLoad():this.installNewSubtree(a)},installNewSubtree:function(a){w(this.findElements(a),this.addElement,this)},findElements:function(a){return a.querySelectorAll?a.querySelectorAll(B):[]},removeElement:function(a){this.removeCallback(a)},addElement:function(a){this.addCallback(a)},elementChanged:function(a,b){this.changedCallback(a,b)},concatLists:function(a,b){return a.concat(y(b))},
  110961. // register all touch-action = none nodes on document load
  110962. installOnLoad:function(){document.addEventListener("readystatechange",function(){"complete"===document.readyState&&this.installNewSubtree(document)}.bind(this))},isElement:function(a){return a.nodeType===Node.ELEMENT_NODE},flattenMutationTree:function(a){
  110963. // find children with touch-action
  110964. var b=x(a,this.findElements,this);
  110965. // flatten the list
  110966. // make sure the added nodes are accounted for
  110967. return b.push(z(a,this.isElement)),b.reduce(this.concatLists,[])},mutationWatcher:function(a){a.forEach(this.mutationHandler,this)},mutationHandler:function(a){if("childList"===a.type){var b=this.flattenMutationTree(a.addedNodes);b.forEach(this.addElement,this);var c=this.flattenMutationTree(a.removedNodes);c.forEach(this.removeElement,this)}else"attributes"===a.type&&this.elementChanged(a.target,a.oldValue)}};var D=["none","auto","pan-x","pan-y",{rule:"pan-x pan-y",selectors:["pan-x pan-y","pan-y pan-x"]}],E="",F=window.PointerEvent||window.MSPointerEvent,G=!window.ShadowDOMPolyfill&&document.head.createShadowRoot,H=u.pointermap,I=25,J=[1,4,2,8,16],K=!1;try{K=1===new MouseEvent("test",{buttons:1}).buttons}catch(L){}
  110968. // handler block for native mouse events
  110969. var M,N={POINTER_ID:1,POINTER_TYPE:"mouse",events:["mousedown","mousemove","mouseup","mouseover","mouseout"],register:function(a){u.listen(a,this.events)},unregister:function(a){u.unlisten(a,this.events)},lastTouches:[],
  110970. // collide with the global mouse listener
  110971. isEventSimulatedFromTouch:function(a){for(var b,c=this.lastTouches,d=a.clientX,e=a.clientY,f=0,g=c.length;f<g&&(b=c[f]);f++){
  110972. // simulated mouse events will be swallowed near a primary touchend
  110973. var h=Math.abs(d-b.x),i=Math.abs(e-b.y);if(h<=I&&i<=I)return!0}},prepareEvent:function(a){var b=u.cloneEvent(a),c=b.preventDefault;return b.preventDefault=function(){a.preventDefault(),c()},b.pointerId=this.POINTER_ID,b.isPrimary=!0,b.pointerType=this.POINTER_TYPE,b},prepareButtonsForMove:function(a,b){var c=H.get(this.POINTER_ID);
  110974. // Update buttons state after possible out-of-document mouseup.
  110975. 0!==b.which&&c?a.buttons=c.buttons:a.buttons=0,b.buttons=a.buttons},mousedown:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=H.get(this.POINTER_ID),c=this.prepareEvent(a);K||(c.buttons=J[c.button],b&&(c.buttons|=b.buttons),a.buttons=c.buttons),H.set(this.POINTER_ID,a),b&&0!==b.buttons?u.move(c):u.down(c)}},mousemove:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);K||this.prepareButtonsForMove(b,a),b.button=-1,H.set(this.POINTER_ID,a),u.move(b)}},mouseup:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=H.get(this.POINTER_ID),c=this.prepareEvent(a);if(!K){var d=J[c.button];
  110976. // Produces wrong state of buttons in Browsers without `buttons` support
  110977. // when a mouse button that was pressed outside the document is released
  110978. // inside and other buttons are still pressed down.
  110979. c.buttons=b?b.buttons&~d:0,a.buttons=c.buttons}H.set(this.POINTER_ID,a),
  110980. // Support: Firefox <=44 only
  110981. // FF Ubuntu includes the lifted button in the `buttons` property on
  110982. // mouseup.
  110983. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  110984. c.buttons&=~J[c.button],0===c.buttons?u.up(c):u.move(c)}},mouseover:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);K||this.prepareButtonsForMove(b,a),b.button=-1,H.set(this.POINTER_ID,a),u.enterOver(b)}},mouseout:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);K||this.prepareButtonsForMove(b,a),b.button=-1,u.leaveOut(b)}},cancel:function(a){var b=this.prepareEvent(a);u.cancel(b),this.deactivateMouse()},deactivateMouse:function(){H["delete"](this.POINTER_ID)}},O=u.captureInfo,P=v.findTarget.bind(v),Q=v.allShadows.bind(v),R=u.pointermap,S=2500,T=200,U="touch-action",V={events:["touchstart","touchmove","touchend","touchcancel"],register:function(a){M.enableOnSubtree(a)},unregister:function(){},elementAdded:function(a){var b=a.getAttribute(U),c=this.touchActionToScrollType(b);c&&(a._scrollType=c,u.listen(a,this.events),
  110985. // set touch-action on shadows as well
  110986. Q(a).forEach(function(a){a._scrollType=c,u.listen(a,this.events)},this))},elementRemoved:function(a){a._scrollType=void 0,u.unlisten(a,this.events),
  110987. // remove touch-action from shadow
  110988. Q(a).forEach(function(a){a._scrollType=void 0,u.unlisten(a,this.events)},this)},elementChanged:function(a,b){var c=a.getAttribute(U),d=this.touchActionToScrollType(c),e=this.touchActionToScrollType(b);
  110989. // simply update scrollType if listeners are already established
  110990. d&&e?(a._scrollType=d,Q(a).forEach(function(a){a._scrollType=d},this)):e?this.elementRemoved(a):d&&this.elementAdded(a)},scrollTypes:{EMITTER:"none",XSCROLLER:"pan-x",YSCROLLER:"pan-y",SCROLLER:/^(?:pan-x pan-y)|(?:pan-y pan-x)|auto$/},touchActionToScrollType:function(a){var b=a,c=this.scrollTypes;return"none"===b?"none":b===c.XSCROLLER?"X":b===c.YSCROLLER?"Y":c.SCROLLER.exec(b)?"XY":void 0},POINTER_TYPE:"touch",firstTouch:null,isPrimaryTouch:function(a){return this.firstTouch===a.identifier},setPrimaryTouch:function(a){
  110991. // set primary touch if there no pointers, or the only pointer is the mouse
  110992. (0===R.size||1===R.size&&R.has(1))&&(this.firstTouch=a.identifier,this.firstXY={X:a.clientX,Y:a.clientY},this.scrolling=!1,this.cancelResetClickCount())},removePrimaryPointer:function(a){a.isPrimary&&(this.firstTouch=null,this.firstXY=null,this.resetClickCount())},clickCount:0,resetId:null,resetClickCount:function(){var a=function(){this.clickCount=0,this.resetId=null}.bind(this);this.resetId=setTimeout(a,T)},cancelResetClickCount:function(){this.resetId&&clearTimeout(this.resetId)},typeToButtons:function(a){var b=0;return"touchstart"!==a&&"touchmove"!==a||(b=1),b},touchToPointer:function(a){var b=this.currentTouchEvent,c=u.cloneEvent(a),d=c.pointerId=a.identifier+2;c.target=O[d]||P(c),c.bubbles=!0,c.cancelable=!0,c.detail=this.clickCount,c.button=0,c.buttons=this.typeToButtons(b.type),c.width=2*(a.radiusX||a.webkitRadiusX||0),c.height=2*(a.radiusY||a.webkitRadiusY||0),c.pressure=a.force||a.webkitForce||.5,c.isPrimary=this.isPrimaryTouch(a),c.pointerType=this.POINTER_TYPE,
  110993. // forward modifier keys
  110994. c.altKey=b.altKey,c.ctrlKey=b.ctrlKey,c.metaKey=b.metaKey,c.shiftKey=b.shiftKey;
  110995. // forward touch preventDefaults
  110996. var e=this;return c.preventDefault=function(){e.scrolling=!1,e.firstXY=null,b.preventDefault()},c},processTouches:function(a,b){var c=a.changedTouches;this.currentTouchEvent=a;for(var d,e=0;e<c.length;e++)d=c[e],b.call(this,this.touchToPointer(d))},
  110997. // For single axis scrollers, determines whether the element should emit
  110998. // pointer events or behave as a scroller
  110999. shouldScroll:function(a){if(this.firstXY){var b,c=a.currentTarget._scrollType;if("none"===c)
  111000. // this element is a touch-action: none, should never scroll
  111001. b=!1;else if("XY"===c)
  111002. // this element should always scroll
  111003. b=!0;else{var d=a.changedTouches[0],e=c,f="Y"===c?"X":"Y",g=Math.abs(d["client"+e]-this.firstXY[e]),h=Math.abs(d["client"+f]-this.firstXY[f]);
  111004. // if delta in the scroll axis > delta other axis, scroll instead of
  111005. // making events
  111006. b=g>=h}return this.firstXY=null,b}},findTouch:function(a,b){for(var c,d=0,e=a.length;d<e&&(c=a[d]);d++)if(c.identifier===b)return!0},
  111007. // In some instances, a touchstart can happen without a touchend. This
  111008. // leaves the pointermap in a broken state.
  111009. // Therefore, on every touchstart, we remove the touches that did not fire a
  111010. // touchend event.
  111011. // To keep state globally consistent, we fire a
  111012. // pointercancel for this "abandoned" touch
  111013. vacuumTouches:function(a){var b=a.touches;
  111014. // pointermap.size should be < tl.length here, as the touchstart has not
  111015. // been processed yet.
  111016. if(R.size>=b.length){var c=[];R.forEach(function(a,d){
  111017. // Never remove pointerId == 1, which is mouse.
  111018. // Touch identifiers are 2 smaller than their pointerId, which is the
  111019. // index in pointermap.
  111020. if(1!==d&&!this.findTouch(b,d-2)){var e=a.out;c.push(e)}},this),c.forEach(this.cancelOut,this)}},touchstart:function(a){this.vacuumTouches(a),this.setPrimaryTouch(a.changedTouches[0]),this.dedupSynthMouse(a),this.scrolling||(this.clickCount++,this.processTouches(a,this.overDown))},overDown:function(a){R.set(a.pointerId,{target:a.target,out:a,outTarget:a.target}),u.enterOver(a),u.down(a)},touchmove:function(a){this.scrolling||(this.shouldScroll(a)?(this.scrolling=!0,this.touchcancel(a)):(a.preventDefault(),this.processTouches(a,this.moveOverOut)))},moveOverOut:function(a){var b=a,c=R.get(b.pointerId);
  111021. // a finger drifted off the screen, ignore it
  111022. if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e,
  111023. // recover from retargeting by shadow
  111024. d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):(
  111025. // clean up case when finger leaves the screen
  111026. b.target=e,b.relatedTarget=null,this.cancelOut(b))),c.out=b,c.outTarget=b.target}},touchend:function(a){this.dedupSynthMouse(a),this.processTouches(a,this.upOut)},upOut:function(a){this.scrolling||(u.up(a),u.leaveOut(a)),this.cleanUpPointer(a)},touchcancel:function(a){this.processTouches(a,this.cancelOut)},cancelOut:function(a){u.cancel(a),u.leaveOut(a),this.cleanUpPointer(a)},cleanUpPointer:function(a){R["delete"](a.pointerId),this.removePrimaryPointer(a)},
  111027. // prevent synth mouse events from creating pointer events
  111028. dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0];
  111029. // only the primary finger will synth mouse events
  111030. if(this.isPrimaryTouch(c)){
  111031. // remember x/y of last touch
  111032. var d={x:c.clientX,y:c.clientY};b.push(d);var e=function(a,b){var c=a.indexOf(b);c>-1&&a.splice(c,1)}.bind(null,b,d);setTimeout(e,S)}}};M=new c(V.elementAdded,V.elementRemoved,V.elementChanged,V);var W,X,Y,Z=u.pointermap,$=window.MSPointerEvent&&"number"==typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE,_={events:["MSPointerDown","MSPointerMove","MSPointerUp","MSPointerOut","MSPointerOver","MSPointerCancel","MSGotPointerCapture","MSLostPointerCapture"],register:function(a){u.listen(a,this.events)},unregister:function(a){u.unlisten(a,this.events)},POINTER_TYPES:["","unavailable","touch","pen","mouse"],prepareEvent:function(a){var b=a;return $&&(b=u.cloneEvent(a),b.pointerType=this.POINTER_TYPES[a.pointerType]),b},cleanup:function(a){Z["delete"](a)},MSPointerDown:function(a){Z.set(a.pointerId,a);var b=this.prepareEvent(a);u.down(b)},MSPointerMove:function(a){var b=this.prepareEvent(a);u.move(b)},MSPointerUp:function(a){var b=this.prepareEvent(a);u.up(b),this.cleanup(a.pointerId)},MSPointerOut:function(a){var b=this.prepareEvent(a);u.leaveOut(b)},MSPointerOver:function(a){var b=this.prepareEvent(a);u.enterOver(b)},MSPointerCancel:function(a){var b=this.prepareEvent(a);u.cancel(b),this.cleanup(a.pointerId)},MSLostPointerCapture:function(a){var b=u.makeEvent("lostpointercapture",a);u.dispatchEvent(b)},MSGotPointerCapture:function(a){var b=u.makeEvent("gotpointercapture",a);u.dispatchEvent(b)}},aa=window.navigator;aa.msPointerEnabled?(W=function(a){i(a),j(this),k(a)&&(u.setCapture(a,this,!0),this.msSetPointerCapture(a))},X=function(a){i(a),u.releaseCapture(a,!0),this.msReleasePointerCapture(a)}):(W=function(a){i(a),j(this),k(a)&&u.setCapture(a,this)},X=function(a){i(a),u.releaseCapture(a)}),Y=function(a){return!!u.captureInfo[a]},g(),h(),l();var ba={dispatcher:u,Installer:c,PointerEvent:a,PointerMap:p,targetFinding:v};return ba});
  111033. /***/ }),
  111034. /* 57 */
  111035. /***/ (function(module, exports, __webpack_require__) {
  111036. "use strict";
  111037. Object.defineProperty(exports, "__esModule", { value: true });
  111038. var defaultViewer_1 = __webpack_require__(9);
  111039. var mappers_1 = __webpack_require__(3);
  111040. var _1 = __webpack_require__(6);
  111041. /**
  111042. * Will attach an init function the the DOMContentLoaded event.
  111043. * The init function will be removed automatically after the event was triggered.
  111044. */
  111045. function initListeners() {
  111046. document.addEventListener("DOMContentLoaded", init);
  111047. function init(event) {
  111048. document.removeEventListener("DOMContentLoaded", init);
  111049. if (_1.viewerGlobals.disableInit || _1.disableInit)
  111050. return;
  111051. InitTags();
  111052. }
  111053. }
  111054. exports.initListeners = initListeners;
  111055. /**
  111056. * Select all HTML tags on the page that match the selector and initialize a viewer
  111057. *
  111058. * @param selector the selector to initialize the viewer on (default is 'babylon')
  111059. */
  111060. function InitTags(selector) {
  111061. if (selector === void 0) { selector = 'babylon'; }
  111062. var elements = document.querySelectorAll(selector);
  111063. for (var i = 0; i < elements.length; ++i) {
  111064. var element = elements.item(i);
  111065. // get the html configuration
  111066. var configMapper = mappers_1.mapperManager.getMapper('dom');
  111067. var config = configMapper.map(element);
  111068. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  111069. }
  111070. }
  111071. exports.InitTags = InitTags;
  111072. /***/ })
  111073. /******/ ]);
  111074. return BabylonViewer;
  111075. });